title: Operator ASCII art

text:
# Question
Title: Operator ASCII art
### Challenge

Given an ASCII operator from the list below and a number n, draw an ASCII representation of the operator using that operator as the character with the line segments of the operator having length *n*.

### Input

An ASCII character from the list `= + - x /` and an integer `n` where `n >= 1`. (I'm using `x` instead of `*` and `/` instead of `÷`, but you could use either one, whichever is easier). For `+` and `x`, you only have to handle odd numbers to avoid issues with alignment.

### Output

An ASCII drawing of the operator composed of the character with segments of length n. Horizontal portions should have spaces between the characters to offset vertical/horizontal distance differences.

### Rules

This is , so shortest code in bytes wins. Standard loopholes are forbidden.

### Examples

Input: `+ 3`

```
  +
+ + +
  +

```

Input: `= 4`

```
= = = =
= = = =

```

Input: `= 10`

```
= = = = = = = = = =
= = = = = = = = = =

```

Input: `- 2`

```
- -

```

Input: `/ 10`

```
         /
        /
       /
      /
     /
    /
   /
  /
 /
/

```

Input: `x 7`

```
x     x
 x   x
  x x
   x
  x x
 x   x
x     x

```

# Answer
## Pip, ~~62~~ ~~59~~ 56 bytes

55 bytes of code, +1 for `-S` flag.

```
[sXbRA_AEv-_aM,b(Y^aWR_Xb/2s)MyRVsX,b.aYaXbJsxyRL2x]@Aa

```

Note that this solution works with input of `÷` for division and `*` for multiplication, though it uses those characters to draw ASCII-art `/` and `x`, respectively. OP has clarified that this is okay. Try it online!

### How?

Here's a partially spaced and commented version. Note that `a` and `b` are the command-line args, i.e. the operator and the size respectively. The `-S` flag controls how lists are output: it joins on newlines first, but joins any nested lists on spaces.

```
[                 Build a list of all possible figures:
 sXbRA_AEv-_aM,b   0 - Multiplication
 (Y^aWR_Xb/2s)My   1 - Addition
 RVsX,b.a          2 - Division
 YaXbJs            3 - Subtraction
 x                 4 - Empty
 yRL2              5 - Equals
 x                 6 - Empty
] @ Aa            Index, mod 7, with ASCII value of a

```

And here are the individual sections:

**Multiplication**

For each row in the figure, we generate a string of spaces and then replace two of them with the input character. For row `i`, we want to replace the spaces at index `i` and `b-1-i`; but note that the latter can use the negative index `-1-i`. (It's even shorter because the variable `v` is preinitialized to negati**v**e 1.)

```
sXbRA_AEv-_aM,b
            M,b  Map this function to range(b):
sXb                Space, repeated b times
     _             Function arg
      AE           (Implicitly) convert to list and append element...
        v-_        -1 minus function arg
   RA              Replace the characters at those indices...
           a       ... with input character
                 The resulting list is output with one item per line

```

**Addition**

Using the strategy from my Draw a hollow square answer, we define a function that wraps a `+` in `b/2` copies of its argument and returns the result as a list of characters. (Integer division `//` isn't necessary because the string repetition operator `X` automatically truncates to integer.) First, we call this function on a space, giving `[" ";" ";"+";" ";" "]`; then, we map the same function to that result, giving `[" ";" ";"+";" ";" "]` on most lines but `["+";"+";"+";"+";"+"]` on the center line. This nested list is then output, because of the `-S` flag, with spaces between all characters on a row and newlines between rows.

```
(Y^aWR_Xb/2s)My
                 Anonymous function:
      _Xb/2        Function arg, repeated b/2 times (implicitly rounded down)
   aWR             Wrap a in two copies of the above
  ^                Split resulting string into list of chars
 Y               Yank that function into y
(          s)    Apply function y to space
             My  Map y to that result

```

**Division**

Each row has between `b-1` and `0` spaces, followed by the input character `a`.

```
RVsX,b.a
    ,b    Range(b)
  sX      Space, repeated that many times (works itemwise)
      .a  Concatenate a (itemwise)
RV        Reverse (puts the larger number of spaces at the beginning)
          Outputs newline-separated

```

**Subtraction**

Make a space-separated row of the input character. Save a copy for later.

```
YaXbJs
 aXb    b copies of a
    Js  Join on space
Y       Yank into y (overwrites the function from earlier, but we're done using it anyway)
        This is a string, so it just gets output

```

**Equals**

The subtraction step stored half of what we need in `y`--just double it.

```
yRL2  (Implicitly) convert y to list and repeat it twice
      Outputs newline-separated

```

The dummy `x` values are there to pad the main list so that the modular indexing gives a unique index for each input character in `+-*÷=`.
> 5 votes

# Answer
# , ~~78, 72, 71, 68, 65, 63, 62~~, 61 bytes

```
Ç=ü-/Àé X
ç^Ó/é Àä$
ç+/ÀÄM|ÀR+
ç=/Ä
ç¯/lòhYpX
çx/rxòl3Äjxlrx

```

Try it online!

As always, the neck-and-neck battle with 05AB1E is really fun!

Since this contains non-ASCII characters, here is a hexdump:

```
0000000: c73d fc2d 2fc0 e920 580a e75e d32f e920  .=.-/.. X..^./.
0000010: c0e4 240a e72b 2fc0 c44d 7cc0 522b 200a  ..$..+/..M|.R+ .
0000020: e73d 2fc4 0ae7 af2f 6cf2 6859 7058 0ae7  .=/..../l.hYpX..
0000030: 782f 7278 f26c 33c4 6a78 6c72 78         x/rx.l3.jxlrx

```

This does create leading spaces in the output for `=` and `-`, but this seems to be allowed. If this is not allowed, feel free to comment and I'll roll it back.

# Explanation

The "global command" (e.g. `ç`) applies a certain set of commands to every line that matches a certain regex. The syntax is

```
ç<compressed regex>/<commands>

```

This is the easiest way of simulating a conditional/switch statement. In my original answer, I simply created the entire ASCII-art on the right-hand side for each different character we need to search for. However, a lot of these outputs require similar commands. So I combined them. The first command ('Ç') is actually the inverse of the global command, it applies the command to every line *not* matching the regex. So the first command is:

```
Ç=ü-        " On every line not containing an '=' or an '-' (e.g. inputs '/', '+', and 'x'):
    /Àé     "   Insert *n* spaces
        X   "   Delete one of them

```

The following command is for inputs '=' and '-'. These two are conveniently easy and similar. After this command, we need no more processing for `-`.

```
ç^Ó         " On every line that starts with non-whitespace (e.g. every line not affected by our previous command):
   /é       "   Insert one space
            "   Move back a character
      À     "   Make *n* copies
       ä$   "   Of every character on this line

```

From here we just do some extra commands for each individual possible input. For `+`:

```
ç+/         " On every line containing a '+':
   ÀÄ       "   Make *n* copies of this line
     M|     "   Move to the first character of the middle line
       À    "   *n* times:
        R+  "   Replace the next two characters with '+ '

```

The command for equals is very straightforward. We just duplicate it with `Ä`. For `/`:

```
ç¯          " On every line containing a '/':
  /l        "   Move one character to the right
    ò       "   Recursively:
     h      "     Move one character to the left
      Yp    "     Make a copy of this line
        X   "     Delete one character
         ò  "   End loop (implicit)

```

The last one is the most complicated. It is basically a port of this answer.

```
çx              " On every line containing a 'x':
  /rx           "   Replace the first character with an 'x'
     ò          "   Recursively:
      l         "     Move one char to the right
       3Ä       "     Make 3 copies of this line
         j      "     Move down one line
          x     "     Delete one char
           l    "     Move one char to the right
            rx  "     Replace this char with an 'x'

```
> 13 votes

# Answer
# 05AB1E, ~~81~~ ~~76~~ ~~74~~ ~~73~~ ~~70~~ ~~69~~ ~~68~~ ~~65~~ ~~64~~ ~~62~~ ~~60~~ ~~59~~ ~~57~~ 56 bytes

Currently **in war** with the *V answer*. I'm coming for you Dr. McMoylex :p.

Also **in war** with the *Pip answer*. I'll be watching you Mr. DLosc.

---

Code:

```
Ç6&"¹s<ú.s.Bívy¹'xQiÂðñ}, ¹×S)»¹'=Qƒ= ;ƒ¹})D¦»»Rû.c"#è.V

```

Or in a more readable form:

```
  Ç6&
"¹s<ú.s.Bívy¹'xQiÂðñ},
 ¹×S)»¹'=Qƒ=
 ;ƒ¹})D¦»»Rû.c"
#è.V

```

Uses the **CP-1252** encoding. Try it online!
> 13 votes

# Answer
# Python 3, ~~304~~ ~~283~~ 278 bytes

Simple enough, just makes a matrix of chars and applies the different operations based on which one it is. The `=` and `-` have trailing spaces if that's not too bad.

EDIT: Thanks to @Shebang and @Rod for their suggestions which ended up saving 21 bytes!

EDIT2: Thanks to @Artyer for saving 5 bytes!

```
t,s=input().split()
s=int(s)
r=range(s)
b=[[' ']*s for x in r]
exec(['for x in r:b[s//2][x]=b[x][s//2]=t','b=[t*s]'+'*2'*(t=='='),'for x in r:b[x][s-x-1]='+'b[x][x]='*(t=='x')+'t'][(t>'+')+(t in'x/')])
if t in'-=+':b=[[x+' 'for x in l]for l in b]
print(*map(''.join,b),sep='\n')

```
> 7 votes

# Answer
# JavaScript (ES6), ~~238~~ ~~225~~ ~~215~~ ~~202~~ 196 bytes

```
(c,n)=>[...Array(i=n*(c=="="?4:c+1-1?2:c<"-"?n+n:n+1))].map(_=>--i%(n+(c=='/'|c>'w'||n))?c>'w'?i%n&&~-i%(n+2)?" ":c:c<'-'?i%(n*2)-n&&(~i&1|(n/2^i/n/2))?" ":c:c=="/"?i%n?" ":c:i%2?c:" ":`
`).join``

```

Could probably be golfed, but it's a start.
> 7 votes

# Answer
# Scala, 275 bytes

```
(i,c)=>if(c<44){val b=(" "*(i-1)+"+\n")*((i-1)/2)
b+"+ "*i+"\n"+b}else
if(c<46)"- "*i else
if(c<48)i-1 to(0,-1)map(" "*_+"/\n")mkString else
if(c<62)"= "*i+"\n"+"= "*i
else{val a=0 to i/2-1 map(x=>" "*x+"x"+" "*((i/2-x)*2-1)+"x"+" "*x+"\n")mkString;a+" "*(i/2)+"x"+a.reverse}

```

Usage:

```
val f:((Int,Char)=>String)=...
print(f(10, '/'))

```

Explanation:

The code tests for the ascii value of the char to choose the right way of generating the image. The ascii values of the operators in question are: `('+' -> 43), ('-' ->45), ('/' -> 47), ('=' -> 61), ('x' -> 120)`

```
(i,c)=>                              //define a function
  if(c<44){                            //if c is a plus
    val b=(" "*(i-1)+"+\n")*((i-1)/2)    //define the top/bottom part b as (i-1)/2 times (i-1) spaces, a plus sign and a newlineine
    b+"+ "*i+"\n"+b                      //return b, i times a plus and a space, a newline and b
  }else if(c<46)                       //if c is a '-'
    "- "*i                               //return "- " repeated i times
  else if(c<48)                        //if c is a '/'
    i-1 to(0,-1)                         //create a range from i-1 to 0 in steps of -1
    map(" "*_+"/\n")                     //map each number to that number of spaces plus a "/" and a newline
    mkString                             //join them together
  else if(c<62)                        //if c is '='
    "= "*i+"\n"+"= "*i                   //return "= " repeated i times, a newline and "= " repeated i times again
  else{                                //if c if 'x'
    val a=                               //define a, which will be the top part, as...
      0 to i/2-1                         //a range from 0 to i/2-1
      map(n=>                            //map each number n to
        " "*n                              //n spaces
        +"x"                               //plus an "x"
        +" "*((i/2-n)*2-1)                 //plus ((i/2)-n)*2-1 spaces
        +"x"                               //plus an "x"
        +" "*n                             //plus n spaces
        +"\n"                              //and a newline
      )mkString;                         //join them
    a+" "*(i/2)+"x"+a.reverse          //return a, i/2 spaces, "x" and the reverse of a
  }

```
> 6 votes

# Answer
## JavaScript (ES6), 156 bytes

```
(c,n)=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>({'/':a=i+j-n,x:a&&i-j,'-':a=i+i-n,'+':a&&j+j-n,'=':a+2&&a-2}[c]?' ':c)).join(c=='='|c<'/'?' ':'')).join`\n`

```

Where `\n` represents the literal newline character.
> 5 votes

# Answer
# Dyalog APL, ~~91~~ 86 bytes

Needs `⎕IO←0`, which is default on many systems. Takes **n** as left argument, and one of **\+ - × ÷ =** as right argument.

```
{s←⌈⍎⍕3⍵2
t←' '⍵
d←⌽∘.=⍨⍺
s∊2 6:t[d∨⌽d∧6=s]
5=s:t[↑,/2↑¨∨/¨(⌊⍺÷2)=⍳⍺ ⍺]
(2-s)(2×⍺)⍴t}

```

### Explanation

```
{
    s ← ⌈ ⍎ ⍕ 3 ⍵ 2             ⍝ calculate ceil(3 f 2), where f is the given symbol
    t ← ' '⍵                    ⍝ create a string with a space before the symbol
    d ← ⌽ ∘.=⍨ ⍺                ⍝ Boolean \ diagonal
    s ∊ 2 6: t[d ∨ ⌽ d ∧ 6 = s] ⍝ if ÷ or × index t with one or both diagonals
⍝ find coordinates that are in the middle of at least one dimension
⍝ pad with zeros for spacing
⍝ use that to index into t
    5 = s: t[ ↑ ,/ 2↑¨ ∨/¨ (⌊ ⍺ ÷ 2) = ⍳ ⍺ ⍺]
⍝ - or =:
    (2 - s) (2 × ⍺) ⍴ t       ⍝ one or two rows of double-spaced symbols
}

```
> 4 votes

# Answer
# Mathematica, 191 bytes

```
e=#~Mod~2==1&;StringRiffle[Normal@SparseArray[{a_,b_}/;(a+b==d+1||a==b)[e@b&&a<3,,e@b&&(a==⌈d/2⌉||b==d),,e@b&&a<2,,a+b==d+1][[Last@ToCharacterCode@#~Mod~10]]:>#,{d=#2,2d-1}," "],"
"," "]&

```

Anonymous function. Takes a string and a number as input, and returns a string as output. Not the shortest by far, but still fun to write.
> 3 votes

# Answer
# C, 396 bytes

```
#define p(x) printf(x);
i,j,k,m;f(char s,int n){i=k=0;if(s==45)for(;i<n;++i)p("- ")m=n/2;if(s==43)for(;i<n;++i)for(j=0;j<=m;++j)if(i-m)p(j-m?"  ":"+\n")else{for(;k<n;++k)p("+ ")p("\n")j+=m;}if(s==61)for(;i<2;++i){for(k=0;k<n;++k)p("= ")p("\n")}j=n;if(s==47)for(;i<n;++i){--j;for(k=0;k<j;++k)p(" ")p("/\n")}if(s==120)for(;i<n;++i){k=m-abs(m-i);for(j=0;j<n-k;++j)p(j-k?" ":"x")p(i-m?"\bx\n":"\n")}}

```

Call with:

```
int main()
{
   f('x', 5);
   return 0;
}

```
> 3 votes

# Answer
# SOML, ~~104~~ 100 bytes (non-competing)

```
    Cd³³b»E +=?ce*d+e{t}bd*Oe{t}} ==?b*tt} -=?b*t} /=?bc*b{j:d+p}} x=?"”cb*e{jj⁴⁴d;d+++tGG;c+;}XOdoe{O

```

This is kind-of competing as I'm pretty sure that everything I used here has docs on github before this questions posting date but the parser doesn't have support for some functions I used so idk.
> 2 votes

# Answer
# PHP, ~~306~~ ~~292~~ ~~281~~ ~~282~~ ~~281~~ ~~275~~ 270 bytes

```
$r=str_pad("",2*$n=$argv[2],($c=$argv[1])." ")."\n";if(",">$c)$r=($m=str_repeat(str_pad($c,$n," ",0)."\n",$n/2))."$r$m";if(9<$c)$r.=$r;if(w<$c)for($r=$c;$i<$n;$r[$i*(2+$n)]=$r[++$i*$n-1]=x)$r[$i*$n+$i+$n]="\n";if("/"==$c)for($r=$s="";$i++<$n;$s.=" ")$r="$s/\n$r";echo$r;

```

Ooh this is bulky ... needs further golfing.
I could save 4 bytes with physical linebreaks or one byte with putting "\n" into a variable.
> 2 votes

# Answer
# C#, 744 Bytes

*It's like 1 million characters long, I think, but I don't care, I am just so happy that I solved this...*

Golfed:

```
string A(string s,int n){string O="";Func<string,int,string>R=(a,b)=>{return string.Join("",Enumerable.Repeat(a,b))+"\r\n";};switch(s){case"+":for(int i=0;i<n;i++){if(i==n/2){O+=R("+",n);}else{O+="+".PadLeft(n-n/2,' ').PadRight(n-n/2,' ')+"\r\n";}}return O;case"=":return R("=",n)+R("=",n);case "-":return R("-",n);case "/":for(int i=n;i>0;i--){O+="/".PadLeft(i)+"\r\n";}return O;case "x":int x=0;string[]r=new string[n];for(int i=n;i>0;i--){if(n-x-x<0){O+="x".PadLeft(x+1)+"\r\n";break;}string row=string.Join("",Enumerable.Repeat(" ",x))+"x"+string.Join("",Enumerable.Repeat(" ",n-x-x))+"x"+"\r\n";O+=row;x++;r[x]=row;if(i==n/2)break;}for(int i=r.Length-1;i>0;i--){if(string.IsNullOrEmpty(r[i]))continue;O+=r[i];}return O;default:return "";}}

```

Ungolfed:

```
public string A(string s, int n)
{
  string O = "";

  Func<string, int, string> R = (a, b) =>
  {
    return string.Join("", Enumerable.Repeat(a, b)) + "\r\n";
  };

  switch (s)
  {
    case "+":
      for (int i = 0; i < n; i++)
      {
        if (i == n / 2)
        {
          O += R("+", n);
        }
        else
        {
          O += "+".PadLeft(n - n / 2, ' ').PadRight(n - n / 2, ' ') + "\r\n";
        }
      }
      return O;
    case "=":
      return R("=", n) + R("=", n);
    case "-":
      return R("-", n);
    case "/":
      for (int i = n; i > 0; i--)
      {
        O += "/".PadLeft(i) + "\r\n";
      }
      return O;
    case "x":
      int x = 0;
      string[] r = new string[n];
      for (int i = n; i > 0; i--)
      {
        if (n - x - x < 0)
        {
          O += "x".PadLeft(x + 1) + "\r\n";
          break;
        }
        string row = string.Join("", Enumerable.Repeat(" ", x))
          + "x"
          + string.Join("", Enumerable.Repeat(" ", n - x - x)) + "x" + "\r\n";
        O += row;
        x++;
        r[x] = row;
        if (i == n / 2)
          break;
      }
      for (int i = r.Length - 1; i > 0; i--)
      {
        if (string.IsNullOrEmpty(r[i]))
          continue;
        O += r[i];
      }
      return O;
    default:
      return "";
  }
}

```

Testing:

```
+: 3, 5, 7, 9, 11
/: 7, 8, 9, 10
-: 3, 4, 5, 6
=: 3, 4, 5, 6, 7
x: 5, 7, 9, 11

```

Too much to paste and format here, I created a pastebin:

Pastebin
> 2 votes

# Answer
## C, 331 Bytes

```
i,j;f(o,n){if(47==o)for(i=n;i;puts("")){for(j=i--;j--;putchar(j?32:o)){}}
if(43==o)for(i=n;i--;puts("")){for(j=n;j--;printf(i==n/2||!j?"+ ":" ")){}}
if(45==o)for(i=n;i--;putchar(o)){}
if(61==o)for(i=3;i--;puts("")){for(j=n;j--;putchar(i&1?32:o)){}}
if(120==o)for(i=n;i;puts("")){for(j=0;j++<n;putchar(j==i||j==n-i+1?o:32)){}i--;}}

```

The operator is passed as ASCII code into `o` and the character count into `n`. I only added spaces between horizontally consecutive characters into the plus sign, since this was the only one where the output would have been distorted if I hadn't and in the task it only said "should". I use two nested loops counting down (except for `-` where I only need one line).

`=` Three Lines, one of them empty, straight forward

`+` using `printf` because of the spaces

`-` straight forward

`/` have the inner loop print at zero and start at the outer loop's counter

`x` have the inner loop print at the outer loop's counter and its "inverse" `n-i`. Still need to look at why I'am off-by-one here.

Sample call:

```
#include <stdio.h>
/*  =       61
    +       43
    -       45
    /       47
    Space   32
    x       120
*/
int main(int argc, char **argv){
    printf("%s\n%s\n",argv[1], argv[2]);
    f(*argv[1],strtol(argv[2],NULL,10));
}

```
> 2 votes

# Answer
# Lua, ~~402~~ ~~344~~ 312 bytes

312:

```
r,p,b,x=string.rep,print,' ','x'function d(s,n)h,l=(n+1)/2,s..b;e=r(l,n)if s=='-'then p(e)elseif s=='='then p(e)p(e)else for f=1,n do p(s=='/'and(r(b,n-f)..s)or s=='+'and(f~=h and r(' ',n-1)..'+'or r('+ ',n))or f<h and r(b,f-1)..x..r(b,n-2*f)..x or f>h and r(b,n-f)..x..r(b,2*f-2-n)..x or r(b,f-1)..x)end end end

```

344:

```
r,p,b,x=string.rep,print,' ','x'function d(s,n)h,l=(n+1)/2,s..b;e=r(l,n)if s=='-'then p(e)elseif s=='='then p(e)p(e)else for f=1,n do if s=='/'then p(r(b,n-f)..s)elseif s=='+'then p(f~=h and r(' ',n-1)..'+'or r('+ ',n))elseif s=='x'then p(f<h and r(b,f-1)..x..r(b,n-2*f)..x or f>h and r(b,n-f)..x..r(b,2*f-2-n)..x or r(b,f-1)..x)end end end end

```

402:

```
r,p,b,x=string.rep,print,' ','x'function d(s,n)h=(n+1)/2;if s=='-'then p(r(s..b,n))end;if s=='='then p(r(s..b,n))p(r(s..b,n))end;if s=='/'then for i=1,n do p(r(b,n-i)..s)end end;if s=='+'then for i=1,n do p(i~=h and r(' ',n-1)..'+'or r('+ ',n))end end;if s=='x'then for i=1,n do if i<h then p(r(b,i-1)..x..r(b,n-2*i)..x)elseif i>h then p(r(b,n-i)..x..r(b,-n+2*i-2)..x)else p(r(b,i-1)..x)end end end end

```

90 characters reduced and it's now painful to look at even when expanded. :|
> 1 votes

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


title: Draw a Straight Line

text:
# Question
Title: Draw a Straight Line
Draw a simple ASCII art image containing a straight line. It's similar to this and this but with different specifications.

**Input**

You can modify this input format to suit your code.

* integer `width`
* integer `height`
* integer `x0`
* integer `y0`
* integer `x1`
* integer `y1`

**Output**

A filled ASCII art image of the specified width and height containing a line from pixel `(x0, y0)` to pixel `(x1, y1)`.

Any standard form of text output is acceptable, but don't use built in line drawing functions.

**Details**

The line must be drawn using a single printable character (such as `#`), while the background is filled with a different character (such as `.`). You must print the necessary trailing characters so that the image size is correct.

Pixel coordinates can be 0-indexed or 1-indexed and can start in any corner of the image. The line should be drawn by imagining a 0-width sub-pixel line connecting the centers of the start and end pixels. Every pixel that the line enters should be filled in.

**Winning**

Usual code-golf rules. Shortest code wins.

**Examples**

```
IN: width, height, x0, y0, x1, y1

IN: 7, 6, 0, 0, 6, 5
OUT:
.....##
....##.
...##..
..##...
.##....
##.....

IN: 3, 3, 1, 1, 1, 1
OUT:
...
.#.
...

IN: 3, 3, 0, 2, 2, 0
OUT:
#..
.#.
..#

IN: 6, 3, 0, 0, 5, 2
OUT:
....##
.####.
##....

IN: 4, 4, -1, -1, 0, 3
OUT:
#...
#...
#...
....

```

# Answer
## Mathematica, ~~166~~ 137 bytes

```
l:={i,j};s=Sign;f[p_,q_,h_,w_]:=Grid@Table[(1-Max[s[p-l]s[q-l],0])Boole[Abs@Mean[s@Det@{p-l+#,p-q}&/@Tuples[.5{1,-1},2]]<.6],{i,h},{j,w}]

```

More readable version:

```
l := {i, j}; s = Sign;
f[p_, q_, h_, w_] :=
 Grid@Table[(1 - Max[s[p - l] s[q - l], 0]) Boole[
     Abs@Mean[
        s@Det@{p - l + #, p - q} & /@
         Tuples[.5 {1, -1}, 2]] < .6], {i, h}, {j, w}]

```

This defines a function called `f`. I interpreted the input and output specifications fairly liberally. The function `f` takes input in the format `f[{x0, y0}, {x1, y1}, height, width]`, and the grid is 1-indexed, starting in the top left. Outputs look like

with the line displayed as `1`s and the background as `0`s (shown here for `f[{2, 6}, {4, 2}, 5, 7]`). The task of turning a Mathematica matrix of `1`s and `0`s into a string of `#`s and `.`s has been golfed in many other challenges before, so I could just use a standard method, but I don't think that adds anything interesting.

### Explanation:

The general idea is that if the line passes through some pixel, then at least one of the four corners of the pixel is above the line, and at least one is below. We check if a corner is above or below the line by examining the angle between the vectors (`{x0,y0}` to corner) and (`{x0,y0}` to `{x1,y1}`): if this angle is positive, the corner is above, and if the angle is negative, the corner is below.

If we have two vectors `{a1,b1}` and `{a2,b2}`, we can check if the angle between them is positive or negative by finding the sign of the determinant of the matrix `{{a1,b1},{a2,b2}}`. (My old method of doing this used arithmetic of complex numbers, which was way too…well, complex.)

The way this works in the code is as follows:

* `{p-l+#,p-q}&/@Tuples[.5{1,-1},2]` gets the four vectors from `{x0,y0}` and the four corners of the pixel (with `l:={i,j}`, the coordinates of the pixel, defined earlier), and also the vector between `{x0,y0}` and `{x1,y1}`.
* `s@Det@...` finds the signs of the angles between the line and the four corners (using `s=Sign`). These will equal -1, 0 or 1.
* `Abs@Mean[...]<.6` checks that some of the angles are positive and some negative. The 4-tuples of signs that have this property all have means between -0.5 and 0.5 (inclusive), so we compare to 0.6 to save a byte by using `<` instead of `<=`.

There's still a problem: this code assumes that the line extends forever in both directions. We therefore need to crop the line by multiplying by `1-Max[s[p-l]s[q-l],0]` (found by trial and error), which is `1` inside the rectangle defined by the endpoints of the line, and `0` outside it.

The rest of the code makes a grid of these pixels.

(As a bonus, here's an earlier attempt with a completely different method, for 181 bytes:)

```
Quiet@Grid@Table[(1-Max[Sign[{i,j}-#3]Sign[{i,j}-#4],0])Boole[#3==#4=={i,j}||2Abs@Tr[Cross@@Thread@{{i,j},#3,#4}]/Norm[d=#3-#4]<2^.5Cos@Abs[Pi/4-Mod[ArcTan@@d,Pi/2]]],{i,#},{j,#2}]&

```
> 2 votes

# Answer
# CJam, 122 bytes

```
{),V>{[I\]E.*A.+}/}:F;l~]2/~@:S~'.*f*\@:A.-_:g:E;:z:D[0=:B{D~I2*)*+:U(2/B/FU2/B/:V;}fID~\:I;F]{_Wf>\S.<+:*},{~_3$=@0tt}/N*

```

Try it online

This basically combines two answers I previously wrote for other challenges (mainly the calculations from the 2nd one - function `l`).
(0, 0) is naturally the top left corner, not bottom left like the examples in the statement.

**Overview:**

`{),V>{[I\]E.*A.+}/}:F;` defines function F which helps generate all the pixels (coordinate pairs) for a given x coordinate
`l~]2/~@:S~'.*f*\@:A.-_:g:E;:z:D` reads and processes the input, and creates a matrix of dots
`0=:B{D~I2*)*+:U(2/B/FU2/B/:V;}fI` iterates over all x coordinates except the last one, and generates all the corresponding pixels
`D~\:I;F` does the same for the last x coordinate
`{_Wf>\S.<+:*},` keeps only the pixels that should appear inside the image
`{~_3$=@0tt}/` puts a 0 in the matrix for each pixel
`N*` joins the matrix with newline characters for display
> 1 votes

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


# Question
Title: Indices of elements in an array in order from smallest to largest
**Task**

Basically you have an array of random integers e.g.

```
I() = [1, 4, 3, 2, 5, 3, 2, 1]

```

and you have to create another array of the same length with the numbers 1 to the size of the array in place of the smallest to largest numbers respectively, e.g.

```
O() = [1, 7, 5, 3, 8, 6, 4, 2]

```

For duplicates, the first occurrence is taken as the smaller of the indices.

**Test Cases:**

```
Input:   I() = [1, 5, 3, 4, 5, 3, 2, 4]
Output:  O() = [1, 7, 3, 5, 8, 4, 2, 6]

Input:   I() = [1, 5, 3, 2, 5, 3, 2, 4, 6, 6, 5]
Output:  O() = [1, 7, 4, 2, 8, 5, 3, 6, 10, 11, 9]

```

**Rules**

1. It should work with array of any finite length
2. All integers are positive(greater than 0)
3. This is , so the submission with the least amount of bytes wins!

# Answer
> 3 votes
# Haskell, 41 bytes

```
f l|z<-zip l[0..]=[sum[1|q<-z,p>=q]|p<-z]

```

Try it online!

Haskell doesn't have build-in sorting, so we have to roll up our sleeves. We pair each element with its index with `z<-zip l[0..]`, then for each pair counts the number of pairs that are smaller or equal. This first compares the values, then tiebreaks by their index.

# Answer
> 2 votes
# Bash + coreutils, 28

```
f()(nl|sort -k2)
f|f|cut -f1

```

Try it online.

# Answer
> 1 votes
# Dyalog APL, 2 bytes

`⍋⍋`

is the symbol for grade up \- return a permutation that sorts the argument. Applied twice, it does what's asked for in this problem. Indices in Dyalog are 1-based by default.

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

```
f=(a,b=a.length,c=[...Array(b)])=>(m=a.lastIndexOf(Math.max(...a)),a[m]=0,c[m]=b--,m?f(a,b,c):c)

```

```
f=(a,b=a.length,c=[...Array(b)])=>(m=a.lastIndexOf(Math.max(...a)),a[m]=0,c[m]=b--,m?f(a,b,c):c)

console.log(f([1, 5, 3, 4, 5, 3, 2, 4]));
```

# Answer
> 0 votes
# Ruby, 35 bytes

```
->a{a.zip(1..999).sort.map{|x,y|y}}

```

Try it online!

---
Tags: code-golf, array
---


title: Summing? That's my forte!

text:
# Question
Title: Summing? That's my forte!
# Introduction

Forte is a very peculiar esoteric language based on the concept of modifying the values of numbers. In Forte numbers are not constants but variables, you can use the `LET` instruction to assign new values to them.

For example, after executing `LET 2=4-1` from now on `2` assumes the value of `3`, which means that whenever the value `2` comes up in an expression it is instead "replaced" by `3`. The expression `(1+1)*2` would now evaluate to `9`.

This instruction in Forte is used both for storing information and for flow control (lines are numbered and by changing the value of their numbers you can determine the order of their execution). In this challenge we will not deal with this second aspect.

# The challenge

You are required to write an interpreter for a simplified subset of Forte's `LET` expressions.

You will receive as input a series of lines following this grammar:

```
<line>::= <number>=<expression>

<expression>::= <number>|<expression>+<number>

```

Note: this grammar is not valid Forte because it lacks line numbers, LET, and parentheses (which are always mandatory)

That is, you will only need to deal with computing summations and assigning values to numbers. Parentheses won't be present in the input, and each expression will need to be evaluated from left to right: beware that partial results are affected by redefinitions!

Numbers will always be non-negative integers, up to the limit of your language's native integer type (or 2^32, whichever is higher).

For each line you should output the result of the expression and assign this result to the (possibly reassigned) value of the first number, which will affect how the following lines will be interpreted.

This is , the shortest code (in bytes) wins!

# Other rules

* The input format is flexible, you can for example take a single string with newlines, a list of strings, a list of lists of numbers... The same goes for the output, as long as it's clear what's the result of each expression in the input.
* You may submit either a function, a full program, or a solution to be run in a REPL environment calling it once for each line.
* Standard loopholes are forbidden, in particular you can't call an external Forte interpreter in your code.

# Examples

These are all part of the same input. After each line the expected output relative to that line is shown, sometimes with a comment indicating relevant reassignments (not part of the required output).

```
5=4
4
6=5
4        # 5 -> 4
7=1+2+5
7
7=5+2+1
4        # Order of operations matters! 5+2 -> 4+2 -> 6 -> 4
18=5+6+7
12
5=3
3        # Remember: 5 -> 4
10=6+4
3        # 6 -> 4 -> 3, 3+3 = 6 -> 3

```

# Answer
# Jelly, 28 bytes

```
®y$ÐL
ṪÇ+Ç¥/Ṅ;®⁸Ç¤;©
⁸©ḷƓÇ€¤

```

Try it online!

This is one of the few Jelly programs where it seems to be terser to take input from standard input. It's a full program (writing a function would have been shorter but is banned by PPCG rules, because it wouldn't run correctly the second time). The input format looks like this:

```
[[5,[4]],[6,[5]],[7,[1,2,5]],[7,[5,2,1]],[18,[5,6,7]],[5,[3]],[10,[6,4]]]

```

## Explanation

**Helper function** `1Ŀ` (translate an integer to its value)

```
®y$ÐL
   ÐL   Repeatedly, until there are no further changes,
  $       apply the following unary function to {the input}:
 y          replace values using the mapping table
®             stored in the register.
        {Then return the eventual result.}

```

Rather conveniently, this helper function will work correctly either on a single value, or a list of values, due to the way `y` is defined. If more than one mapping is given for a single value, we take the first mapping from the table. The mapping table is stored in the register (which is basically just a variable; Jelly only has one variable).

**Helper function** `2Ŀ` (evaluate one LET instruction)

```
ṪÇ+Ç¥/Ṅ;®⁸Ç¤;©
Ṫ               On the last element of {the input},
 Ç              Run 1Ŀ,
     /          left fold it via
    ¥             the following binary function:
  +                 add {the two arguments}
   Ç                and run 1Ŀ on {the result},
      Ṅ         write {the result} (and a newline) to standard output,
       ;®       append the value of the register,
            ;   prepend
           ¤      the following value:
         ⁸          {the input, without its last element}
          Ç         with 1Ŀ run on it
             ©  and store that value in the register {and return it}.

```

We don't really want a return value here; we're just running this for its side effects (updating the register and outputting the assigned value). Jelly functions always return a value, though, so we just let the mapping table get returned, as that's tersest.

**Main program**

```
⁸©ḷƓÇ€¤
 ©       Initialize the mapping table
⁸        with the empty string (which is also the empty list)
  ḷ      then evaluate and discard
      ¤  the following value:
   Ɠ       a line from standard input, parsed into a data structure
    Ç€     with each element transformed via 2Ŀ
         {and leave the empty string to be printed implicitly}

```

Normally,  would give us the first command-line argument when run in this context, but there isn't one (we're taking input from standard input), so it runs in an alternative mode that gives us the null string. The need to initialise the register (from its default value of `0`, which crashes `y`) means that we can't mention the user's input implicitly, meaning that it's as cheap to take it from standard input (`Ɠ`) as it would be to take it from a command line argument (`³` or ), and being able to access the alternative use of  means that the unusual (for Jelly) form of input is actually a byte shorter.

It's possible this is improvable. I still haven't figured out why the second line needs to say `⁸Ç¤;` rather than just `;@Ç` – the two should be equivalent, as far as I understand Jelly, given the lack of use of `µ`/`ð`/`ø` – but the latter crashes for some reason. Likewise, there are various other ways to rearrange the program without losing bytes, so it's possible that I've missed a way to make things a bit shorter.

Incidentally, changing the  in the last line to `;` gives you an interesting look into the internal workings of the program, as it'll then output the "history of the register" that's implicitly output by the return values of `2Ḷ`.
> 4 votes

# Answer
# Perl 5, 92 bytes

90 bytes of code + `-pl` flags.

```
sub f{($b=$h{$a=pop}//$a)!=$a?f($b):$a}s%(\d+)\+(\d+)%f($1)+f$2%e&&redo;/=/;$_=$h{f$`}=f$'

```

Try it online!

I use the hashtable `%h` to store the mapping between numbers.
The function (`sub`) `f` returns the number to which its input map (or its input if it's mapped to no number): `$h{$a=pop}` retrieves the number toward which the input maps. If it's none, thanks to `//$a`, the value of `($b=$h{$a=pop}//$a)` is the input (`$a`). We make sure that this values isn't the input itself to not loop infinitely (`!=$a`). Then, we either recursively call `f` or return the input.
The main program consists of two steps:
\- `s%(\d+)\+(\d+)%f($1)+f$2%e&&redo` evaluates the first addition on the right side, while there is still an addition: it replaces `x+y` by the result of the evaluation of `f(x)+f(y)`.
\- `/=/;$_=$h{f$`}=f$'` does the assignment: `/=/` allows to access the left side with `$`` and the right side with `$'`, then `$h{f$`}=f$'` does the assignment. And we also assign it to `$_` that is implicitly printed after each line.
> 5 votes

# Answer
# JavaScript (Node.js), 81 bytes

```
v=x=>(v[x]=v[x]||x,v[x]-x?v(v[x]):x)
f=x=>l=>v[v(x)]=l.reduce((p,x)=>v(v(x)+p),0)

```

Try it online!

Receives input by calling f with the value to assign to, then calling the result of that with an array of values to add together. (i.e. `f(5)([4])`) Repeat for multiple lines.

`v` is used as a function to compute the actual current value of a number, and also as an object to store the actual values. First `v[x]=v[x]||x` ensures that `v[x]` is defined. `v[x]-x` performs a comparison to determine whether this is the actual number or not. If the number does not map to itself, `v(v[x])` recursively tries again, otherwise return `x`.

`f` performs the calculation and assignment, curried to save one byte, where the second call returns the computed value.
> 5 votes

# Answer
# Haskell, ~~116 113 108~~ 106 bytes

```
(#)=until=<<((==)=<<)
e?((n,s):r)|m<-foldl1(\a b->e#(e#a+e#b))s=m:(\x->last$m:[e#x|x/=e#n])?r
e?r=[]
(id?)

```

Try it online! Each equation `4=3+1+5` is notated as tuple `(4,[3,1,5])`. The anonymous function `(id?)` takes a list of such tuples and returns a list of all intermediate results.

`#` is a function to find a fixpoint of a given function `e` and a start value `x`.

The function `?` takes an evaluation function `e` and recursively solves each equation.`foldl1(\a b->e#(e#a+e#b))s` evaluates the right hand side of an equation and saves the result to `m`, e.g. for `4=3+1+5` it computes `eval(eval(eval 3 + eval 1) + eval 5)`, where each `eval` is a fix point application of `e`. Then the eval function is modified to take the new assignment of `n` into account: `(\x->last$m:[e#x|x/=e#n])` which is the same as `\x -> if x == eval n then m else eval x`.

The initial evaluation function is `id` which maps each integer to itself.

---

Thanks to Ørjan Johansen for a shorter fixpoint function, saving 2 bytes!
> 3 votes

# Answer
# Python 3, ~~146~~ ~~132~~ 130 bytes

*14 bytes saved thanks to @Dada*
*2 bytes saved thanks to @mbomb007*

```
d={}
g=lambda x:d.get(x)and x!=d[x]and g(d[x])or x
def f(t):
 for n,(s,*r)in t:
  for b in r:s=g(g(s)+g(b))
  d[g(n)]=s;yield g(n)

```

Try it online!

Receives input as tuples of equations \[`x = y + z + w` as `(x, (y, z, w))`\], outputs via generator.
> 3 votes

# Answer
# oK, 48 bytes

```
a:[];s:{*(a@x;x)^0N}/;f:{a[s@x]:y:{s@x+y}/s'y;y}

```

Usage: `f[5;1 2 3] / 5=1+2+3`

Try it online!

---

If you don't mind having an upper limit to the numbers you can use, such as only using numbers `0` through `998`, then the following suffices (**41 bytes** ± a few depending on the maximum):

```
a:!999;s:(a@)/;f:{a[s@x]:y:{s@x+y}/s'y;y}

```

---

Explanation:

`;` separates three definitions.

`a` is a dictionary/map of numbers. In the first case, it's an actual, empty dictionary `[]`, in the second case it's a list of the numbers `0` to `998`.

`s` is a function that finds the "resulting" number when given a number. The `/` on the end of the function means that it will apply itself to its own output until the output stops changing.

The last bit, `f`, means that:

```
f:{                      } /function called f, input number x, list y
                    s'y    /apply s to every number in the list
                   /       /fold through the list
            {s@x+y}        /    sum the two numbers, apply s
   a[s@x]:                 /set the s(x) to map to the final sum
          y:           ;y  /redefine y to be the final sum, then return it

```
> 3 votes

---
Tags: code-golf, arithmetic, interpreter
---


title: Count Mills in Nine Men's Morris

text:
# Question
Title: Count Mills in Nine Men's Morris
# Introduction

Nine Mens's Morris (also called Mills) is a board game for two players which is played on the following board (image taken from the linked Wikipedia-page):

Each player has 9 men, colored black and white. The concrete rules are not important for this challenge, but check out the Wikipedia-page if you are interested.

# The Challenge

Given a grid as input, which represents a certain boardstate, output the total mill count `m` with `0<=m<=8`.
Three men of the same color form a mill when they are in a straight row of connected points. `b2` to `f2` is not a mill since the men are of different color. Also `d2` to `d5` would not form a mill since the three points have to be connected.
The board in the image above contains two mills for example. One from `f2` to `f6` and one from `e3` to `e5`.

# Input

The board is represented as a 2D grid with 24 points which are connected as shown in the example image above. The example uses letters from `a-g` for the columns and numbers from `1-7` for the rows, but you may choose any reasonable input format as long as it maps 24 unique coordinates to one of the following states:

* Empty
* Taken by black
* Taken by white

The concrete repersentation is up to you you are not restricted to "b" or "w" for the colors.

Besides this, your input may not contain any additional information.

### Additional notes

* You don't have to map the points by any kind of values. If you want to take the input as a 2D array, that's fine as well. But keep in mind that not all points in there are used and that you have to consider the connections between them.
* The input might be empty, in which case you have to output zero (empty board -\> no mills).
* Since each player has 9 men, the input will never contain more than 18 taken points.
* You may leave out emtpy points in the input and therefore only input points which are taken.
* The input may be ordered in any way. You can't rely on a specific order.
* You may assume that the input will always be valid. This means that there won't be more than 9 men of each color and that each point will be unique.

# Rules

* Make clear which input format you use in your solution. Providing an example run of your program is hightly encouraged.
* Function or full program allowed.
* Default rules for input/output.
* Standard loopholes apply.
* This is , so lowest byte-count wins. Tiebreaker is earlier submission.

# Test cases

The input format here is a list of tuples with the coordinates as in the example above as first element and the state of the point second element. A point taken by white is marked as "w" and a point taken by black as "b". All other points are left out and are empty.

```
[("a4","w"),("b2","b"),("b4","b"),("c4","b"),("d1","w"),("d2","w"),("e3","w"),("e4","w"),("e5","w"),("f2","b"),("f4","b"),("f6","b"),("g4","w")] -> 2
[("a1","b"),("a4","b"),("a7","b"),("b4","b"),("c4","b"),("d3","w"),("d2","w"),("d1","w")] -> 3
[] -> 0
[("b4", "b"),("a4",b"),("c4",w")] -> 0
[("b4", "b"),("a4",b"),("c4",b")] -> 1
[("a1", "b"),("a4", "b"),("a7", "b"),("b2", "b"),("b4", "b"),("b6", "b"),("c3", "b"),("c4", "b"),("c5", "b"),("e3", "w"),("e4", "w"),("e5", "w"),("f2", "w"),("f4", "w"),("f6", "w"),("g1", "w"),("g4", "w"),("g7", "w")] -> 8

```

**Happy Coding!**

# Answer
> 4 votes
# APL (Dyalog Classic), ~~26~~ 25 bytes

-1 thanks to FrownyFrog

```
≢{|∊(+/⍵⍪↓⍵),⊢/4 2⍴+⌿⍵}∩≢

```

Try it online!

The argument is a 3x3x3 array of `1`(black), `¯1`(white), and `0`(empty). The first dimension is along the concentric squares' nesting depth. The other two dimensions are along the vertical and horizontal axis.

```
000---------001---------002
 |           |           |
 |  100-----101-----102  |
 |   |       |       |   |
 |   |  200-201-202  |   |
 |   |   |       |   |   |
010-110-210     212-112-012
 |   |   |       |   |   |
 |   |  220-221-222  |   |
 |   |       |       |   |
 |  120-----121-----122  |
 |           |           |
020---------021---------022

```

We have a mill whenever summation along any axis yields a `3` or `¯3`, except we must discard the four corners when summing along the first axis.

`{}` is a function with implicit argument

`↓⍵` is *split* \- in our case it turns a 3x3x3 cube into a 3x3 matrix of nested length-3 vectors

`⍵⍪↓⍵` takes the original cube and glues the 3x3 matrix of 3-vectors below it, so we get a 4x3x3 mixed array of scalars and vectors

`+/` sums along the last axis; this has the combined effect of summing the original cube along the last axis (`+/⍵`) and summing it along the middle axis due to the split we did (`+/↓⍵`)

Now we must take care of the special case for the first axis.

`+⌿⍵` sums along the first axis, returning a 3x3 matrix

`4 2⍴` but we must not count the corners, so we reshape it to a 4x2 matrix like this:

```
ABC      AB
DEF  ->  CD
GHI      EF
         GH  ("I" disappears)

```

now we are only interested in the last column (`BDFH`), so we use the idiom `⊢/`

`,` concatenates `BDFH` to the matrix we obtained before for the 2nd&3rd axis (`BDFH` and the matrix both happen to have a leading dimension of 4)

flattens everything we obtained so far into a single vector

`|` takes the absolute values

`{ }∩≢` filters only the threes - the length (≢) of the input is always 3

counts them

# Answer
> 4 votes
# JavaScript (ES6), ~~276~~ ~~228~~ ~~125~~ ~~117~~ 105 bytes

```
a=>btoa`i·yø!9%z)ª»-ºü1j;ÝÈ%¥·¡ªÜ"·ç¹Ê1`.replace(/.../g,b=>(a[b[0]]+a[b[1]]+a[b[2]])/3&1||'').length

```

(the above contains some unprintable ascii characters that won't show up here, so here's a version without the `btoa` that can be copied and run)

```
a=>'abcdefghijklmnopqrstuvwxajvdksglpbehqtwimrfnucox'.replace(/.../g,b=>(a[b[0]]+a[b[1]]+a[b[2]])/3&1||'').length

```

Breaks a reference string into letter triplets that match up with mill group keys. Input is in the form of an object, where keys are the letters `a-x`, starting from the bottom left and ending in the top right, moving left-to-right first. Values are `1` for white, `-1` for black, and `0` for blank.

### Example

```
{b:1,d:-1,e:1,f:-1,i:1,k:-1,l:-1,m:1,n:-1,r:1,u:-1} => 2
{j:1,d:-1,k:-1,l:-1,b:1,e:1,i:1,m:1,r:1,f:-1,n:-1,u:-1,o:1} => 2
{a:-1,j:-1,v:-1,k:-1,l:-1,h:1,e:1,b:1} => 3
{} => 0
{k:-1,j:-1,l:1} => 0
{k:-1,j:-1,l:1} => 1
{a:-1,j:-1,v:-1,d:-1,k:-1,s:-1,g:-1,l:-1,p:-1,i:1,m:1,r:1,f:1,n:1,u:1,c:1,o:1,x:1} => 8

```

These examples are taken from OP's examples, converted to the letter-key and number-value object. The first is from the example image, while the others are from the example set.

# Answer
> 2 votes
# Mathematica, ~~217~~ 131 Bytes

While I'm sure this is not particularly competitive, here's an entry for you.

```
Count[Total/@{{a1,d1,g1},{b2,d2,f2},{c3,d3,e3},{a4,b4,c4},{e4,f4,g4},{c5,d5,e5},{b6,d6,f6},{a7,d7,g7},{a1,a4,a7},{b2,b4,b6},{c3,c4,c5},{d1,d2,d3},{d5,d6,d7},{e3,e4,e5},{f2,f4,f6},{g1,g4,g7}}/.#/.{"w"->1,"b"->2},3|6]&

```

Input example:

```
{a4 -> "w", b2 -> "b", b4 -> "b", c4 -> "b", d1 -> "w", d2 -> "w", e3 -> "w", e4 -> "w", e5 -> "w", f2 -> "b", f4 -> "b", f6 -> "b", g4 -> "w"}

```

Allowing single-character coordinate names trivially golfs off 51 characters, making this a 166 byte solution. Naming the players 1 and 2 rather than "w" and "b" golfs off 17 further characters.

So we get

```
Count[Total/@{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,a,j,v,d,k,s,g,l,p,b,e,h,q,t,w,r,i,m,f,u,n,c,o,x}~Partition~3,3|6]/.#&

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 50 bytes

### "The Objects' Solution"

While longer (29 chars) than @ngn's solution, it uses an entirely different approach: The input has the same overall structure as that solution, but all slots are represented as objects. Empty slots (including the non-existing center column) must be empty objects. while all black men must be references to the "black man" object, and all white men must be references to the "white man" object. All the objects may optionally have nice **D**isplay **F**orms for readability, and so the center column can optionally be made invisible.

```
+/1=(≢¨(,∪/,∪⌿⍤2),(⊢/4 2⍴∪⌿))

```

Try it online!

`+/` the sum of

`1=(``)` ones in

`≢¨(``)` the tallys of

`,` the raveled (flattened)

`∪/` unique sets across

`,` concatenated to

`∪⌿⍤2` unique sets down

`,(``)` concatenated to

`⊢/` the rightmost column of

`4 2⍴` the, reshaped into four rows and two columns,

`∪⌿` unique columnar sets

An *atop* operator, as supplied with AGL (`ä`), would bring the length down to 27 characters.

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


title: ASCII Tux (Linux Penguin)

text:
# Question
Title: ASCII Tux (Linux Penguin)
I once hacked `upstart` on my Ubuntu box so that a colored, themeable ASCII Tux displayed on the screen with the boot messages scrolling beneath him. I'm curious to see what kind of ASCII art Linux Penguins you can come up with.

* It must fit in a 80 x 25 terminal, without using the bottom line (thus 80 x 24)
* Compact source code
* Bonus: use color
* Bonus: use variations on the standard Tux

**Edit**: As a clarification, by "compact source code" I meant smallest source code *per number of lines of output*. The answers so far have been good but it would be fun to get a diversity of penguins going.

# Answer
Instead of attempting to print a given penguin, I hacked together a program to reduce ASCII art to a minimum production string in Python. I could do some crazy hacks with metaprogramming the environment to define variables for re-used strings, but this is good enough for now. It's Sunday, what can I say.

# ASCII compiler - 882 - Python

---

```
#!/usr/bin/env python

import sys, re

d = "".join(sys.stdin.readlines()) # get all text (WARNING... BIG INPUTS POSSIBLE)
d = re.sub(r' +[\r\n]','',d)       # strip trailing spaces
i,j,c,o,f=0,0,d[0],"""#!/usr/bin/python
# -*- coding: UTF-8 -*-
print \"""",False      # set up vars

while (i <= j) and (j < len(d)):   # while the head cursor (j) is in bounds
 if(d[j] == c): j+=1               # if we are in a repetition be gready
 else:
  if c == "\\": c = "\\\\"         # generate repr()s of special case strings
  elif c == "\n": c = "\\n"
  elif c == "\r": c = ""           # bump \n\r
  elif c == "\"": c = "\\\""

  if((j-i)-9 > 0):                 # if the sequence is long enough to justify a repetition
   if(o): o += "\"+"
   o += "\""+c+"\"*{0}+\"".format(j-i)

  else: o += (c*(j-i))             # else just print the sucker
  i = j
  c = d[j]
o += "\""                          # system assumes an open quote at all times, close it

print o

```

Usage: cat ./tux.txt | python ./encode.py

# My Tux - 1009 chars with spaces

---

```
                    ..- - .
                   '        `.
                  '.- .  .--. .
                 |: _ | :  _ :|
                 |`(@)--`.(@) |
                 : .'     `-, :
                 :(_____.-'.' `
                 : `-.__.-'   :
                 `  _.    _.   .
                /  /  `_ '  \    .
               .  :          \\   \
              .  : _      __  .\   .
             .  /             : `.  \
            :  /      '        : `.  .
           '  `      :          : :  `.
         .`_ :       :          / '   |
         :' \ .      :           '__  :
      .--'   \`-._    .      .' :    `).
    ..|       \   )          :   '._.'  :
   ;           \-'.        ..:         /
   '.           \  - ....-   |        '
      -.         :   _____   |      .'
        ` -.    .'--       --`.   .'
            `--                --

```

# Compiled Tux - 878 - Python

---

```
print " "*20+"..- - .\n"+" "*19+"'"+" "*8+"`.\n"+" "*18+"'.- .  .--. .\n"+" "*17+"|: _ | :  _ :|\n"+" "*17+"|`(@)--`.(@) |\n"+" "*17+": .'"+" "*5+"`-, :\n"+" "*17+":("+"_"*5+".-'.' `\n"+" "*17+": `-.__.-'   :\n"+" "*17+"`  _."+" "*4+"_.   .\n"+" "*16+"/  /  `_ '  \\"+" "*4+".\n"+" "*15+".  :"+" "*10+"\\\\   \\\n"+" "*14+".  : _"+" "*6+"__  .\\   .\n"+" "*13+".  /"+" "*13+": `.  \\\n"+" "*12+":  /"+" "*6+"'"+" "*8+": `.  .\n"+" "*11+"'  `"+" "*6+":"+" "*10+": :  `.\n"+" "*9+".`_ :"+" "*7+":"+" "*10+"/ '   |\n"+" "*9+":' \\ ."+" "*6+":"+" "*11+"'__  :\n"+" "*6+".--'   \\`-._"+" "*4+"."+" "*6+".' :"+" "*4+"`).\n"+" "*4+"..|"+" "*7+"\\   )"+" "*10+":   '._.'  :\n   ;"+" "*11+"\\-'."+" "*8+"..:"+" "*9+"/\n   '."+" "*11+"\\  - "+"."*4+"-   |"+" "*8+"'\n"+" "*6+"-."+" "*9+":   "+"_"*5+"   |"+" "*6+".'\n"+" "*8+"` -."+" "*4+".'--"+" "*7+"--`.   .'\n"+" "*12+"`--"+" "*16+""

```

**Edit 1**: Sadly, while this is efficient for large ASCII art files, as with many compression schemes its performance is lackluster to say the least when presented with very small inputs. The "standard" penguin featured thus far "compresses" to 100 chars of Python which while much better than Brainf\*ck is still nothing to brag about considering that the penguin itself is a mere 75 chars by my count.

**Edit 2**: Also as with many compression schemes the incremental gain is minimal. When I tested my compiler against several ASCII files I seem to get a mere 9-10% improvement over the source.

**Edit 3**: Re: kolmogorov complexity. After some quality time thinking and attempting to golf the base penguin, I have come to the conclusion that the optimal representation is 87 characters long, adding 12 to the actual penguin.

```
print """    .--.
   |o_o |
   |:_/ |
  //   \ \
 (|     | )
/'|_   _/'\
\___)=(___/"""

```

The python string repetition syntax for one character, say `"a"*5`, consumes `4+log10(n)` characters in the best case (non-special characters) and `5+log10(n)` for characters such as the newline or tab which require the string "\n" not a quoted single char. Therefor to achieve a compression greater than 0%, a character repetition greater than 9 characters in length must exist. `(assuming that the repetition is part of a substring which must be terminated with a quote and added to with + and restarted with the same symbols, thus adding 4 to the cost of a repetition)` A trivial examination of the penguin above reveals that no such string exists, therefore no compression is possible using string repetition and the best one can do is leverage the tripple quoted string syntax to represent newlines in one char not two.

**Edit 4**: Fixed edit 3 to reflect the relatively high probability of repetitions internal to some superstring, requiring a repetition like `"+'a'*15+"` which is of length `6+len(repr(a))-2+log10(n)`, updated compiler. (the -2 is required because repr() double-quotes everything)

**Edit 5**: Grabbed the ASCII art collection HERE, and threw together the BASH script below. Pulled a 12% compression average over the entire collection.

```
#!/bin/bash
l=$(find ./art/ -type f)
len=$(find ./art/ -type f | wc -l)
s=0

for i in $l; do
    chars=$(cat $i | wc -c)
    out=$(cat $i | python ./encode.py | wc -c)
    c=$(calc "1-(($out-42)/$chars)" | sed s/'~'/''/g)
    s=$(calc "$s+$c")
    cat $i | python ./encode.py | python 2> /dev/null
    echo -e "$i, $c\t|$?"
done;
echo $(calc "$s/$len")

```

**Edit 6**: Added the UTF-8 specification header to all compiler output and removed those chars from the test script's count because they are spec-required.
> 11 votes

# Answer
## Many script languages, 6 UTF-8 bytes

It doesn't print ASCII art, but...

```
""

```

The character in the quote is the unicode character penguin (U+1F427) (if you want to see the penguin above, download the Symbola font). It looks like this (but a lot smaller):
> 19 votes

# Answer
## Haskell - 14 characters

```
main=putStr"."

```

The penguin this program displays is in the far distance.
> 8 votes

# Answer
## brainfuck, 311 chars (44.4 sc/ol)

(where "sc/ol" stands for "source characters per output line")

```
++++++++++[>++++++>++++>++++>+>+++>+++++++++>++++++++++++>+++++++++++
<<<<<<<<-]>>>>>++....<<++++++.-..+.>.>...>>++++.>+.<<+++++.>>.<<<.>>.
<<<.>...>>.<<<<<<--.>>>>>.<<<+.>>.>>.<<<.>..<<..>>...>---.<.>.<<.>.<<
<.>>>>>.<<.....>>.<<.<<<+.>>.<.<--.>>>>>.<+++.<...>.<<<.<.>>>>---.<<.
>>.+++...<<<<++.<+++.>-.>>>>...<<<.

```

Same tux as CMP:

```
    .--.
   |o_o |
   |:_/ |
  //   \ \
 (|     | )
/'|_   _/'\
\___)=(___/

```

I inserted CRs to get rid of the scrollbar, but I didn't count them.

It's most probably still not optimal. I leave the maths to someone else. It's all in the choice of initial numbers/characters (to save increments and decrements) and in which order to place them (to save pointer moves).
> 5 votes

# Answer
## Brainfuck - 378

```
++++[>++++++++<-]>[>+>++>+++>++++<<<<<+>-]<[>+<-]++++++++++
>....>++++++++++++++.-..+.<<.
>...>>>>----.-------------.<-.>.<<<<.>>>>+++++++++++++.<<<<<.
>...>>>>.<<------.>.<<+.<.>>>>.<<<<<.
>..>..<...>>>---.<<<.>>>.<<<<.
>.>-------.>>>.<<<<.....>>>>.<<<<.>+.<<.
>>++++++.<+++++++.>>>>.<+++.<<<-------...>>>.<<.<+++++++.>>>---.<<<<.
>>>>.+++...<<------.>+++.<-.>>...<<+++++++.<<.

```

Prints this:

```
    .--.
   |o_o |
   |:_/ |
  //   \ \
 (|     | )
/'|_   _/'\
\___)=(___/

```

Hand coded from an image I found on wikipedia. Unfortunately I have no facility to provide color.
> 4 votes

# Answer
Try:

```
#!/bin/bash
sudo apt-get install cowsay
echo | cowsay -f tux.cow "Welcome"

```

This returns the exact same ascii as in the first answer.
> 3 votes

# Answer
This was inspired by @trinithis's answer with the small penguin in the distance. Getting a little closer, it appears he has turned to the side:

# Bash – 7 characters

```
echo \&

```
> 3 votes

# Answer
## Brainfuck - 446 (441 if omit `>>>>>.` which prints `\n`)

```
++++++++[>++++++>>++++>>>-------->+>++++<<<<<<<<-]>-[->+>>++>++>
++++<<<<<]>>.....>+......>>>++.<<<<....<.>......>>--.>>.>...<<.<
<<.<.>>>.<<..<.>>>.<<.>>>.>.>...<<.<<<...>..<...>>>.>.>...<<.<<<
..<.>..>>.>>>..<<.>.<<<<...<.>.<.>>....>.<<.>>.>>.<<<<..<.>.<.>>
>.<....<<.>>>.<<.>>.>>.<<<<.<.>.<.>........>>.<<.>>.>>.>.<<.>>.<
<.>>........<<.>>.<<.>.<<<<<.>.>>.>.>>........<<.<<<<.>.>>.>>.<.
<<<..>>.<........<<.>..>>>.>.<<.<...<<.>......>>.<...<<.>>>>>.

```

This prints

```
     ______
    /      \
   | /\  /\ |
   |   __   |
   |  /  \  |
   / /____\ \
  / /\____/\ \
 / /        \ \
 | |        | |
/ \|        |/ \
|  \________/  |
\___/      \___/

```

Therefore, it's `37.1667` (`36.75` if the code printing last `\n` is omitted) letters per line.
> 2 votes

# Answer
# PHP, 1 byte

Tux in a distance

```
.

```

Thanks to original by Thomas Eding
Try it online!
> 1 votes

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


title: The Big Bang Polyglot

text:
# Question
Title: The Big Bang Polyglot
Everyone loves The Big Bang Theory, right? And everyone loves polyglots, right? So let's combine them!

# Task

Your task *in each language* is quite basic. You must output the name of the one of the 5 main characters of The Big Bang Theory: Sheldon Lee Cooper, Leonard Leakey Hofstadter, Howard Joel Wolowitz, Rajesh Ramayan Koothrapali and Penny Hofstadter.

Your task overall is to write a polyglot that will work in at least *5* languages. Each language should output a different character on the show.

I say "at least" because in order to win, you must output more characters (see Scoring below). But before that, let's go over the details of your program

# Input

You program should take no input when run in any of the languages.

# Output

Your program should output the **full name** of a different characters of TBBT for each language it is run in. If no middle name is known, no middle name is required. 5 of those characters must be the 5 main characters:

* Leonard Leakey Hofstadter
* Sheldon Lee Cooper
* Howard Joel Wolowitz
* Rajesh Ramayan Koothrapali
* Penny Hofstadter

The names outputted must be characters that have appeared in more than one episode and they must have both a first and a last name. If they have a middle name, it **must** be outputted as well.

# Scoring

The scoring system is quite basic: your score is the length of your code in bytes minus 20 times the extra number of characters you output. The extra characters are any that aren't in the list above.

```
length - 20 * (num_characters - 5)

```

You may also subtract 100 from your score if you don't use any comment characters.

# Rules

* No builtins allowed. (Why not?)
* The lowest score wins.
* Only characters with both first *and* surnames are valid
* You must output to STDOUT or your languages equivalent. Nothing may be outputted to STDERR
* Each submission must run in at least *5 different languages*
* Different language versions *do not* count as different languages
* Entries must be **full programs**
* Case and whitespace matter so an output of `Pen nyHof STAdter` isn't valid.
* The valid characters are listed here
* Leading/trailing whitespace is allowed.
* A comment character is a character that makes the program ignore the next line or command

# Answer
# Befunge-98, \>\<\>, Haystack, Minkolang, Alice: 5 languages

## ~~151~~ ~~150~~ 146 bytes

*4 bytes saved thanks to @MartinEnder*

```
#\"retdatsfoH ynneP">:#,_@>o<'Leonard Leakey Hofstadter'
#>!v"Howard Joel Wolowitz"$O.
| @>"Sheldon Lee Cooper"O
d&O>/"ilaparhtooK nayamaR hsejaR"

```

All aboard the 2D-language train!

I got the template for this answer from a previous answer of mine from a similar challenge, but I wanted this submission to be composed of *only* 2D languages. I am planning to add more languages soon.

### Befunge-98

Try it online!

```
#                          Jump over one command
"retdatsfoH ynneP"         Push the characters in this string
>:#,_@                     Print it (basically checks if the top value is not zero, then prints it, otherwise exits the program)

```

Outputs `Penny Hofstadter`.

### \>\<\>

Try it online!

```
#                         Reflect; the IP moves to the left and wraps around to go to the right edge of the field
'retdatsfo ... ranoeL'    Push the characters in this string
>o<                       And output each character in the stack until there are no more, at which point the program exits with an error

```

Outputs `Leonard Leakey Hofstadter` and exits with an error.

### Haystack

Try it online!

```
#                        Ignored
\                        Reflect; moves downward
>                        Move right
!                        Ignored
v                        Go down
>                        Go right
Sheldon Lee Cooper"      Push this string
O                        Output all characters in the stack; the program wraps around to the left edge
|                        End program

```

Outputs `Sheldon Lee Cooper`.

### Minkolang

Try it online!

```
#                       Doesn't do anything important
\                       Reflect; moves downward
>                       Move right
!                       Ignore the next command
"Howard Joel Wolowitz"  Push this
$O                      Output all characters in the stack
.                       End program

```

I could have put the `.` and the beginning of the second line so that the IP would encounter that once it wraps around, but since the grid is padded with spaces and Minkolang travels through time when it sees a space (infinite loop in this case), I had to include the `.` right after the `$O`.

Outputs `Howard Joel Wolowitz`.

### Alice

Try it online!

Alice was the most fun and the most confusing of these languages.

```
#                     Skip the next command
\                     Mirror; redirect IP north-east
                      The IP gets reflected off the top and start moving south-east instead
!                     This command gets skipped over from the #
>                     Set the horizontal component of the IP to East (changes nothing)
/                     Set the IP's direction to East
"ilaparht ... sejaR"  Push this
                      IP wraps around and comes in from the left edge
d&O                   Output the string (duplicate the output command stack length times)

```

Now the program goes on a joyride (@MartinEnder showed how this bit works to me) to get to the `@` in Row 3, Column 3.

```
/                     Mirror; redirect IP south-east
                      The IP hits the bottom and reflects north-east

```

Now the IP moves diagonally up and down as it gets reflected executing the commands along its way.

```
anJ                   Push 10; negate it into an empty string; and jump to origin (0, 0)
                      After the jump, the IP still moves in a north-easterly (irk) direction
#                     Skip the next command
                      IP gets reflected and start moving south-east
@                     Terminate the program

```

Of course, the `@` could have been placed right after the `d&O` (replacing the useless `>`) but that wouldn't have been fun :)

Outputs `Rajesh Ramayan Koothrapali`.
> 1 votes

# Answer
# Foo, Python, JavaScript, Retina, \>\<\>: ~~166~~ 148 bytes

```
1//1;print('Sheldon Lee Cooper');"""
alert`Howard Joel Wolowitz`

// Rajesh Ramayan Koothrapali
//!??

//\"Leonard Leakey">o<'Penny'" Hofstadter"""

```

The trailing newline is significant.

Foo outputs `Leonard Leakey Hofstadter`

Python outputs `Sheldon Lee Cooper`

JavaScript outputs `Howard Joel Wolowitz`

Retina outputs `Rajesh Ramayan Koothrapali`

\>\<\> outputs `Penny Hofstadter`

## Explanations

### Foo

In Foo, any text written inside double quotes is sent to STDOUT. So it outputs `Leonard Leakey` and `Hofstadter`. It also prints it with a leading newline. Honestly I'm really not sure about how it parses strings, but it works as-is. It also tries to do some other operations (`/` is divide, parentheses form loops, etc.), but all of that just causes errors and prints to STDERR without affecting the main output in any way.

### Python

`1//1` is 1 integer divided by 1. In a statement by itself, that does nothing relevant. Then it prints `Sheldon Lee Cooper`, and the rest is in a triple quoted string, which is basically a block comment.

### JavaScript

JavaScript sees most lines as either empty or commented (`//`). The first statement is `1` by itself which, like in the Python part, does nothing. Then it `alert`s `Howard Joel Wolowitz`.

### Retina

```
1//1;print('Sheldon Lee Cooper');"""
alert`Howard Joel Wolowitz`

```

First all matches of `1//1;print('Sheldon Lee Cooper');"""` in the input are replaced with `alert`Howard Joel Wolowitz``. Seeing as the input is empty, nothing happens.

```

// Rajesh Ramayan Koothrapali
```

Then the empty input is replaced with `// Rajesh Ramayan Koothrapali`.

```
//!??

```

Then all matches of `//` optionally followed by a `!` are replaced with nothing. This deletes the initial `//`, leaving one leading space (which is allowed).

```
//\"Leonard Leakey">o<'Penny'" Hofstadter"""

```

Then all matches of the regex above are replaced with nothing. This regex doesn't match anything in the working string, so nothing happens.

The working string is then output implicitly.

### \>\<\>

The IP starts in the top-left, initially moving right. It first pushes 1, then bounces around on mirrors (`/` and `\`) for a while (looping around when it goes out of bounds). The `1` will be popped when it hits `?`.

Eventually it will be on the right side of the second last line moving left. On this line, it sees an empty string `""`, pushing nothing. Then it encounters two strings, `" Hofstadter"` and `'Penny'`, pushing the characters from each as it sees them. When it hits `>o<`, it repeatedly pops and prints the top of the stack as a character, until there's nothing left to pop. It exits with an error.
> 2 votes

# Answer
# Clojure, Java, Ruby, Groovy, Common Lisp - 297 bytes

```
;/\u002A/
(if '()(print"Leonard Leakey Hofstadter")(eval(quote(princ"Sheldon Lee Cooper"))))
;'then print "Howard Joel Wolowitz" end)
;%(/a*/class I{public static void main(String[]a){System.out.print("${}".getClass().getName().contains("G")?"Rajesh Ramayan Koothrapali":"Penny Hofstadter");}}//%)

```

Ruby actually sees all the lines of the program. The first line is a `;` (no-op) followed by Ruby `Regexp`. The second line is an `if` expression which evaluates a string which is True and on the third line it prints the character. The last line is no-op again followed by multi-line string `%(` and `%)`.

See it online : Ruby

Java and Groovy see the same portion of the program, these langauges allow `;` as no-op (first line), then the comment is started as `/\u0002A` which evaluates to `/*` and then the comment ends right before class declaration. After that it's a plain Java/Groovy program. In order to distinguish between them I check the name of the String object class, in Java it will be the usual `java.lang.String` but in Groovy this string object will have class name `groovy.lang.GString` because it contains interpolated expression `${}`.

See it online: Java , Groovy

Clojure and Common Lisp see only the second line of the program (`;` denotes comment). In Clojure empty list `'()` (quote symbol luckily denotes string in ruby) evaluates to `true` and it evaluates to `nil` in Common Lisp, which is `false`. `eval` has to be used in an `else` part because `print` in Common Lisp outputs value with double-quotes so `princ` is used which is not a valid function in Clojure so it's eval\`d.

See it online: Clojure , Common Lisp
> 1 votes

---
Tags: code-challenge, polyglot
---


title: Rock, Polyglot, Scissors

text:
# Question
Title: Rock, Polyglot, Scissors
Write a program that is a polyglot in three languages that plays rock–paper–scissors.

The input for any version of the program is always one of the strings `rock` or `paper` or `scissors`.

In the first language the program must output the rock–paper–scissors choice that beats the input:

```
Input     Output
rock      paper
paper     scissors
scissors  rock

```

In the second language the program must output the rock–paper–scissors choice that ties the input:

```
Input     Output
rock      rock
paper     paper
scissors  scissors

```

In the third language the program must output the rock–paper–scissors choice that loses to the input:

```
Input     Output
rock      scissors
paper     rock
scissors  paper

```

**The shortest code in bytes wins.** Tiebreaker is higher-voted answer.

The inputs and/or outputs may optionally have a trailing newline but otherwise should only be the plain `rock`/`paper`/`scissors` strings. You may use uppercase `ROCK`, `PAPER`, `SCISSORS` if desired.

You may *not* use different versions of the same language (e.g. Python 2 and 3).

# Answer
> 62 votes
## Python, brainfuck and JavaScript, ~~103~~ 99 bytes Yay under 100 bytes!

```
0,[.5,];p=["rock","scissors","paper"]
1//1;lambda x:p[p.index(x)-1];"""
x=>p[-~p.indexOf(x)%3]//"""

```

In Python, this defines a function which beats the input, in brainfuck it's just a simple cat program, and in JavaScript it loses. Here's a version which gives the functions a name, `f`, and also prompts for input in JavaScript and Python 3:

```
0,[.5,];p=["rock","scissors","paper"]
1//1;f=lambda x:p[p.index(x)-1];"""
f=x=>p[-~p.indexOf(x)%3]//"""

1//1;"""
console.log(f(prompt())) // JavaScript
1//1"""; print(f(input())) # Python

```

Try it online (older version): Python, brainfuck, JavaScript

## Explanation:

In Python, `"""..."""` is a multiline string, which can be used as any token. When placed stand-alone it doesn't do anything at all. I use this to "hide" the JavaScript code from Python. The same goes for the `(0,[.5,])` bit, it's just a tuple containing a `0` and a list of `5`, and also the `1//1` part, `//` in Python is integer division, but starts a comment in JavaScript. Here's the code stripped of these tokens:

```
p=["rock","scissors","paper"]
lambda x:p[p.index(x)-1]

```

The first line is pretty self-explanatory, it just defines the list `p` to contain the different choices in rock-paper-scissors. The second line defines an unnamed function which takes one argument, `x`, and gives back the choice that beats `x` (eg. the previous element in `p`)

---

In JavaScript, `//` denotes a single-line comment. Similarly to Python, single tokens are ignored, so the code stripped of these tokens is:

```
p=["rock","scissors","paper"]
x=>p[-~p.indexOf(x)%3]

```

This works similarly to Python, by first setting the list `p` to contain the choices and then defining an anonymous function that gives the losing choice. `-~x` is the same as `x+1` but with higher precedence so that I can skip the parens.

---

In brainfuck, every character except `+-,.[]<>` are removed, leaving this:

```
,[.,][,,]
[.-]
>[-.]

```

The command `,` reads one byte of input, `.` prints it and `[...]` loops while the value is non-zero. What this program does then is read the input and printing it one character at a time until the character `\0` is found. Since we don't have that in the code, we can ignore the rest of the program. In effect, this just echoes back whatever the user types in, effectively tying them.

# Answer
> 41 votes
# Python 2, Ruby, Retina, ~~90~~ 83 bytes

*-7 bytes thanks to Value Ink*

```
s=['rock','paper','scissors']
print s[s.index((0and gets or input()))+(0and-2or-1)]

```

Try it Online: Python, Ruby, Retina

Wins in Ruby, loses in Python, and ties in Retina. This solution makes use of the fact that `0` is truthy in Ruby but falsey in Python. It also makes use of negative indexing in both Python and Ruby.

# Answer
> 21 votes
# V, Brain-flak, and Python 2, ~~97, 86, 81, 77~~, 75 bytes

```
o='rock paper scissors'.split()
lambda s:o[o.index(s)-1]#ddt.C rHd*wywVp

```

*Two bytes saved thanks to @nmjcman101!*

This was super fun! I like this answer a lot because it's a cool overview of languages I like: My favorite editor, my favorite non-esoteric language, and a language I wrote. (Technically python 3 is better, but python 2 is golfier so `¯\_(ツ)_/¯`).

Try it online! in Python (slightly modified so you can see the output), which prints what loses to the input.

Try it online! in Brain-Flak, which prints what ties with the input.

Try it online! in V, which prints what beats the input.

Since V relies on unprintable ASCII characters, here is a hexdump:

```
00000000: 6f3d 2772 6f63 6b20 7061 7065 7220 7363  o='rock paper sc
00000010: 6973 736f 7273 272e 7370 6c69 7428 290a  issors'.split().
00000020: 6c61 6d62 6461 2073 3a6f 5b6f 2e69 6e64  lambda s:o[o.ind
00000030: 6578 2873 292d 315d 231b 6464 742e 4320  ex(s)-1]#.ddt.C
00000040: 720e 1b48 642a 7779 7756 70              r..Hd*wywVp

```

Explanation:

## Python

In python, this is very straightforward. We define a list of the three elements, and return the element right before the input. Since `-1` returns the back element, this works circularly, and it's all very straightforward and easy. Then, everything after `#` is a comment.

## Brain-Flak

This is *also* extremely straightforward in brain-flak. If we had to do winning or losing, this would probably be several hundred bytes. But this actually works in 0 bytes. On the start of the program, all of the input is loaded onto the stack. At the end of the program, the whole stack is implicitly printed.

Once we remove all of the irrelevant characters, the code brain-flak sees is

```
()[()]

```

Which simply evaluates to `1 + -1`, but since this value is not used at all, it's a NOOP.

## V

Here is where it gets a little weird. Naming the python list `o` might have seemed arbitrary, but it's definitely not. In V, `o` opens up a newline, and puts us in insert mode. Then,

```
='rock paper scissors'.split()
lambda s:o[o.index(s)-1]#

```

is inserted into the buffer. After that, the relevant code is:

```
<esc>ddxxf'C r<C-n><esc>Hd*wywVp

```

Explanation:

```
<esc>                          " Return to normal mode
     dd                        " Delete this line. Now the cursor is on '='
       t.                      " Move the cursor forward to the "'"
         C                     " Delete everything after the "'", and enter insert mode
           r                   " From insert mode, enter '<space>r'
            <C-n>              " Autocomplete the current word based on what is currently in the buffer
                               " Since only one word starts with 'r', this will insert 'rock'
                 <esc>         " Leave back to normal mode
                      H        " Go to the first line (where the input is)
                       d*      " Delete everything up until the next occurence of the input
                         w     " Move forward one word
                          yw   " Yank the word under the cursor
                            Vp " And paste that word over the current line, delete everything else

```

# Answer
> 16 votes
# CJam, Retina, PHP, ~~92~~ ~~86~~ 85 bytes

```
ECHO["rock",0,"scissors","paper"][ORD(READLINE())%4];
#];"scissors  paper rock"S/rci=

```

Should be run in PHP using the `-r` flag.

Try it in CJam

Try it in Retina

Try it in PHP

### CJam

In CJam, all capital letters are predefined variables. On the first line, many of these values are pushed onto the stack, along with some string and array literals. Some increments, decrements, and other operations are performed.

After all of that, the stack is wrapped in an array (`]`) and discarded (`;`), so none of that other stuff matters at all. The main CJam program is simply:

```
"scissors  paper rock"S/rci=

"scissors  paper rock"        e# Push this string
                      S/      e# Split it on spaces
                        r     e# Read the input
                         c    e# Cast to char (returns the first character in the string)
                          i   e# Cast to int (its codepoint)
                           =  e# Get the index of the split array (CJam has modular arrays)

```

### Retina

This almost feels like cheating...

Retina will substitute any match of the regex `ECHO["rock",0,"scissors","paper"][ORD(READLINE())%4];` in the input with `#];"scissors paper rock"S/rci=`. Whatever this regex matches, it certainly doesn't match anything in `rock`, `paper`, or `scissors`, so no substitution is made. The unmodified input is then implicitly output.

### PHP

The second line is a comment, so it is ignored.

The first line uses the same algorithm as the CJam part, but with different ordering of the results.

# Answer
> 14 votes
# C, C++, Python; ~~227~~ ~~226~~ 216 bytes

*Saved a byte thanks to @Mat!*

```
#include<stdio.h>/*
f=lambda a:"rock"if a[0]=="r"else"paper"if a[0]=="p"else"scissors"
"""*/
int f(char*b){puts(sizeof'b'-1?*b=='r'?"paper":*b=='s'?"rock":"scissors":*b=='r'?"scissors":*b=='s'?"paper":"rock");}
//"""

```

Defines a function `f` in all languages. Wins in C, ties in Python, loses in C++. Like C++ always does /s

The part between the `/*` and the `*/` is a comment block in C and C++ while it's the lambda function declaration in Python. It basically compares the first character of the function argument and returns the move that starts with that letter.

The part between the `"""`s is a multiline string in Python while it's the function declaration in both C and C++. `sizeof'b'-1` figures out if the current language is C of C++. It has a truthy value if the size is other than 1, a falsy value otherwise. In C character literals are 4-byte long type while in C++ they are a single byte type. Then after the language is figured out it just looks at the first letter of the input and outputs accordingly.

## C

Try it online!

## C++

Try it online!

## Python

Try it online!

# Answer
> 10 votes
# C++, R, C; ~~252~~ ~~240~~ ~~226~~ ~~220~~ 209 bytes

```
#define b/*
M=function()cat(readline())
#*/
#import<stdio.h>
#define M()main(){int i=0;char t[9];char*u;char*s[]={"rock","paper","scissors"};scanf("%s",t);for(;*t-*s[i++];);puts(s[(i+=sizeof('a')==1)%3]);}
M()

```

Makes use of the difference between C and C++ that the size of a character literal is 4 bytes in C and 1 byte in C++.

**C++:**

Try it online!

**R:**

Result:

```
> #define b/*
> M=function()cat(readline())
> #*/
> #import<stdio.h>
> #define M()main(){int i=0;char t[9];char*u;char*s[]={"rock","paper","scissors"};scanf("%s",t);for(;*t-*s[i++];);puts(s[(i+=sizeof('a')==1)%3]);}
> M()
rock
rock

```

**C:**

Try it online!

# Answer
> 9 votes
## Gawk, Retina, Perl; 68 bytes

```
{eval"\$_=uc<>"}{$_=/[Sk]/?"paper":/[Pc]/?"rock":"scissors"}{print}

```

(with a newline at the end)

### Gawk (winner)

Some junk for Perl's sake, then change the line content (`$_`, which is the same as `$0` because the variable `_` is undefined) depending on whether it contains a `k` or a `c`, then print the result. Ignore any warning about escape sequences, I meant to do that.

```
{a_string_that_is_ignored}
{$_ = /[Sk]/ ? "paper" : /[Pc]/ ? "rock" : "scissors"}
{print}

```

### Retina (tie)

Same trick as Basic Sunset and others: replace matches of some silly regexp on the first line by the content of the second line, so pass the input through.

### Perl (loser)

Read a line and convert it to uppercase, then choose a word based a letter it contains, and print the result. The first and last step are wrapped using `eval` to hide them from awk.

```
$_ = uc <>;
$_ = /[Sk]/ ? "paper" : /[Pc]/ ? "rock" : "scissors";
print $_

```

## Gawk, Retina, `perl -p`; 57 bytes

I'm entering this as a bonus because the command line switch in `perl -p` is supposed to be part of the program by the usual rules on this site, which would make it not a polyglot.

```
{eval"\$_=uc"}$_=/[Sk]/?"paper":/[Pc]/?"rock":"scissors"

```

Again with a final newline for Retina. This time, with `perl -p` to print the output automatically, the perl overhead is significantly reduced. I can let the assignment to `$_` trigger an implicit print in awk.

# Answer
> 7 votes
# \>\<\>, Retina, Python 2: ~~144~~ ~~127~~ 123 bytes

*1 byte saved thanks to @Loovjo by removing a space*

*4 bytes saved thanks to @mbomb007 by using `input` instead of `raw_input`*

```
#v"PAPER"v?%4-2{"SCISSORS"v?%2:i
#>ooooo; >oooooooo<"ROCK"~<
a="KRS".index(input()[-1])
print["SCISSORS","ROCK","PAPER"][a]

```

Posted in TNB as a challenge, I decided to try out this combination of languages.

### \>\<\>

Try it online!

The IP starts moving right.

```
#                      Reflect the IP so that it now moves left and it wraps around the grid
i:                     Take one character as input and duplicate it

```

The possible characters that will be taken into the input are `PRS` (since the program only takes the first character). Their ASCII-values are `80`, `81` and `82`.

```
2%                     Take the modulo 2 of the character. Yields 0, 1, 0 for P, R, S respectively
?v                     If this value is non-zero (ie the input was ROCK), go down, otherwise skip this instruction

```

If the input was rock, then this is what would happen:

```
<                      Start moving to the left
~                      Pop the top most value on the stack (which is the original value of R and not the duplicate)
"KCOR"                 Push these characters onto the stack
<                      Move left
oooo                   Output "ROCK" as characters (in turn these characters are popped)
o                      Pop the top value on the stack and output it; but since the stack is empty, the program errors out and exits promptly.

```

Otherwise, if the input was `SCISSORS` or `PAPER`, this is what the IP would encounter:

```
"SROSSICS"             Push these characters onto the stack
{                      Shift the stack, so the the original value of the first char of the input would come to the top
2-4%                   Subtract 2 and take modulo 4 of the ASCII-value (yields 2, 0 for P, S respectively)
?v                     If it is non-zero, go down, otherwise skip this instruction

```

If the input was `PAPER`, then:

```
>ooooooooo             Output all characters on the stack (ie "SCISSORS")
<                      Start moving left
o                      Pop a value on the stack and output it; since the stack is empty, this gives an error and the program exits.

```

Otherwise (if the input was `SCISSORS`):

```
"REPAP"                Push these characters onto the stack
v>ooooo;               Output them and exit the program (without any errors).

```

### Retina

Try it online!

In this case, Retina considers each pair of two lines as a pair of a match and substitution. For example, it tries to replace anything matching the first line with the second line, but since the first line is never matched, it never substitutes it with anything, thus preserving the input.

### Python 2

Try it online!

The Python program requires input to be put in between `"`s.

The first two lines are comments in Python.

```
a="KRS".index(input()[-1])             # Get the index of the last character of the input in "KRS"
print["SCISSORS","ROCK","PAPER"][a]    # Print the ath index of that array

```

# Answer
> 1 votes
# Ruby, Clojure, Common Lisp - 251 bytes

```
(print(eval '(if()({(quote SCISSORS)(quote PAPER)(quote PAPER)(quote ROCK)(quote ROCK)(quote SCISSORS)}(read))(eval(quote(nth(position(read)(quote("SCISSORS""PAPER""ROCK")):test(quote string-equal))(quote(ROCK SCISSORS PAPER))))))))
;'['"'+gets+'"']))

```

More readable version with whitespaces:

```
(print(eval '(if() ; distinguish between CLojure and Common Lisp
    ({(quote SCISSORS)(quote PAPER)(quote PAPER)
       (quote ROCK)(quote ROCK)(quote SCISSORS)}(read)) ; use hash-map as a function
    (eval(quote(nth ; find index of the input arg in the list
       (position(read)(quote("SCISSORS""PAPER""ROCK")):test(quote string-equal))
    (quote(ROCK SCISSORS PAPER))))))))
 ;'['"'+gets+'"'])) ; ruby indexation

```

Clojure always wins, Ruby always draws, Common Lisp always loses.

For Ruby everything inside `'`s is a string. It spans across two lines. Then it uses `[]` operator with a string argument which return the string itself if it's present in the string. The result is printed out, Ruby just mirrors the input.

The second line is a comment for Clojure and Common Lisp. A bunch of `eval` and `quote` has to be used because Clojure needs to make sure that all symbols are valid. It would be nice to reuse code more but even `nth` function have different signatures in these languages. Basically for Clojure `if()` evaluates to true and it goes to the first branch when a hash-map of possible variants is called with argument read from stdin. Common Lisp goes to the second branch, it finds the position of the argument from stdin in the list and returns corresponding item from the resulting list.

I guess Common Lisp part can be golfed more.

See it online: Ruby , Common Lisp , Clojure

# Answer
> 1 votes
# Scala, Javascript and Ook, 167 bytes

```
s=>{var a="paper,scissors,rock".split(",")/*/**/a[-1]="rock"
return a[a.indexOf(s)-1];`*/a((a.indexOf(s)+1)%3)//`//Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook!
}

```

Try it in Scala Try it in Javascript Try the brainfuck version of Ook

### Scala - wins

```
s=>{                                                      //define an anonymous function
  var a="paper,scissors,rock".split(",")                  //generate the array
  /* /* */ a[-1]="rock"                                   //scala supports nested comments,
  return a[a.indexOf(s)-1];`                              //so this comment...
  */                                                      //...ends here
  a((a.indexOf(s)+1)%3)                                   //return the winning string
  //`//Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook!  //another comment
}

```

### Javascript - loses

```
s=>{                                                   //define an anonymous function
  var a="paper,scissors,rock".split(",")               //generate the array
  /*/**/                                               //a comment
  a[-1]="rock"                                         //put "rock" at index -1
  return a[a.indexOf(s)-1];                            //return the string that loses
  `*/a((a.indexOf(s)+1)%3)//`                          //a string
  //Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook!  //a comment
}

```

### Ook! - ties

The Ook part is the simple brainfuck cat program `,[.,]` tranlsated to Ook.

```
s=>{var a="paper,scissors,rock".split(",")/*/**/a[-1]="rock"   //random stuff
return a[a.indexOf(s)-1];`*/a((a.indexOf(s)+1)%3)//`//         //more random stuff
Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook!              //the program
}                                                              //random stuff

```

---
Tags: code-golf, string, kolmogorov-complexity, game, polyglot
---


title: Fold Some Towels!

text:
# Question
Title: Fold Some Towels!
I heard somewhere that one thing that technology cannot do yet is fold towels1. So it is now your job to prove that statement false!

Given a string as input, made up of rectangles (towels), like the following, fold each towel in half twice. For example:

```
+------+    +------+        +--+
|      |    |      |        |  |
|      |    |      |        |  |
|      | -> +------+ ->     +--+
|      |
|      |
|      |
+------+

```

Notice that when a towel is folded, it is first folded up, then from left to right. You program must mimic this behavior as well. Also notice that in the test cases, the towels stays in the same place, but folded.

**Rules:**

* Standard methods of input/output.
* Standard loopholes apply.
* Input and output should be as a string.
* Trailing whatevers are okay in output, as long as the towels are in the right place relative to each other.
* You may assume that the length of each side of the towel will always be divisible by 2.
* The towels passed as input will always be rectangular.
* The towels will always be separated-- however, they may be separated by variable amounts.
* , so shortest code wins!

**Test cases:**

```
Input:
+------+
|      |
|      |
|      |
|      |
|      |
|      |
+------+
Output:
    +--+
    |  |
    |  |
    +--+

Input:
+--+ +--+ +--+
|  | |  | |  |
|  | |  | |  |
+--+ +--+ +--+

Output:
  ++   ++   ++
  ++   ++   ++

Input:
+----+
|    |
|    |
|    |
|    | ++
+----+ ++

Output:

   +-+
   | |
   +-+

        +

Input:
+--+
+--+     ++
         ||
         ||
         ++
Output:
  ++
          +
          +

```

1: This has been disproved by Geobits and Laikoni. However, I did hear it somewhere.

# Answer
# Retina, 245 bytes

```
m1+`^((.)*(?!\+ )[+|]([- ])*[+|].*¶(?<-2>.)*)([+|][- ]*[+|])
$1$.4$*
m+`^((.)*) ( *) (.*¶(?<-2>.)*)(?(2)(?!))\|\3\|
$1|$3|$4 $3
m+`^((.)*)\|( *)\|(?=.*¶(?<-2>.)*(?(2)(?!)) )
$1+$.3$*-+
([+|])\1
 $1
(?!\+ )([+|])([- ])\2(\2*)\3\1
$.3$*   $1$3$1

```

Try it online!

Note: some lines end in spaces. Explanation:

```
m1+`                    Repeatedly search from the beginning of input
    ^((.)*              Optional indentation
      (?!\+ )           Towel does not start with a plus and a space
      [+|]([- ])*[+|]   A row of towel
      .*¶               Rest of the line
      (?<-2>.)*         Some indentation on the next line
     )
     ([+|][- ]*[+|])    Another row of towel
$1$.4$*                 Replace the second row with blanks

```

Delete every other line of every towel (this works because all towels have even height),

```
m+`             Repeatedly search
   ^((.)*)      Optional indentation
    ( *)        Find some space
    (.*¶        Rest of the line
     (?<-2>.)*) Matching indentation on the next line
    (?(2)(?!))  Ensure that the indentation exactly matches
    \|\3\|      Piece of towel
$1|$3|$4 $3     Swap the piece into the space above

```

shift all the detached towel pieces up,

```
m+`                 Repeatedly search
   ^((.)*)          Optional indentation
    \|( *)\|        Piece of towel
    (?=             Followed by
       .*¶          Rest of the line
       (?<-2>.)*    Matching indentation on the next line
       (?(2)(?!))   Ensure that the indentation exactly matches
        )           Nothing on the next line
$1+$.3$*-+          Change the piece into a towel bottom

```

and fix the bottom of the towels, effectively folding them up.

```
([+|])\1    Match a row of towel of width 2, which is just ++ or ||
 $1         Change the first column to a space, which folds it

```

Fold the towels of width 2 to the right.

```
(?!\+ )     Towel does not start with a plus and a space
([+|])      Start with a + or a |
([- ])\2    Then at least two -s or spaces
(\2*)\3     Then an even number of -s or spaces
\1          Then another + or |
$.3$*       Replace the left half with spaces
$1$3$1      Replace the first character of the right half

```

Fold the remaining towels to the right.
> 5 votes

# Answer
# Octave with Image Package, ~~277~~ 272 bytes

```
function x=f(x)
[i,j,v]=find(bwlabel(x-32));a=@(w)accumarray(v,w,[],@max);r=-a(-i);R=a(i);s=-a(-j);S=a(j);x(:)=32;for k =1:nnz(r)
u=(r(k)+R(k)-1)/2;v=(s(k)+S(k)+1)/2;p=v:S(k);x(r(k),p)=45;x(u,p)=45;q=r(k):u;x(q,v)=124;x(q,S(k))=124;x(u,[v S(k)])=43;x(r(k),[v S(k)])=43;end

```

Input and output are 2D char arrays.

Try it online! Or verify all test cases: , , , . (Note that `endfunction` in the test cases is only needed to separate the function from the subsequent code. It is not necessary if the function is saved in its own file.)

### Readable version and explanation

```
function x = f(x)
[i,j,v] = find(bwlabel(x-32)); % make background equal to 0 by subtracting 32.
% Then label each connected component (i.e. towel) with a unique integer
% Then get row indices (i) and column indices (j) of nonzero values (v)
a = @(w)accumarray(v,w,[],@max); % helper function. Gives the maximum of w for
% each group given by an integer label in v
r = -a(-i); % upper coordinate of each towel (minimum row index)
R = a(i); % lower coordinate of each towel (maximum row index)
s = -a(-j); % left coordinate of each towel (minimum column index)
S = a(j); % right coordinate of each towel (maximum column index)
x(:) = 32; % remove all towels: fill x with spaces
for k = 1:nnz(r) % for each original towel: create the new, folded towel
    u = (r(k)+R(k)-1)/2; % new lower coordinate
    v = s(k)+S(k)+1)/2; % new left coordinate
    p = v:S(k); % column indices of horizontal edges
    x(r(k),p) = 45; % fill upper horizontal edge with '-'
    x(u,p) = 45; % fill lower horizontal edge with '-'
    q = r(k):u; % row indices of vertical edges
    x(q,v) = 124; % fill left vertical edge with '|'
    x(q,S(k)) = 124; % fill right vertical edge with '|'
    x(u,[v S(k)]) = 43; % fill lower corners with '+'
    x(r(k),[v S(k)]) = 43; % fill upper corners with '+'
end

```
> 3 votes

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