# Question
Title: How many answers does this question have?
Write a program or a function that outputs the integer number of answers this question has. Your solution should still work as more answers are added.

Languages that run in a browser may be run from the js console while on this page. Otherwise, you'd probably have to download this page. Multi-language solutions, e.g. `wget`ing the page and parsing it using `grep` is ok. Just sum up the command line and all source used.

This is code golf; shortest answer in bytes wins.

EDIT:

Let's allow at most one occourance of the url of this page to not count, either as input or in the source. No url shorteners, no data stored as get parameters etc. Quotes around url, if needed, still count. Taking the url as input is also fine. If you want to remove some part of the url, e.g. `/how-many-answers...`, you can, but it probably doesn't help you.

# Answer
> 15 votes
## Javascript + jQuery, 23 bytes

```
_=>+$("h2>span").text()

```

# Answer
> 4 votes
# Mathematica, 33 bytes

```
Length@Import[#,"Data"][[4,2]]-1&

```

The input is the url of this page.

# Answer
> 4 votes
## Python 2, 120 bytes, 79 w/o URL

I can't say Python was made for this challenge.

```
import urllib
print[l for l in urllib.urlopen("http://codegolf.stackexchange.com/q/96298")if"answerCount"in l][0][83:-9]

```

Unfortunately, inline import is the same length :(

Any help with golfing this further would be greatly appreciated!

If the URL (a whopping 41 bytes—over 1/3 my byte count) can be taken as input, it is 82 bytes:

```
import urllib
lambda u:[l for l in urllib.urlopen(u)if"answerCount"in l][0][83:-9]

```

# Answer
> 3 votes
## Javascript, 67 bytes

```
alert($(".answers-subheader").children().first().children().html())

```

This look way too long

# Answer
> 3 votes
# Javascript (ES5), ~~46~~ ~~44~~ ~~40~~ ~~38~~ 33 bytes

```
_=>parseInt($('#answers').text())

```

5 bytes saved thanks to Ismael Miguel

**Note:** This is pretty slow, and won't work if you have the PPCG-Design userscript.

# Answer
> 3 votes
# CJam, 15 bytes

```
lg"2>"/1=A>S/0=

```

Expects this page's URL as input.

### How it works

```
l                e# Read a line (the URL) from STDIN.
 g               e# Fetch the resource the URL points to.
  "2>"/          e# Split the source at occurrences of "2>".
       1=        e# Select the second chunk, i.e., everything between the first
                 e# <h2> and the first </h2>.
         A>      e# Discard the first 10 characters (a linefeed and 9 tabs).
           S/0=  e# Split at spaces and select the first chunk.

```

# Answer
> 1 votes
# 171 bytes bash + 3 keys lynx

```
lynx -cfg=<(echo PRINTER:Answercount:grep [0-9]*.Answers %s|less:FALSE:999') http://codegolf.stackexchange.com/questions/96298/how-many-answers-does-this-question-have

```

# Answer
> 1 votes
## 99 bytes sh + curl + jq + stackexchange API

```
curl -s --compressed api.stackexchange.com/questions/96298/answers?site=codegolf|jq .items\|length

```

Using the API, I was able to avoid issues related to page formatting and html. Unfortunately, 60 bytes of my answer are the maximally golfed url for this particular api query, and another 13 bytes for curl to unzip the resulting of the query, because stackexchange refuses to serve uncompressed data via the api.

The actual "logic" comes from curling the api to ask for a json reply with the answers to this post. That is unzipped and then piped into jq, a json parser, which extracts the "items" array and outputs its length.

You can get impressively close to having the api just return the number of answers, but from what I could come up with you could not get 100% of the way there, and getting closer would cost more bytes than just passing it through jq.

## 101 bytes to return {"total":}:

```
curl -s --compressed api.stackexchange.com/questions/96298/answers?site=codegolf&filter=!)V)MSZJUgX_

```

The filter parameter in api queries is very powerful, but it falls just short of providing a "just curl a url" solution. There may be a middle ground here, where you can get a shorter response and then just count the lines or extract the number, but unfortunately filter strings are a set length, and the required jq command was already more efficient.

# Answer
> 1 votes
## PHP, 76 (Code) + 41 (URL) = 117 bytes

```
preg_match_all('<h2>(.*) answers<span',file_get_contents("http://codegolf.stackexchange.com/q/96298"),$o);
echo $o[0];

```

# Answer
> 1 votes
# Java, ~~230~~ 269-41=228 bytes

```
interface A{static void main(String[]a)throws Exception{System.out.print(new java.util.Scanner(new java.net.URL("http://codegolf.stackexchange.com/q/96298").openStream()).useDelimiter("\\Z").next().replaceAll("\n|\r","").replaceAll("^.+?\\s+(\\d+) Answers.+$","$1"));}}

```

(Only counts non-deleted answers)

# Answer
> 0 votes
## JavaScript + jQuery (already included in page), 20 bytes

```
+$('h2>span').text()

```

This is a program intended to be executed in the console for the current page (opened with `F12`). It outputs the number of answers, without quotation marks. It works in Chrome, Firefox, IE11, and Edge. It should work in other browsers, but I have only tested it in those listed.

Unlike other JavaScript solutions here, it is a program by itself rather than a function expression using ES6 arrow function notation. Also unlike those solutions, it actually produces output (without quotes) in the console with the number of answers (rather than just being a function expression which produces no output). Producing output relies on the feature in each browser's console that the value of an expression is output after that expression has been evaluated.

This relies on the only `<span>` on the page with a parent that is an `<h2>` element is the one containing the number of answers as its text content. After experimentation, this appears to be the case, and it does not appear possible to intentionally create an `<h2>` with a `<span>` child using the editor: all explicitly inserted `<span>` elements are stripped and no Markdown, as used on Stack Exchange, creates an actual `<span>` within an `<h2>`. If someone can demonstrate a case where the page can be manipulated such that `'h2>span'` selector is no longer unique, then this will need to be revised.

If evaluating to a string instead of a number is acceptable, then

## JavaScript + jQuery (already included in page), 19 bytes

```
$('h2>span').text()

```

However, while this does not evaluate to include `""`, in all tested consoles it produces output which is enclosed within `""`. I read Filip Haglund's comments on the question as precluding this output.

# Answer
> 0 votes
# R, 80 bytes

Answer is based on searching the vector returned by `readLines` using regular expressions. I'm guessing that this could be broken by text in comments/answers (possibly even my own). Will delete if so. Also the pattern could also be gofled but not sure if that would increase the likelihood of getting a false value.

```
x=readLines(scan(,""));regmatches(x,regexpr("(?<=answerCount\">).*?(?=<)",x,,T))

```

---
Tags: code-golf, internet
---


title: Permutation Numbering

text:
# Question
Title: Permutation Numbering
# The Challenge

For a given set of n integers, write a program which will output its lexicographic index.

# The Rules

* The input must only be a set of unique non-negative integers separated by spaces.
* You should output the lexicographic index (range 0 to n!-1 inclusive) of the permutation.
* No permutation libraries or permutation built-ins may be used.
* You may not generate the set of permutations or any subset of permutations of the input to help you find the index.
* You also can't increment or decrement the given permutation to the next/previous(lexicographically) permutation.
* Bonus points (-10 bytes) if you find some way to complete this without using factorials.
* Runtime should be less than 1 minute for n = 100
* Shortest code by byte count wins
* Winner chosen Tuesday (July 22, 2014)

# More About Permutations

# Examples

```
0 1 2 --> 0
0 2 1 --> 1
1 0 2 --> 2
1 2 0 --> 3
2 0 1 --> 4
2 1 0 --> 5
0 1 2 3 4 5 6 7 --> 0
0 1 2 3 4 5 7 6 --> 1
0 1 2 3 4 6 5 7 --> 2
1 3 5 17        --> 0
781 780 779 13  --> 23
81 62 19 12 11 8 2 0 --> 40319
195 124 719 1 51 6 3 --> 4181

```

# Answer
> 4 votes
### GolfScript, 12 (22 characters - 10 bonus)

```
~]0\.,{.,@*\.(@$?@+\}*

```

Bonus points for not using factorials. Input must be given on STDIN in the format desriped in the question. You can try the code online.

# Answer
> 4 votes
# CJam, 31, with factorials

```
q~]{__(f<0+:+\,,(;1+:**\(;}h]:+

```

# Answer
> 1 votes
# Cobra - 202

Obviously Cobra isn't really competing in this one.

```
class P
    var n=0
    var t=CobraCore.commandLineArgs[1:]
    def main
        .f(.t[0:0])
    def f(l as List<of String>)
        if.t.count==l.count,print if(.t<>l,'',.n+=1)
        else,for i in.t.sorted,if i not in l,.f(l+[i])

```

# Answer
> 1 votes
# Python 2 (77 = 87-10)

```
p=map(int,raw_input().split())
s=0
while p:s=s*len(p)+sorted(p).index(p.pop(0))
print s

```

Such readable. Much built-in. Wow.

We use the fact that the lexicographic index of a permutation is the sum over the elements of the permutations of the number of inversions above that element (values after it but below it) multiplied by the factorial of the number of elements after it. Rather than evaluate this polynomial-like expression term by term, we use something akin to Horner's method.

Rather then looping over array indices, we repeatedly remove the first element of the list and process the remaining elements. The expression `sorted(p).index(p.pop(0))` counts the number of inversions past the first index by taking its position in the sorted list, while at the same time doing the removal.

Sadly, I had to use Python 2 and take 4 more characters for `raw_input` (though -1 for `print`) because in Python 3 the `map(int,...)` produces a map object, which doesn't support list operations,

# Answer
> 1 votes
# Pyth (13 = 23-10)

```
JVPwdWJ=Z+*ZlJXovNJ;J)Z

```

A port of my Python answer.

A Python translation (with some irrelevant stuff filtered out):

```
Z=0
J=rev(split(input()," "))
while J:
 Z=plus(times(Z,len(J)),index(order(lambda N:eval(N),J),J.pop()))
print(Z)

```

The input numbers stay strings but are sorted as ints by using eval as the key. The list is reversed so that `pop` takes the the front rather than the back.

# Answer
> 0 votes
# J, 5 bytes (15 - 10)

```
#\.#.+/@(<{.)\.

```

This runs in *O*(*n*2) time and is able to handle *n* = 100 easily.

## Usage

```
   f =: #\.#.+/@(<{.)\.
   f 0 1 2
0
   f 0 2 1
1
   f 1 0 2
2
   f 1 2 0
3
   f 2 0 1
4
   f 2 1 0
5
   f 0 1 2 3 4 5 6 7
0
   f 0 1 2 3 4 5 7 6
1
   f 0 1 2 3 4 6 5 7
2
   f 1 3 5 17
0
   f 781 780 779 13
23
   f 81 62 19 12 11 8 2 0
40319
   f 195 124 719 1 51 6 3
4181
   NB. A. is the builtin for permutation indexing
   timex 'r =: f 927 A. i. 100'
0.000161
   r
927

```

## Explanation

```
#\.#.+/@(<{.)\.  Input: array P
             \.  For each suffix of P
          {.       Take the head
         <         Test if it is greater than each of that suffix
     +/@           Sum, count the number of times it is greater
#\.              Get the length of each suffix of P
   #.            Convert to decimal using a mixed radix

```

---
Tags: code-golf, math, combinatorics, set-theory, permutations
---


title: Help me with my Halloween decoration

text:
# Question
Title: Help me with my Halloween decoration
The Halloween is upon us, and I haven't decorated my house yet, so I gonna need your help to do this task

**Input**
The input will be a list of 4 digits numbers, where each digit represent a portion of decoration:

```
EMBU
||||
|||+-upper decoration
||+-bottom decoration
|+-mouth/nose
+-eyes

```

Eyes:
0 - `°`
1 - `¯`
2 - `-`
3 - `^`
4 - `'`

Mouth/Nose
0 - `v`
1 - `w`
2 - `o`
3 - `_`
4 - `-`

Bottom decoration
0 - nothing
1 - skeleton
2 - pumpkin

Upper decoration
0 - nothing
1 - flying bat
2 - resting bat
3 - spider

**Output**

Skeleton:
`(EME)`
` _|_ `
`/[|]\`
` |  `
` / \ `

Pumpkin
` , `
`(EME)`

Flying bat
` `
` ^"^ `

Resting bat
`  () `
`  ´` `

Spider
` | `
` .|. `
` :": `

* Each decoration has a 5 character width
* Upper decorations start from the top
* Lower decorations start from the bottom
* If the spider is over the pumpkin or there is no bottom decoration the web length will be 3, if it's over the skeleton, the web length will be 1
* When the bottom decoration is `0` the first 2 digits are irrelevant
* Between each decoration there will be an empty column

**Example**
Input
`3123 ??02 1021 0310`
Output

```
   |     ()
   |     ´`   ^"^
  .|.              (°_°)
  :":               _|_
                   /[|]\
   ,           ,     |
 (^w^)       (¯v¯)  / \

```

Trailing spaces at the end of each line are optional
Trailing newline at the end of the entire output is allowed

**Winning criteria**
This is so the shortest answer wins

# Answer
> 4 votes
## JavaScript (ES6), ~~319~~ 315 bytes

```
let f =

s=>[0,1].map(i=>s.map(([A,B,C,D],x)=>+(z=i?D:C)&&[...'01/21/5015/41211/91/65'.split`/`[z-(i?C+D-13?1:-2:-2)]].map((n,y)=>a[(i?y:6-y)*4+x]=' '+('      ^"^   ()   ´`  / \\   |   .|. /[|]\\ _|_ ('+(e='°¯-^'[A])+'vwo_-'[B]+e+')  ,   :": ').substr(p+=n*5,5),p=0)),a=Array(28).fill`      `)&&a.join``.match(/.{24}/g).join`
`

console.log(f(["3123","0002","1021","0310"]));
```

# Answer
> 5 votes
# Java, ~~829~~, 798

Yeah. Substantially improved thanks to Kevin Cruijssen and corvus\_192.

```
s->{String[]e=s.split(" ");char c[][]=new char[8][e.length*6],t,u,h='|';int y,x=2,i=0,j;for(String l:e){y=0;char[]p=l.toCharArray(),z=c[y];int a=p[0],b=p[1],f=p[2],d=p[3],k=x-1,m=x+1;t=a<49?'°':a<50?'¯':a<51?45:a<52?'^':39;u=(char)(b<50?b+70:b<51?111:b<52?95:39);if(d>50){z[x]=h;if(f!=49){y=2;c[1][x]=h;c[2][x]=h;}z=c[y];z[k]=46;z[m]=46;z=c[++y];z[k]=58;z[m]=58;z[x]=34;}if(d==50){z[x]=40;z[m]=41;c[++y][x]='´';c[y][m]=96;}if(d==49){z=c[++y];z[k]=94;z[x]=34;z[m]=94;}if(f>49){y=6;c[y][x]=44;}if(f>48){y=f>49?7:3;z=c[y++];z[x]=u;z[k]=t;z[m]=t;z[x-2]=40;z[x+2]=41;}if(f==49){z=c[y++];z[x]=h;z[k]=95;z[m]=95;z=c[y];z[x]=h;z[k]=91;z[m]=93;z[x-2]=47;c[y++][x+2]=92;c[y++][x]=h;c[y][k]=47;c[y][m]=92;}x+=6;}for(;i<8;i++){s="";for(j=0;j<c[0].length;){t=c[i][j++];s+=t<1?' ':t;}System.out.println(s);}};

```

the ungolfed version

```
static void makeDecorations(String s){
    String[]e=s.split(" ");
    char c[][]=new char[8][e.length*6],t,u,h='|';
    int x=2,i=0,j,y;
    for(String l:e){
        y=0;
        char[]p=l.toCharArray(), z=c[y];
        int a=p[0],b=p[1],f=p[2],d=p[3],k=x-1,m=x+1;
        t=a<49?'°':a<50?'¯':a<51?45:a<52?'^':39;
        u=(char)(b<50?b+70:b<51?111:b<52?95:39);
        if(d>50){z[x]=h;
            if(f!=49){y=2;
                c[1][x]=h;
                c[2][x]=h;
            }
            z=c[y];
            z[k]=46;
            z[m]=46;
            z=c[++y];
            z[k]=58;
            z[m]=58;
            z[x]=34;
        }
        if(d==50){
            z[x]=40;
            z[m]=41;
            c[++y][x]='´';
            c[y][m]=96;
        }

        if(d==49){
            z=c[++y];
            z[k]=94;
            z[x]=34;
            z[m]=94;}
        if(f>49){
            y=6;
            c[y][x]=44;
        }
        if(f>48){
            y=f>49?7:3;
            z=c[y++];
            z[x]=u;
            z[k]=t;
            z[m]=t;
            z[x-2]=40;
            z[x+2]=41;
        }
        if(f==49){
            z=c[y++];
            z[x]=h;
            z[k]=95;
            z[m]=95;
            z=c[y];
            z[x]=h;
            z[k]=91;
            z[m]=93;
            z[x-2]=47;
            c[y++][x+2]=92;
            c[y++][x]=h;
            c[y][k]=47;
            c[y][m]=92;
        }
        x+=6;
    }
    for(;i<8;i++){
        s="";
        for(j=0;j<c[0].length;){
            t=c[i][j++];s+=t<1?32:t;
        }
        System.out.println(s);
    }
}

```

Favorite decoration (which apparently looks more evil in my console): terminator skeleton

```
(-w-)
 _|_
/[|]\
  |
 / \

```

# Answer
> 2 votes
# Ruby 2.3.1, 777 752 bytes

Edit\_0: I totally missed out on some golfable variable usage and some other stuff.

```
@o=Array.new;$*.each_with_index do|j,i|a,e,n,b,u,q,r,z,y=0,j[0].to_i,j[1].to_i,j[2].to_i,j[3].to_i,['°','¯','-','^',"'"],['v','w','o','_',"-"],Array.new(7," "),"     ";g,h=[z,["(#{q[e]}#{r[n]}#{q[e]})"," _|_ ","/[|]\\","  |  "," / \\ "],["     ","  ,  ","(#{q[e]}#{r[n]}#{q[e]})"]],[z,["     "," ^\"^ "],["  () ", "  ´` "],[" .|. "," :\": "]];2.times{h[3].unshift("  |  ")}unless b==1;if b<1 && u<1;@o.push(z);elsif b<1;u<3 ? (a=5):(a=3);a.times{h[u].push(y)};@o.push(h[u]);elsif u<1;b==1 ? (a=2):(a=4);a.times{g[b].unshift(y)};@o.push(g[b]);elsif u>0;2.times{h[u].push(y)}if u<3&&b>1;@o.push(h[u]+g[b]);end;@o.push(z);end;@o.transpose.each do|v|;v.each do |w|;print w;end;print"\n";end

```

Takes in N number of variables of decorations. There's certainly some more golfing that can be done with this. I'm not that familiar with a lot of Ruby's tricks, but here's a shot at it! I'm also happy at being able to solve it.

## Un-golfed

```
@output = Array.new
$*.each_with_index do |j, i|
  # output decoration combo
  s = 0

  # set up vars for decoration input
  e = j[0].to_i
  n = j[1].to_i
  b = j[2].to_i
  u = j[3].to_i

  # Setup decorations/misc
  eyes = ['°','¯','-','^',"'"]
  nose = ['v','w','o','_',"-"]
  nothing = Array.new(7, " ")
  skeleton = ["(#{eyes[e]}#{nose[n]}#{eyes[e]})", " _|_ ", "/[|]\\", "  |  ", " / \\ "]
  pumpkin = ["     ", "  ,  ", "(#{eyes[e]}#{nose[n]}#{eyes[e]})"]
  fbat = ["     ", " ^\"^ "]
  rbat = ["  () ", "  ´` "]
  spider = ["  |  ", " .|. ", " :\": "]
  spider.unshift("  |  ") unless b == 1
  a = "     "
  bot = [nothing, skeleton, pumpkin]
  top = [nothing, fbat, rbat, spider]

  # if bottom and upper are empty
  if b < 1 && u < 1
    @output.push(nothing)
  # if bottom is empty
  elsif b < 1
    u < 2 ? (s = 3) : (s = 5)
    s.times {top[u].push(a)}
    @output.push(top[u])
  # if upper is empty
  elsif u < 1
    # put in white space before the decorations
    b == 1 ? (s = 2) : (s = 5)
    s.times {bot[b].unshift(a)}
    @output.push(bot[b])
  # if there's an upper decoration
  elsif u > 0
    # put in the top deco
    2.times {top[u].push(a)} if u < 3 && b > 1
    @output.push(top[u] + bot[b])
  end
  # Input the empty column
  @output.push(nothing)
end

# Transpose the array of arrays so that
# instead of outputting each line of a single each decoration
# what's output is each line of each decoration.
# Example:
# [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
# [[1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]]
@output.transpose.each do |data|
   data.each do |data1|
     print data1
   end
   print "\n"
end

```

The following:

```
ruby deco_g.rb 0000 0001 0002 0003 1110 1111 1112 1113 2220 2221 2222 2223 3310 3312 3321 3323

```

Outputs this:

```
          ()    |                 ()   .|.                ()    |           ()          |
   ^"^    ´`    |          ^"^    ´`   :":         ^"^    ´`    |           ´`   ^"^    |
               .|.  (¯w¯) (¯w¯) (¯w¯) (¯w¯)                    .|.  (^_^) (^_^)        .|.
               :":   _|_   _|_   _|_   _|_                     :":   _|_   _|_         :":
                    /[|]\ /[|]\ /[|]\ /[|]\                         /[|]\ /[|]\
                      |     |     |     |     ,     ,     ,     ,     |     |     ,     ,
                     / \   / \   / \   / \  (-o-) (-o-) (-o-) (-o-)  / \   / \  (^_^) (^_^)

```

# Answer
> 1 votes
## Python 2, 331 bytes""

```
B,I,l,s=' '*5,'  |  ',' .|. ',' :": '
r=[]
for x in inputtt:m,n,b,u=(int(y)for y in x);e="°¯-^'"[m];H='('+e+"vwo_-"[n]+e+')';r+=[[[B,B,'  () ',[I,l,I][b]][u],[B,' ^"^ ','  ´` ',[I,s,I][b]][u],[[B,l][u==3],H][b==1],[[B,s][u==3],' _|_ '][b==1]]+[[B]*3,['/[|]\\',I,' / \ ',],[B,'  ,  ',H]][b]]
print'\n'.join(map(' '.join,zip(*r)))

```

Takes input as list of strings

-

### Example

Input: `["1212","4321","0123","1102","0020","1010","0101","2113"]`

Output:

```
  ()          |     ()                     .|.
  ´`   ^"^    |     ´`               ^"^   :":
(¯o¯)        .|.              (¯v¯)       (-w-)
 _|_         :":               _|_         _|_
/[|]\                         /[|]\       /[|]\
  |     ,     ,           ,     |           |
 / \  ('_') (°w°)       (°v°)  / \         / \

```

---
Tags: code-golf, ascii-art
---


title: ASCII PPCG Beta Logo Golf

text:
# Question
Title: ASCII PPCG Beta Logo Golf
We shall soon have a new logo & site design, let us use this last breath of the simple times and golf this ASCII version of the speech bubble beta logo:

+-------------------------------------------+
|    .---------------------------------.    |
|   .EPEpEpBPEpEGCXCgCgCGJgCgP&PWP&P&P&Y`   |
|  .RSRsRWRSRsRsHoNoNONxNONONuJuSUSUSVSUS`  |
|  :o@OTO@O@O@W@IDiDIWiDIDIDWZEZeZEWEZeZE-  |
|  :GWGFGfGFKFGFMEMwMEMEMeXEMZLZLWLZLzLZH-  |
|  :rLRLRLXLRLrLMBMGMGmGXGMGMLzTZLZLZLYLZ-  |
|  :AOAoBOAOAOAYAOAoAoBOAOAoAWZEZEZEVEZEZ-  |
|  :MGVGm!'""'!GRLr!'""'!LRKRS!'""'!uSuSU-  |
|  :XEME' .''% !Gf' .;G% 'GFG' .;P% '&PVP-  |
|  :IDID  !DI! !V! .OPoYOPOP!  -gCGCGHGCG-  |
|  :NONw  ``` .OR! .RWRRRRRR! !ONo* 'ONON-  |
|  :GBGC  !CXCGCP! !POP; !xOP  `IJ; `!IDW-  |
|  :P&P&._!&P&P&F~.____.;GFGF~.____.;eJEM-  |
|  :USUSVSUSuSuTLRlRLRWRLRlRLWMGMGmGwGmGM-  |
|  :ZeWEZEZeZWZeOAOaKAOAOaOwOOAoAOXoAoAOA-  |
|  :wLZLZLzHZLZLGMxMgMGMgBGMGLRLXLRLrLRTr-  |
|  :LZLZLYLZLZLzBMEMEMEyEmEMEfBFGFGfGWGFG-  |
|  :EZEVEZEZeZVZDIdIDYdIdIDIx@O@o@oKO@O@o-  |
|  `SkSuSuSUXUSuONOVONOnONWNOSRSRWRSRSRS-   |
|   `.&P&PVP&P&PCXcGCGCGVGcGCEPYPEpEPE?.-   |
|      ```````````````````:STACKE-`````     |
|                         :XCHA-`           |
|                         :NG-`             |
|           ?=W...HWYWVWB :E`               |
+-------------------------------------------+

This is , so it's straight forward, output all the text that appears in the above code-block in as few bytes of code as possible, without any funny-business.

### input

None

### Output

The ASCII content of the code-block above as a return value or printed to STDOUT or equivalent;
carriage returns `(13)` and/or new lines `(10)` are acceptable;
a trailing empty line is also allowed.

### Update

The original aim of this challenge was to have a puzzle aspect. It seems this has not been noticed, so I have decided to make the puzzle portion *significantly* easier, but still present, by performing a couple of steps to get you going:

1. There is a use of the string `"STACKEXCHANGE"` in the very bottom portion of the speech-bubble.
2. If one reads the rows of text in the main-portion of the speech-bubble, one might notice an almost repetitive nature of pairs of letters, for example the fourth row reads `"GWGFGfGFKFGFMEMwMEMEMeXEMZLZLWLZLzLZH"` which is almost `"GFGFGFGFGFGFMEMEMEMEMEMEMZLZLZLZLZLZH"`, except some letters have been changed either to another letter (e.g. the second letter from `F` to `W`), to lower-case (e.g. the sixth letter from `F` to `f`), or both (e.g. the sixteenth letter from `E` to `w`). The rows seem to all conform to such a pattern with a 12-13-12 character split (ignoring the mess of the `PPG` logo's white space and border).
3. The process described in (2), once noticed, should be quite easy to undo for the unmasked rows of the speech-bubble (the top six and bottom seven), by first converting the whole text to upper-case and then replacing the odd-ones-out and results in:

+-------------------------------------------+
|    .---------------------------------.    |
|   .EPEPEPEPEPEGCGCGCGCGCGCGP&P&P&P&P&P`   |
|  .RSRSRSRSRSRSNONONONONONONUSUSUSUSUSUS`  |
|  :O@OTO@O@O@O@IDIDIWIDIDIDIZEZEZEZEZEZE-  |
|  :GFGFGFGFGFGFMEMEMEMEMEMEMZLZLZLZLZLZL-  |
|  :RLRLRLRLRLRLMGMGMGMGMGMGMLZLZLZLZLZLZ-  |
|  :AOAOAOAOAOAOAOAOAOBOAOAOAEZEZEZEZEZEZ-  |
|  :MGVGm!'""'!GRLr!'""'!LRKRS!'""'!uSuSU-  |
|  :XEME' .''% !Gf' .;G% 'GFG' .;P% '&PVP-  |
|  :IDID  !DI! !V! .OPoYOPOP!  -gCGCGHGCG-  |
|  :NONw  ``` .OR! .RWRRRRRR! !ONo* 'ONON-  |
|  :GBGC  !CXCGCP! !POP; !xOP  `IJ; `!IDW-  |
|  :P&P&._!&P&P&F~.____.;GFGF~.____.;eJEM-  |
|  :USUSUSUSUSURLRLRLRLRLRLRLGMGMGMGMGMGM-  |
|  :ZEZEZEZEZEZEOAOAOAOAOAOAOOAOAOAOAOAOA-  |
|  :ZLZLZLZLZLZLGMGMGMGMGMGMGLRLRLRLRLRLR-  |
|  :LZLZLZLZLZLZEMEMEMEMEMEMEFGFGFGFGFGFG-  |
|  :EZEZEZEZEZEZDIDIDIDIDIDID@O@O@O@O@O@O-  |
|  `SUSUSUSUSUSUONONONONONONOSRSRSRSRSRS-   |
|   `.&P&P&P&P&PCGCGCGCGCGCGCEPEPEPEPEP.-   |
|      ```````````````````:STACKE-`````     |
|                         :XCHA-`           |
|                         :NG-`             |
|           ?=W...HWYWVWB :E`               |
+-------------------------------------------+

4. While carrying out (3) one may notice a couple of things. First the least obvious: that the only `?`, in the very bottom-right became a `P`, whereas the extra text at the bottom says `?=W...`, and that a large proportion of replaced characters were also `W`. Second that the odd-ones out in upper-case were `B,H,J,K,T,V,W,X,Y`. Third that the odd-ones out occurred every seven letters. The second and third observation helps to fill in the middle rows - which, if we remove the `PCG` mask of spaces and non-letters, non `&` (used in the top and bottom row) and replace it with the letters yields:

+-------------------------------------------+
|    .---------------------------------.    |
|   .EPEPEPEPEPEGCGCGCGCGCGCGP&P&P&P&P&P`   |
|  .RSRSRSRSRSRSNONONONONONONUSUSUSUSUSUS`  |
|  :O@O@O@O@O@O@IDIDIWIDIDIDIZEZEZEZEZEZE-  |
|  :GFGFGFGFGFGFMEMEMEMEMEMEMZLZLZLZLZLZL-  |
|  :RLRLRLRLRLRLMGMGMGMGMGMGMLZLZLZLZLZLZ-  |
|  :AOAOAOAOAOAOAOAOAOBOAOAOAEZEZEZEZEZEZ-  |
|  :MGMGMGMGMGMGRLRLRLRLRLRLRSUSUSUSUSUSU-  |
|  :MEMEMEMEMEMEGFGFGFGFGFGFG&P&P&P&P&P&P-  |
|  :IDIDIDIDIDIDOPOPOPOPOPOPOCGCGCGCGCGCG-  |
|  :NONONONONONORRRRRRRRRRRRRONONONONONON-  |
|  :GCGCGCGCGCGCPOPOPOPOPOPOPDIDIDIDIDIDI-  |
|  :P&P&P&P&P&P&FGFGFGFGFGFGFEMEMEMEMEMEM-  |
|  :USUSUSUSUSURLRLRLRLRLRLRLGMGMGMGMGMGM-  |
|  :ZEZEZEZEZEZEOAOAOAOAOAOAOOAOAOAOAOAOA-  |
|  :ZLZLZLZLZLZLGMGMGMGMGMGMGLRLRLRLRLRLR-  |
|  :LZLZLZLZLZLZEMEMEMEMEMEMEFGFGFGFGFGFG-  |
|  :EZEZEZEZEZEZDIDIDIDIDIDID@O@O@O@O@O@O-  |
|  `SUSUSUSUSUSUONONONONONONOSRSRSRSRSRS-   |
|   `.&P&P&P&P&PCGCGCGCGCGCGCEPEPEPEPEP.-   |
|      ```````````````````:STACKE-`````     |
|                         :XCHA-`           |
|                         :NG-`             |
|           ?=W...HWYWVWB :E`               |
+-------------------------------------------+
</code></pre>
1. Now reading the columns one can see that the "input" text to make this base grid was `PROGRAMMINGPUZZLES&CODEGOLFPROGRAMMINGPUZZLES&CODEGOLF@SE`.

The lower-casing and replacement characters are to be determined by you, but also note that the ten remaining letters in the alphabet after removing those present in that string are `B,H,J,K,Q,T,V,W,X,Y` \- the replacements plus `Q`.

# Answer
# Bubblegum, ~~542~~ 541 bytes

Reversible hexdump:

```
00000000: d2d6 251e 68f3 72d5 002a 2903 1637 6138  ..%.h.r..*)..7a8
00000010: 8a7f 9578 7027 0c9a 0fd0 32ae 6a63 b435  ...xp'....2.jc.5
00000020: 2668 6734 00e7 d8d9 32b6 cea3 4769 57c6  &hg4....2...GiW.
00000030: 3efb 5e94 1a60 07c7 e5f1 7f89 f033 35ff  >.^..`.......35.
00000040: a725 18f4 5d92 5aec cf88 53a6 d80b 7b09  .%..].Z...S...{.
00000050: adf3 a88e f610 5fc3 d583 d228 a869 279c  ......_....(.i'.
00000060: 1665 f15a e8c1 5f93 3eef 7399 5f72 099d  .e.Z.._.>.s._r..
00000070: d6a7 f20b 54a1 da1b 3eef 9772 2b97 567a  ....T...>..r+.Vz
00000080: 99ae beaf 528d 82b4 61a6 334c 0f3e 9b70  ....R...a.3L.>.p
00000090: ae79 cc77 3cde c43c 164c 9c05 83ba 9a09  .y.w<..<.L......
000000a0: 9399 4ca3 ae99 491c 7ecc 0aa8 461d 3311  ..L...I.~...F.3.
000000b0: 0a2e f881 d770 915d b7b8 036a 32e3 f040  .....p.]...j2..@
000000c0: 067d 2803 ab06 d58f 5798 b561 5695 7587  .}(.....W..aV.u.
000000d0: 0b5e f183 e7df ddf9 1ec7 2f8c abac d814  .^......../.....
000000e0: e5b8 3c95 38b1 c3f1 94cc 27d4 f7ef 89c7  ..<.8.....'.....
000000f0: 7758 2df8 3df1 711e bb54 583e a84a 39dc  wX-.=.q..TX>.J9.
00000100: 7681 106f 957a c4ab 3c42 a5ea 1ba9 a4f2  v..o.z..<B......
00000110: 0899 2181 8827 2887 a3c3 6742 dab6 0559  ..!..'(...gB...Y
00000120: 0047 06c3 c0dd 32ef 3f11 5f82 7038 0f79  .G....2.?._.p8.y
00000130: 84dd a31a 3b29 30d8 7841 bc8b 54d8 235d  ....;)0.xA..T.#]
00000140: 2f48 eb21 0387 db94 e993 37a4 1dff a54f  /H.!......7....O
00000150: 1878 fc98 4feb 6ecd 84c3 6f39 a303 dbac  .x..O.n...o9....
00000160: f889 1034 0ab3 1e33 38a3 84c3 4da7 d990  ...4...38...M...
00000170: b736 1d1a fe75 1358 9767 697b 2feb de7a  .6...u.X.gi{/..z
00000180: e0f0 f390 dc35 b1ce c545 ecb1 e93e c4c6  .....5...E...>..
00000190: 53d6 c5f6 e8f0 5bce d035 14cc ea37 3bc0  S.....[..5...7;.
000001a0: 7761 3cbc 4d1a eef0 5bce 9da9 cc2a 7d4e  wa<.M...[....*}N
000001b0: 57cd b3f5 f482 77b4 5ff6 1b69 e709 6fcb  W.....w._..i..o.
000001c0: 1fe5 9073 8dd3 a2c5 15ea 97cc 752e 4b7c  ...s........u.K|
000001d0: 031a 0581 1e71 f014 1d44 ced6 a3fa 1b8f  .....q...D......
000001e0: a08a 6366 aab1 5f98 628f d4e1 76b4 ff8f  ..cf.._.b...v...
000001f0: 79b9 0da2 0d9b 0d17 401c fee6 98d7 5112  y.......@.....Q.
00000200: ccda e9fa 3d3c e70e 7e0b 7ffc ac29 a589  ....=<..~....)..
00000210: 6e74 a543 34cc c113 fea1 bfa5 7f         nt.C4........

```

Try it online!

Just Zopfli'd the string for 1 million iterations. Running for 100 million iterations does not yield a shorter solution.
> 4 votes

# Answer
# PHP, 780 Bytes

```
<?=gzinflate(base64_decode("lZRvb9owEMbfT9p3cCq1kYbiDwCaShIcE0hiK2FxkjdNtQY0bSwVVQVDVT/7HpuBYZv2x6e7XKKfD/sem4H372Pw9s0LwaB/JanGXg44ZZI9ssdARx5W4QrGZ4jyRio4rG5POM2L/ClXJj5N+6zPRLaDi+x59lx8gJXw9ogP+7FYiLE2NY4nnyaxgsNUw5quYcpE74RzxSO+5NE84lHK0i2cpV3F0iZpEgXfJ83U4pskh1XwTZIGKU/5mleIabJf6BlNUieNxX3h94HwtdU6//HW+3o1sFJHi6e85GvHvbpyHY5fOGRJPs+LQ/pcYMcWxyqZS6jrXhOHL5GN+DVxsR+dSqQ3spQW110gxJnEDnFKh1Ah+1pIIR1CPCgQ8inc4ujwlpC2bUHmwKGBGZgtsv4dcbUGZ40MeIjq0JOHKOmg8Ig4OyFRI56NSOtAA4trlemdY9SOXukdBpYPEY55N2OpxY86owOLJP8CEVRunuqgwRZ+hjedYkZv1XRo+P1cS3AvtkL3XlS9jr7Ft0a5/VRHnu7SFYquAhQ+aZ0vNhY/6qznBObAsG9sjbgMInOa9Jmy+FHnrimbSfwQT+oHHeMdzmg/7uf6rPYnvC0+F0bnCrtFi0v4V5GpTBS4A/oewDx7m1qqe1iaexNWH7kWsuR4MlnrGybZLT3DiZH05zEsFn44Z555IeQC/80YVuHU99qzL3/GM34B/4LfvleU0qmqVakCNOwSNvjgf/6WvgM="));

```

Maybe helpful maybe not I do not know I give up to find an other way. beginning the first line at 1 you could concat lines they have the sum 24 with one letter starts with the W in the middle go up go left and go reverse the 2 line down then concat the first letter of line 13 with the end of line 11 and go to the middle now I assume that you must go down to line 14

It seems for me that "?=W...HWYWVWB" is a hint to solve this
> 2 votes

# Answer
## Ruby, 788 bytes

Basically the same method as the PHP solution.

```
puts Zlib.inflate Base64.decode64 "eJyVlG9vmzAQxt/vU5hKLdIi/AESTQ0QxyEBjCDDwJtSrUk0bRlVqihZVfWz7zmnOG017Y9PdxzRzyf83DkD79/X4MMTw+J/BTlhT4bmIhP34j6gKMMq3MDkHDG7yjQcVrc9zfMif8i1iQ+zLu1SlR7hKt3P98VnWAlvX+hhN1ZLNSbT42jydRJpOEw3olk1Qpvo9bTUcirXcrqYymkikgNcJKtKJE3cxBr+GDczS+/iHFbBd3ESJDKRW1khJvHjkjY0cR03lvaV3wXKJ6spf3nrfPoUWEnR0oks5dZxLy5cR6L+KYvzRV6c0n2Bw1oaXyhcxl33kjlyjWwkL5mLs1CaIb3KyszSdH7GnEnkMKd0GFdZV6tMZQ5jHpQP5QxuaSh7YKxtW4A5aGhvFjartPvIXNL+rGAgQ9RGF2WIgg7KjphzVBlKRPMRax1ob2lqLb9xTIunz/wGC58O8ft8NReJpfvm4uzLOP8O8XVunvqk/QF+ppuVFqbJullB6NsFSX+rDoo0V1VH0bf0wfTrcUZRJsdkg5KbAGVth/PlztJ9c2lLYIZE/BRbxHUwNRNEc2Tpvrmrpmwm0V00qe8oRkdMZTfuFjSdXU+3xbfCNLfCQSFtCf+hUp2qAjNPcw/z7N1pOYlXmlsSVl8kta+UeIqspvuUiWt+pplp5Ps1LJZ+uBCeeWHsNf2bNazCme+1r375I53KN+x7+vqT5pzPdK1LHUCqtyzRg//69/kFnIsxTA=="

```
> 1 votes

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: String Calculator

text:
# Question
Title: String Calculator
Assume you're writing in one method, (or whatever you call them) with 3 inputs: the first string, a character that contains a `+`, `-` or `*` symbol, and the second string.

Example in Java:

```
public String strCalc(String str1, char sym, String str2) {
    //code...
}

```

What it should return:

```
str1 sym str2 ans
A     +  A   =  B
A     +  B   =  C
B     +  B   =  D
Z     +  A   =  AA
W     +  B   =  Y
A     -  A   =  ' ' (Space Character)
A     -  B   =  -A
A     -  C   =  -B
B     -  A   =  A
CA    -  A   =  BZ
A     *  A   =  A
B     *  B   =  D

```

Think of a one-indexed base 26. Then convert the numbers back to letters based on their position in the alphabet.

```
0 = ' ' (Space Character)
1 = A
2 = B
3 = C
4 = D
5 = E
6 = F
7 = G
8 = H
9 = I
10 = J
11 = K
and so on...

```

This is , so the shortest code in bytes not including the method declaration wins.

# Answer
# Jelly, ~~64~~ 63 bytes

```
Aḃ26ịØA
O_64»0ḅ26
e”-NḤ’×Ç
³Ç;“*×-_”y⁴¤;⁵Ç¤V
¢<0”-x;¢1Ŀ¤
¢⁶¢L¤?

```

Not a particularly clean solution; there are no 3 argument methods in Jelly, so this is a full program.

Accepts negative inputs like `"-A"`, `"- A"`, `" -A"`, ... (note however `"--A"` is treated as `"-A"`)
Accepts zero inputs like `""`, `" "`, `" "`, ...

**TryItOnline**

### How?

```
Aḃ26ịØA           - Link 1, convert integer to absolute value string: i
A                 - absolute value of i
 ḃ26              - convert to bijective base 26 (a list of integers in [1,26])
    ị             - index into (1-based)
     ØA           - alphabet yield -> "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                  - (note: 0 will convert to an empty string here.)

O_64»0ḅ26         - Link 2, convert an input string to a positive integer: s
O                 - cast to ordinal (vectorises)
 _64              - subtract 64 from each (A->[1], B->[2], ..., AZ->[1,26], ...)
    »0            - maximum of that and zero ("-" and space become zeros; vectorises)
      ḅ26         - convert from base-26 to an integer (26 place values still work)

e”-NḤ’×Ç          - Link 3, convert an input string to an integer: s
 ”-               - literal '-'
e                 - exists in s?
   N              - negate
    Ḥ             - double
     ’            - increment (if "-" was in s we have -1, else we have 1)
      ×           - multiply by
       Ç          - call last link (2) as a monad

³Ç;“*×-_”y⁴¤;⁵Ç¤V - Link 4, evaluate the operation: niladic
³                 - first program input
 Ç                - call last link (3) as a monad (value of first input as an integer)
  ;               - concatenate with
           ¤      -     nilad followed by link(s) as a nilad
          ⁴       -     second program input
         y        -     map characters
   “*×-_”         -     literal "*×-_" - change "*" to "×" and "-" to "_"
            ;     - concatenate with
               ¤  -     nilad followed by link(s) as a nilad
             ⁵    -     third program input
              Ç   -     call last link (3) as a monad (value of 3rd input as integer)
                V - evaluate string as Jelly code (something like "-76×5" or "3_2")

¢<0”-x;¢1Ŀ¤       - Link 5, form output for non-zero results: niladic
¢                 - call the last link (4) as a nilad (integer result)
 <0               - less than zero?
   ”-             - literal '-'
     x            - repeat ('-' if negative '' if positive or zero)
      ;           - concatenate with
          ¤       -     nilad followed by link(s) as a nilad
       ¢          -     call the last link (4) as a nilad (integer result)
        1Ŀ        -     call the next link (1) as a monad (as absolute string)

¢⁶¢L¤?            - Main link: niladic (the program arguments expected however)
     ?            - ternary if
    ¤             -     nilad followed by link(s) as a nilad
  ¢               -     call the last link (5) as a nilad
   L              -     length
                  - True case (has length)
¢                 -     call the last link (5) as a nilad
                  - False case (no length)
 ⁶                - literal ' '

```
> 2 votes

# Answer
## Assembler x86 (32-bit) - 142 bytes

The 142 bytes are the compiled size (not the source code size, which is larger). Note that for assembler the size of the compiled code is not dependend on the compiler used but it should always be 142 bytes.

The calling convention is "\_cdecl" so you can call the function from C:

```
const char *strCalc(const char *num1,
    char operation, const char *num2, char *bufferEnd);

```

The function accepts negative inputs (such as "-AB") and zero (" "). However malformed inputs might crash the program!

The last argument points to the LAST byte of a buffer used to store the sring because C does not support strings without pre-allocated buffers.

The function returns the pointer to the string (somewhere in the buffer). The function may be called the following way:

```
#include <stdio.h>

const char *strCalc(const char *num1, char operation, const char *num2, char *bufferEnd);

main(int argc,char **argv)
{
    char buf[21];
    puts(strCalc(argv[1],argv[2][0],argv[3],buf+20));
}

```

Here is the actual function (Linux users: Replace "\_strCalc" by "strCalc"):

```
    .globl _strCalc
    .text
_strCalc:
    push %ebx
    push %esi
    push %edi
    mov 16(%esp), %esi
    call loadNum
    push %ebx
    mov 28(%esp), %esi
    call loadNum
    pop %eax
    # This assumes that the operation is ONLY +, * or -!
    cmpb $0x2B, 20(%esp)
    je isPlus
    jb isMultiply
    sub %ebx, %eax
    jmp calcDone
isPlus:
    add %ebx, %eax
    jmp calcDone
isMultiply:
    xor %edx, %edx
    imul %ebx
calcDone:
    push %eax
    mov 32(%esp), %edi
    std
    xor %al, %al
    stosb
    pop %eax
    call writeOut
    mov %al, (%edi)
    mov %edi, %eax
    inc %eax
    pop %edi
    pop %esi
    pop %ebx
    # Needed due to MSVCRT.DLL bug!
    cld
    ret

    # Write EAX to the buffer
    # EDI points to the last character to be
    # written (the terminating NUL has already been written)
    # Returns: EDI pointer to the first character!
writeOut:
    test %eax, %eax
    jnz notZero
    mov $0x20, %al
    stosb
    ret
notZero:
    jns notNegative
    neg %eax
    call writeOut
    mov $0x2D,%al
    stosb
    ret
notNegative:
    xor %edx, %edx
    dec %eax
    div %ecx
    xchg %al, %dl
    add $0x41, %al
    stosb
    xchg %al, %dl
    test %eax, %eax
    jnz notNegative
    xchg %al, %dl
    ret

    # Load number from string ESI points to to EBX
    # Destroys EAX, ECX, EDX
    # Allows negative and zero inputs!
    # Assumes syntactically correct numbers!
    # Sets ECX to 26 (needed later!)
loadNum:
    xor %ebx, %ebx
    xor %eax, %eax
    mov $26, %al
    mov %eax, %ecx
nextLoad:
    cld
    lodsb
    and $0xDF, %al
    jz endOfLoad
    sub $0x40, %al
    jc negativeInput
    xchg %eax, %ebx
    mul %ecx
    add %eax, %ebx
    jmp nextLoad
negativeInput:
    call loadNum
    neg %ebx
endOfLoad:
    ret

```
> 1 votes

---
Tags: code-golf, string, math
---


title: Real Chebyshev Rotation

text:
# Question
Title: Real Chebyshev Rotation
This is a challenge inspired by Chebyshev Rotation. I suggest looking at answers there to get inspiration for this challenge.

Given a point on the plane there is a unique square (a rectangle with equal sides) that is centered on the origin and intersects that point (interactive demo):

Given a point **p** and a distance **d**, return the point obtained by moving distance **d** from **p**, counter-clockwise (and clockwise for negative **d**), along the perimeter of the square centered on the origin that intersects **p**. Your answer must be accurate to at least 4 decimal digits.

### Testcases:

```
(0, 0), 100 -> (0, 0)
(1, 1), 81.42 -> (-0.4200, 1.0000)
(42.234, 234.12), 2303.34 -> (-234.1200, 80.0940)
(-23, -39.234), -234.3 -> (39.2340, -21.8960)

```

The following test cases are from the original challenge by Martin Ender, and all are with **d = 1**:

```
(0, 0)       -> (0, 0)
(1, 0)       -> (1, 1)
(1, 1)       -> (0, 1)
(0, 1)       -> (-1, 1)
(-1, 1)      -> (-1, 0)
(-1, 0)      -> (-1, -1)
(-1, -1)     -> (0, -1)
(0, -1)      -> (1, -1)
(1, -1)      -> (1, 0)
(95, -12)    -> (95, -11)
(127, 127)   -> (126, 127)
(-2, 101)    -> (-3, 101)
(-65, 65)    -> (-65, 64)
(-127, 42)   -> (-127, 41)
(-9, -9)     -> (-8, -9)
(126, -127)  -> (127, -127)
(105, -105)  -> (105, -104)

```

# Answer
> 4 votes
# Python 2, ~~363~~ ~~335~~ ~~296~~ ~~266~~ ~~262~~ ~~258~~ ~~256~~ 233 Bytes

<sup>***Woo, 130 bytes lost! Thanks to Neil for saving 4 bytes, Nathan Merrill for saving 2 bytes, and xnor for saving a ridiculous 23 bytes!***</sup>

The general idea is this: We can reduce the distance traveled by taking it's the modulus of it against the perimeter of the square. The perimeter is defined as 8 times the largest of the two coordinates, since the point must rest on it. Then, after modulus is taken we are guaranteed to have no overlap. It also guarantees we only ever have to move counter-clockwise, since modulus gives a positive result.

From there, I simply use what we know from the given x and y-coordinates to figure out where we are: top, bottom, left, right, or in a corner, and determine the direction, which can be one of `0, 1, 2, 3`:

```
0 --> we are on the 'top', moving 'left'
1 --> we are on the 'left', moving 'down'
2 --> we are on the 'bottom', moving 'right'
3 --> we are on the 'right', moving 'up'

```

After this, it is as simple as looping while we still have distance to travel, and based on the direction we subtract or add to the appropriate coordinate, and tell the loop which direction we are going next.

```
p,d=input()
x,y=p
s=max(x,y,-x,-y)
d=d%(s*8or 1)
r=[(y<s)*[2,[3,x>-s][x<s]][y>-s],[2*(y<0),3*(y<=0)][x>0]][y*y==x*x]
while s>0<d:f=1-2*(r<2);m=abs(f*s-p[r%2]);j=d>m;p[r%2]=[p[r%2]+f*d,f*s][j];r=-~r%4;d=(d-m)*j
print"%.4f "*2%tuple(p)

```

While quite long, it certainly works. Here's some example I/O:

```
[0, 0], 100 --> 0.0000 0.0000
[1, 1], 81.42 --> -0.4200 1.0000
[42.234, 234.12], 2303.34 --> -234.1200 80.0940
[-23, -39.234], -234.3 --> 39.2340 -21.8960

```

**Try it online** or **run test cases**.

# Answer
> 3 votes
## JavaScript (ES6), 147 bytes

```
f=(x,y,d,s=Math.max(x,y,-x,-y),c=(d/8%s+s)%s*8,v=0,w=x+y>0?1:-1,b=(v?x:y)*w+c-s)=>c?b>0?f(v?s*w:x,v?y:s*w,d,s,b,!v,v?w:-w):[x+c*w*v,y+c*w*!v]:[x,y]

```

Explanation: Works by trying to add the direction vector while keeping within the bounds of the square. Any overshoot is recursively passed back with the direction rotated anticlockwise by 90°. The direction is actually encoded using a vertical flag `v` and a unit `w` so that the vectors (1, 0), (0, 1), (-1, 0) and (0, -1) are encoded with `v` of 0, 1, 0, 1 and `w` of 1, 1, -1, -1 respectively. The direction vector may not initially point in a suitable direction but it never points backwards so it will eventually rotate into a usable direction.

```
f=(x,y,d,                   Input parameters
 s=Math.max(x,y,-x,-y),     Calculate half the side of the square
 c=(d/8%s+s)%s*8,           Reduce the distance modulo the perimeter
 v=0,                       Initial vertical flag
 w=x+y>0?1:-1,              Initial direction
 b=(v?x:y)*w+c-s)=>         Will we overshoot the corner?
  c?b>0?f(v?s*w:x,v?y:s*w,  Advance to the next corner
          d,s,b,!v,v?w:-w): Rotate the direction
        [x+c*w*v,y+c*w*!v]: Advance the remaining amout
    [x,y]                   Nothing to do, zero input

```

---
Tags: code-golf, geometry
---


title: Expand an encoded string

text:
# Question
Title: Expand an encoded string
There's the classic run length encoding and decoding.

```
input   output
a3b2c5  aaabbccccc

```

And that's fairly straight forward and done before.

The challenge is to also account for a non-standard behavior when multiple characters precede the run length (a ***single*** digit from 0-9). Each character before the run length digit (the last digit before a non-digit or end of the string) has that value applied to it *individually* and printed out in order.

Some test input and output including some edge cases:

```
input   output
ab3c5   aaabbbccccc
a0b3    bbb
13b1    111b
a13b1   aaa111b
a123b1  aaa111222b
aa2a1b1 aaaaab

```
* A character sequence (`[a-zA-Z0-9]+`) must be followed by its run length length (`[0-9]`)
* Only valid input needs to be considered (`([a-zA-Z0-9]+[0-9])*`)
    + yes, empty string is valid input.
* Input is via standard input, output via standard output

This is code golf, number of bytes determines the winner.

# Answer
# Pip, 22 + 1 = 23 bytes

Uses `-r` flag. Note that this requires you to either 1) enter an EOF after the input (Ctrl-D on Linux, Ctrl-Z on Windows) or 2) pipe the input in from somewhere else.

```
(^_@<v)X_@vMa@`\D*\d+`

```

Explanation:

```
                        a is first line of stdin (from -r flag) and v is -1 (implicit)
              `\D*\d+`  Pattern (regex) object that matches zero or more non-digits
                        followed by at least one digit
            a@          Find all non-overlapping matches in a, returning a list of strings
           M            To that list, map a lambda function:
  _@<v                    Argument sans last character (equivalent to Python a[:-1])
(^    )                   Split into a list of characters
        _@v               Last character of argument
       X                  Repeat each character of the list that many times
                          (String multiplication X, like most operators, works item-wise
                          on lists)
                        Auto-print (implicit)

```

The result of the map operation is actually a list of lists, but by default lists are simply concatenated together when printed, so no manual conversion to string is necessary.

Example, with input `a13b1`:

```
Var a gets        "a13b1"
After regex match  ["a13" "b1"]
After map          [["aaa" "111"] ["b"]]
Final output       aaa111b

```

Pip has basic regex support as of... 2 days ago. Great timing!
> 3 votes

# Answer
## Perl/Bash ~~54~~ 40+1 = 41 bytes

```
perl -pe's:(\D*\d*)(\d):"\$1=~s/./\$&x$2/egr":ege'

```

It's basically a regex within a regex. And a bit of magic.

### Explanation

The outer regex `/(\D*\d*)(\d)/g` extracts each run-length encoded group. We capture the stuff to repeat in `$1` and the number of repetitions in `$2`. Now we substitute each such group with the expansion of that group. For that, we evaluate the code `"\$1=~s/./\$&x$2/egr"` *two* times (as by the `/ee` flag on the outer substitution).

The first evaluation will only interpolate the number of repetitions into the string – the other variables are protected by a backslash. So assuming the input `a14`, we would now have the code `$1=~s/./$&x4/egr`, which will be evaluated again.

This will apply the substitution to the contents of `$1` (the stuff to repeat `a1`). The substitution matches each character `.`. The `$&` variable holds the whole match, which we repeat `x4` times. We do this `/g`lobally for each match and `/r`eturn the substituted string rather than modifying the `$1` variable (which is read-only). So the result of the inner substitution is `aaaa1111`.

The `-p` flag applies the substitution to each input line and prints out the result.
> 8 votes

# Answer
# CJam, ~~33 31~~ 27 bytes

Ughh, lack of regular expressions makes this pretty long...

```
qN+{:XA,s&L\:L>{])~e*[}&X}%

```

**How it works**

We loop through all characters of the input string and in each iteration, keep track of the last encountered character (starting with an empty character for the first time). Then we check if the current character is non-numeric *and* the last character is numeric. If so, we repeat each previous character (which has not been repeated already), the number times.

(A bit outdated code expansion)

```
q{                       }%        e# Read the input (q) and loop through each character
  L                                e# Put variable L (initially empty character) on stack
   A,                              e# Put variable A (equals 10) and create an array 0..9
     s                             e# Convert the array to string "0123456789"
      &                            e# Do a set intersect b/w previous char and 0-9 string
                                   e# If numeric, it gives 1 char string, otherwise 0
       \:LA,s&                     e# Swap to bring current character on top. Store it in L
                                   e# and do the same set intersect with it
              >                    e# Means we are checking that current char is non-numeric
                                   e# and previous numeric
               {      }&           e# Run this block if above is true
                ])~                e# Wrap everything not already repeated in an array and
                                   e# take out the last character and convert it to integer.
                                   e# This is the run length of the preceding string
                   e*              e# Repeat each character in the string, run length times
                     [             e# Start a new array to help when next run length is found
                        L          e# Restore the current character back on stack to be used
                                   e# in next iteration
                           )~e*    e# The last string-run-length pair is not decoded..
                                   e# So we do that now

```

Try it online here
> 7 votes

# Answer
# rs, 43 71 chars

Well, this turned long quickly. Stupid numbers...

```
(\d)(\D)/\1 \2
+(\w)(\w+?)(\d)(?= |$)/\1\3 \2\3
(\w)(\d)/(\1)^^(\2)
 /

```

Try it here!

Original version (did not work with input like `123`):

```
+(\D)(\D+)(\d)/\1\3\2\3
(\D)(\d)/(\1)^^(\2)

```

## Explanation

The first line places spaces between runs containing numbers, e.g. turning `a313` into `a3 13`.

The second line continuously expands the compressed encodings like `aa5` to `a5a5`.

The third line converts every instance of `a5` into `aaaaa` using the repetition operator.

The last line removes the spaces.
> 6 votes

# Answer
# Javascript (*ES6*), 86 83 bytes

```
alert(prompt().replace(/(.+?)(\d)(?!\d)/g,(a,b,c)=>b.replace(/./g,y=>y.repeat(c))))
```

**Commented:**

```
alert( // output final result
    prompt(). // take input
    replace(/(.+?)(\d)(?!\d)/g, // replace ungreedy capture group of any characters
                                // followed by a digit (captured)
                                // and not followed by a digit (negative lookahead)
        (a, b, c)=> // replace with a function
            b.replace(/./g, // replace all characters in b
                y=>y.repeat(c) // with that character repeated c times
            )
    )
)

```
> 5 votes

# Answer
# CJam, ~~27~~ 25 bytes

```
r_'A+1>.{64&1$>{])~f*o}&}

```

Try it online in the CJam interpreter.

### How it works

```
r_                        e# Read a token from STDIN and push a copy.
  'A+                     e# Append the character A to the copy.
     1>                   e# Discard the first character of the copy.
       .{               } e# For each character C of the input string and the
                          e# corresponding character D of the copy:
         64&              e#   Take the bitwise and of D and 64. This pushes @
                          e#   if D is a letter and NUL if it is a digit.
            1$>           e#   Compare the result to a copy of C. This pushes 1
                          e#   if and only if D is a letter and C is a digit.
               {      }&  e#   If the result was 1, do the following:
                ]         e#     Wrap the stack in an array.
                 )~       e#     Pop and evaluate the last character.
                   f*     e#     Repeat each char in the array that many times.
                     o    e#     Print all characters.

```
> 4 votes

# Answer
# Pyth, ~~33~~ ~~32~~ 28 bytes

```
ssmm*vedkPdPcz-hMJf<@zT\=UzJ

```

Try it online: Demonstration or Test harness

### Explanation

I'll explain the code using the example input `aa1a23b2`. Hopefully this is a bit easier to follow than without.

```
                               implicit: z = input string = 'aa1a23b2'
                         Uz    the indices of z: [0, 1, 2, 4, 5, 6, 7]
                  f            filter for indices T, which satisfy:
                   <@zT\=        z[T] < "="
                               this gives us the list of indices [2, 4, 5, 7],
                               which correspond to digits in z.
                 J             assignment, J = [2, 4, 5, 7]
               hMJ             increment all element in J: [3, 5, 6, 8]
              -            J   and remove the elements of J:
                                 [3, 5, 6, 8] - [2, 4, 5, 7] = [3, 6, 8]
            cz                 split z at these indices: ['aa1', 'a23', 'b2', '']
           P                   remove last element: ['aa1', 'a23', 'b2']
  m                            map each string d to:
   m     Pd                      map each string k of d-without-last-char to:
     ved                           int(last element of d)
    *   k                          * k
                               this creates [['a', 'a'], ['aaa', '222'], ['bb']]
 s                             sum the lists: ['a', 'a', 'aaa', '222', 'bb']
s                              sum the strings: 'aaaaa222bb'

```
> 3 votes

# Answer
# Ruby 73

```
gets.split(/(\d)(?!\d)/).each_slice(2){|s,i|s.chars.map{|c|$><<c*i.to_i}}

```

Tests: http://ideone.com/L1fssb
> 2 votes

# Answer
# JavaScript 112

```
alert(prompt().replace(/.*?\d+/g,function(m){for(i=n=m.length-1,o="";i--;){j=m[n];while(j--)o=m[i]+o}return o}))
```
> 2 votes

# Answer
# Python 2.7, 98 bytes

```
import re
print"".join(c*int(m[-1])for m in
re.findall(r".+?\d(?!\d)",raw_input())for c in m[:-1])

```

This just does a simple regex search for digits that aren't followed by a digit, and then does the string arithmetic on each group and joins them all back together.
> 2 votes

# Answer
# Python 3, ~~148~~ ~~144~~ ~~136~~ 135 Bytes

```
w,o,r,d=''.join,'',[],[]
for c in input()+' ':
 if'/'<c<':':d+=[c]
 elif d:o+=w(x*int(w(d))for x in r);r=[c];d=[]
 else:r+=[c]
print(o)

```

*Thanks to Pietu1998 and mbomb007 for the suggestions.*

# Python 2, ~~161~~ ~~151~~ ~~147~~ ~~139~~ 138 Bytes

Maybe today's just been a long day at work, but I can't for the life of me figure out how to golf this..

```
w,o,r,d=''.join,'',[],[]
for c in raw_input()+' ':
 if'/'<c<':':d+=[c]
 elif d:o+=w(x*int(w(d))for x in r);r=[c];d=[]
 else:r+=[c]
print o

```
> 1 votes

# Answer
# Julia, ~~105~~ ~~99~~ ~~95~~ 87 bytes

```
s->join([join([string(b)^(int(p[end])-48)for b=chop(p)])for p=matchall(r"\D*\d*\d",s)])

```

This creates an unnamed function that takes a string as input a returns a string. To call it, give it a name, e.g. `f=s->...`.

Two array comprehensions are used here, one nested within the other. The outer comprehension acts on each match of the input string against the regular expression `\D*\d*\d`. The inner comprehension repeats each character of the match according to the trailing digit. The elements of the inner array are joined into a string, so the outer array is an array of strings. These are joined and returned.

In Julia, strings can be treated like character arrays. However, note that the `Char` and `String` types in Julia don't have the same methods defined; in particular, there is no method for repetition using `^` for characters. This uses a convoluted workaround:

* Loop over the string omitting the last character, which is removed using `chop()`.
* Convert the current character to a string using `string()`.
* Convert the trailing digit, which is also a character, into an integer. However, note that, for example, `int('4')` does not return 4. Rather, it returns the codepoint, which in this case is 52. Thus we can subtract 48 to get back the actual integer.
* Repeat `string(b)` according to `int(p[end]) - 48`.

Examples:

```
julia> f("ab3c5")
"aaabbbccccc"

julia> f("a0b3")
"bbb"

julia> f("13b1")
"111b"

```
> 1 votes

# Answer
# Java 7, 175 bytes

```
String c(String s){String r="",a[];for(String x:s.split("(?<=(\\d)(?!\\d))")){a=x.split("");for(int i=0,j,l=a.length-1;i<l;i++)for(j=0;j++<new Short(a[l]);r+=a[i]);}return r;}

```

The challenge is harder than it looks, imo..

**Ungolfed & test code:**

Try it here.

```
class M{
  static String c(String s){
    String r = "",
           a[];
    for(String x : s.split("(?<=(\\d)(?!\\d))")){
      a = x.split("");
      for(int i = 0, j, l = a.length-1; i < l; i++){
        for(j = 0; j++ < new Short(a[l]); r += a[i]);
      }
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c("ab3c5"));
    System.out.println(c("a0b3"));
    System.out.println(c("13b1"));
    System.out.println(c("a13b1"));
    System.out.println(c("a123b1"));
    System.out.println(c("aa2a1b1"));
    System.out.println(c("123"));
  }
}

```

**Output:**

```
aaabbbccccc
bbb
111b
aaa111b
aaa111222b
aaaaab
111222

```
> 0 votes

---
Tags: code-golf, string
---


title: Display a Connect Four game

text:
# Question
Title: Display a Connect Four game
Connect Four is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.

**Input**

* Width `w` and Height `h` of the grid, both positive integers.
* Sequence of columns `c1`, `c2`, ..., `cn` chosen by the players, in any reasonable format (list, array etc.); either 0-based (`0` to `w-1`) or 1-based (`1` to `w`) indexing can be used.

It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain `-3` or `w+50`) and that any column number appears at most `h` times in the sequence (so a column can't be chosen once it is full).

Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.

**Output**

* Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.

For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.

For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.

**Test cases**

Here, string output is used, with `X`, `O`, `.` denoting "occupied by Player 1", "occupied by Player 2", "empty".

```
IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.

IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
                              3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO

IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
                              0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX

IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
                              2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO

IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10  [1-based]
                                0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0  9 0  9  [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO

```

**Shortest code in bytes wins.**

# Answer
> 0 votes
# Pyth, 19 bytes

```
m.[2vz%R2fq@QTd_UQE

```

Try it online.

Takes input as `c,o,l,s\nheight\nwidth`, 0-indexed. Outputs a list of columns (transposed), using `012` for player 1, player 2, empty respectively.

# Answer
> 3 votes
# Vim, 34 bytes

`@wO-<Esc><C-V>(d@hpqq<C-O>+D@"G+bs<C-R>=!@.<CR><Esc>@qq@q`

Input is width in the `"w` register, height in the `"h` register, and the 1-indexed moves in the buffer, one per line. Output is a transposed grid with `-` as blank, `1` as player 1, and `0` as player 2 (with a bunch of newlines at the end).

**To clarify**, if you want Height 6, Width 7: type `qh6qqw7q` before starting.

* `@wO-<Esc><C-V>(d@hp`: Use the height and width in the registers to make a transposed grid of `-`s. Note that `(` is run from the last line of the grid, one above the moves. This sets up the jump list.
* `<C-O>+D@"G`: The `<C-O>` uses the jump list to move back to before the last `G`, always to the line above the next number. `@"G` moves to the line number indicated by the deleted text. `+` not only moves the cursor, but it's the failure point; when it runs on the last line, the macro dies.
* `+b`: This maneuver goes to the first `-` in the line, even if it's the first character. (`f-` would go to the second character if the line was still all `-`s.)
* `s<C-R>=!@.`: Replaces a `-` with the last insert `@.`, but NOTted. First time through, the previous insert of `-` will NOT to `1` because that's the way Vim is. After that, it will alternate between `0` and `1`.

### Example

Start with the moves in the buffer:

```
4
4
5
5
6
7
3

```

Make sure you're on line 1 with `gg`, clear `"q` with `qqq`, set up the registers for width 7, height 6 with `qw7qqh6q`. Then run the solution above and get the following output (with newlines at the end):

```
------
------
1-----
10----
10----
1-----
0-----

```

# Answer
> 2 votes
# Python 2, ~~91~~ 88 bytes

```
w,h,s=input()
i,x=0,['']*w
for c in s:x[c]+='XO'[i%2];i+=1
for c in x:print(c+'.'*h)[:h]

```

Since transposed is fine, this prints the board sitting on its right hand side.
**repl.it**

# Answer
> 0 votes
# Python 2, ~~143~~ ~~131~~ 107 Bytes

This doesn't use any real fancy tricks, ~~except list transposition to make index access easier~~ since we can print the board transposed. Definitely not done with this just yet. Moves are taken as 0-based numbers. Byte count comes before commenting.

Jonathan Allan had a better approach to building the board, mine is improved slightly since the slicing is a bit shorter `[-j:] -> [:j]` and the list comprehension helps shorten printing.

```
i,j,k=input()                                     # split up the input
t=0                                               # keep track of whose move it is
g=i*['']                                          # board init
for b in k:g[b]+='XO'[t%2];t+=1                   # read moves sequentially, place pieces
print'\n'.join(''.join((m+'.'*j)[:j])for m in g)  # build the board

```

Example Input: `[7, 6, [3, 3, 4, 4, 5, 6, 2]]`

Example Output:

```
......
......
X.....
XO....
XO....
X.....
O.....

```

Try it online or view all test cases.

# Answer
> 0 votes
# JavaScript (ES6), 62 ~~69~~

**Edit** 7 bytes saved thx @Arnauld

I have used this kind of string representation when logging the board status in my connect four player. It's short coded and easy to understand at first sight.

Input is 0 based

```
(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

```

More in line with the OP examples, this is 93 bytes

```
(w,h,s)=>s.map((v,i)=>r[v]+=i%2,r=Array(w).fill(``))&&r.map(r=>r+Array(h+1-r.length)).join`
`

```

(note: here the `fill```  trick won't work)

Output for `[7, 6, [3, 3, 4, 4, 5, 6, 2]]`

```
,,,,,,
,,,,,,
0,,,,,
01,,,,
01,,,,
0,,,,,
1,,,,,

```

**Test**

```
f=(w,h,s)=>s.map((v,i)=>r[v]+=i&1,r=Array(w).fill`|`)&&r.join`
`

console.log=s=>O.textContent+=s+'\n'

;[
  [1, 1, []]
, [7, 6, [3, 3, 4, 4, 5, 6, 2]]
, [5, 5, [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]]
, [4, 4, [2, 2, 1, 3, 2, 1, 3, 1, 1, 2, 3, 3, 0, 0, 0, 0]]
].forEach(t=>{
  var w=t[0],h=t[1],s=t[2],r=f(w,h,s)
  console.log(w+' '+h+' ['+s+']\n'+r+'\n')
})
```

```

```

# Answer
> 0 votes
## JavaScript (ES6), 121 bytes

```
(w,h,a,r=Array(w).fill``)=>a.map((c,j)=>r[c]+="XO"[j%2])&&[...Array(h)].map((_,i)=>r.map(s=>s[h+~i]||`.`).join``).join`\n`

```

0-indexed. I wanted to see how well I could match the example output, but most of the code seems to be taken up by the rotation.

# Answer
> 0 votes
# Java 7, 209 bytes

Not very inspiring.Simple and plain solution.

```
char[][]f(int w,int h,int[]a){char[][]b=new char[h][w];for(char[]r:b)Arrays.fill(r,'.');for(int l=a.length,i=l-1,j,c=0;i>-1;b[h-c-1][a[i]]=i--%2==0?'X':'O',c=0){for(j=i-1;j>-1 ;)if(a[j--]==a[i])c++;}return b;}

```

# Ungolfed

```
 char[][] f( int w , int h , int[]a ) {
 char[][] b = new char [h][w];
for ( char[] r : b)
    Arrays.fill( r , '.') ;

for ( int l = a.length,i = l-1 , j , c = 0 ; i > -1 ;
                         b[h-c-1][a[i]] = i--%2 == 0 ? 'X' : 'O', c = 0 ) {
    for ( j = i-1 ; j > -1 ;)
        if ( a[j--] == a[i] )
              c++ ;
      }

return b;
}

```

# Answer
> 0 votes
# Scala, 122 bytes

```
def%(w:Int,h:Int,m:Int*)=((Seq.fill(w)(Nil:Seq[Int]),1)/:m){case((a,p),x)=>(a.updated(x,a(x):+p),-p)}._1.map(_.padTo(h,0))

```

Ungolfed:

```
def f(w:Int,h:Int,m:Int*)=
  m.foldLeft((Seq.fill(w)(Nil:Seq[Int]),1)){
    case((res,player),x)=>
      (res.updated(x,res(x):+player), -player)
  }._1.map(_.padTo(h,0))

```

Explanation:

```
def%(w:Int,h:Int,m:Int*)=        //define a method
  (
    (                            //with a tuple of
      Seq.fill(w)(Nil:Seq[Int]),   //a Sequence of w empty sequences
      1                            //and 1
    )                            //as a start value,
    /:m                          //foldLeft the moves
  ){                             //using the following function,
    case((a,p),x)=>                //which takes the result, the player and the x coordinate
      (                            //return a tuple of
        a.updated(x,a(x):+p),        //the seq with index x with p appended
        -p                           //and the other player
      )
  }._1.map(                      //take the resulting seq and foreach column
    _.padTo(h,0)                 //append 0 until the length is h
  )

```

Returns a sequence of the columns in bottom-to-top order. The players are represented as `-1` and `1`, empty cells are `0`.

---
Tags: code-golf, grid, game
---


title: Determine winner of Connect 4

text:
# Question
Title: Determine winner of Connect 4
You are given a partially filled Connect 4 grid (7x6).

```
O X
O X
X O X O     O
X O X O   X X
O X X X O O X
O O O X X O X

```

(Input can be given as a 1D or 2D array and as letters or numbers, etc.)

Assume that

* X started the game.
* Nobody has won yet.
* Players may not have played well until now, but now onwards they will both employ optimal strategies.
* Input grid is not faulty.

You must output a single value that indicates which player wins (or a draw)

Code golf challenge; so shortest code wins. Your program does not have to actual compute the output in reasonable amount of time, but you should be able to prove that the output will be obtained correctly in a finite amount of time.

# Answer
# Perl, ~~119~~ ~~118~~ 117 bytes

Includes +4 for `-0p`

Give rotated board padded with spaces on STDIN (gravity pulls stones to the right)

```
connect4.pl
  OXXX
   XOO
    OX
  OOXX
  XXXO
XXOOXO
OOXXOO
^D

```

`connect4.pl`:

```
#!/usr/bin/perl -p0
y/XO/OX/if$^S|y/X//>y/O//;$_=$$_||=/Z@{[map"|O".".{$_}O"x3,0,5..7]}/sx||s% (?! )%$_="$`X$'";do$0%eg?/1/?3:1+/2/:2

```

Prints `3` if player to move wins, `1` if player to move loses and `2` for a draw.

On older perls you can use a literal `^S` to gain one byte. If you don't mind ***extreme*** inefficiency you can leave out the `$$_||=` (transposition table) and gain 6 more bytes. If you leave out the `$_=` it will show you where to play instead of the result (play on `1` and win if there is one, play on `2` and draw if there is one or play on any `3` and lose)

Builds and evaluates a complete minimax tree. You will run out of memory and time unless the board is already reasonably well filled.
> 18 votes

---
Tags: code-golf, game, grid, board-game
---