title: Draw An ASCII Double Helix

text:
# Question
Title: Draw An ASCII Double Helix
Write a program that takes in an integer N via stdin or the command line.

If N is 0, the single letter `O` must be printed to stdout.

---

If N is *positive*, this **horizontal** ASCII art double helix, drawn N segments wide, must be printed.

If N is 1, the output is:

```
 /\
O  O
 \/

```

If N is 2, the output is:

```
 /\ /\
O  /  O
 \/ \/

```

If N is 3, the output is:

```
 /\ /\ /\
O  /  /  O
 \/ \/ \/

```

If N is 4, the output is:

```
 /\ /\ /\ /\
O  /  /  /  O
 \/ \/ \/ \/

```

The pattern continues in the exact same way for larger N. Note that forward slash (`/`) must be used in all places the helixes cross, except for the `O` ends.

---

If N is *negative*, this **vertical** ASCII art double helix, drawn -N segments tall, must be printed.

If N is -1, the output is:

```
 O
/ \
\ /
 O

```

If N is -2, the output is:

```
 O
/ \
\ /
 \
/ \
\ /
 O

```

If N is -3, the output is:

```
 O
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 O

```

If N is -4, the output is:

```
 O
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 O

```

The pattern continues in the exact same way for smaller N. Note that backward slashes (`\`) must be used in all places the helixes cross, except for the `O` ends.

**Details**

* Instead of a program, you may write a function that takes N as an integer and prints the result normally or returns it as a string.
* The output for any N may optionally contain a trailing newline.
* Any line of output for any N may optionally contain 4 or fewer trailing spaces.
* There should never be any leading space that aren't part of the specified pattern.
* **The shortest code in bytes wins.**

# Answer
# CJam, ~~56 55 53 52~~ 50 bytes

```
S'O:Ori:X0>"\/"=" / \\\ / "+Xz*1>O]s3/X"z"<~N*X\O?

```

Look at that size! The main culprits are `N = 0` special case and the `\` instead of `/` in the vertical helix.

Here is how it works:

```
S'O:O                                  e# Put a space on stack. Now put char O on stack
                                       e# and assign it to variable O. This is not really
                                       e# helping in golfing as using 'O everywhere is
                                       e# same number of bytes
     ri:X                              e# Read input as in integer and store it in X
         0>"\/"=                       e# If X is greater than 0, choose /, otherwise \
                " / \\\ / "            e# Put this string on stack
                           +           e# Append to chosen \ or /
                            Xz*        e# Repeat it abs(X) times
1>                                     e# Remove the first character from repeated string
  O]                                   e# Put char O on stack, wrap everything in an array
                                       e# and convert it to string.
    3/                                 e# Split the string into parts of length 3
      X"z"<~                           e# If X is positive, transpose the array to get a
                                       e# horizontal helix, otherwise it would be vertical
            N*                         e# Join the parts with newline
              X\O?                     e# If X was 0, then pick char O instead of this
                                       e# final joined string.

```

The code is divided into three parts:

* The part `X0>"\/"=" / \\\ / "+` gives either `"/ / \\\ / "` or `"\ / \\\ / "` which is crucial as the helix is simply made up of alternate `"/ \"` and `"\ /"` joined by either `" / "` or `" \ "`. For instance, if you consider input to be `2`, then your final repeated string would be `"/ / \\ / / / \\ / "` (without escaping). This obviously has extra `/`  at the beginning and an extra space at the ending.
* Second part is to correct the above string with additional things and split. For an input `2`, the desired final string without newlines would be `" O / \\\ / / / \\\ / O"`, but after the above point, we only have `"/ / \\\ / / / \\\ / "`. So we remove the first character, add a space and `'O` at the beginning and another `'O` at the end. Then we finally split it into parts of 3
* Finally, we decide whether to transpose this split string for a vertical helix or not; Join the parts by newlines; And choose between this and a single character `'O` (for input 0 case)

Try it online here
> 16 votes

# Answer
# JavaScript(ES6), 126 ~~132 133~~

```
A=n=>(F=(f,j='')=>f+(j+f).repeat(n-1),n>0?F(' /\\')+`
o${F('  ','/')}o
`+F(' \\/'):(n=-n)?` o${F(`
/ \\
\\ /
`,' \\')} o`:'o')

// Test
for(i=0;i<10;i++)
  P.innerHTML = P.innerHTML + A(i)+'\n\n\n',
  N.innerHTML = N.innerHTML + A(-i)+'\n\n\n'
```

```
pre {
  font-size: 10px;
  line-height: 9px;
}
```

```
<table>
<tr><th>Positive</th><th>Negative</th></tr>
<tr><td valign=top><pre id=P></pre></td><td><pre id=N></pre></td></tr>
</table>
```

Using templated string, newlines count.

**More readable**

```
A=n=>(
  F=(f,j='')=>f+(j+f).repeat(n-1),
  n > 0 ? F(' /\\') + '\no' + F('  ','/') + 'o\n'+F(' \\/')
  : (n=-n) ? ' o' + F('\n/ \\\n\\ /\n',' \\')'+' o':'o'
)

```
> 10 votes

# Answer
# Pyth, 52 bytes

```
M[Jj"/\\"*hGdjP*G+*2dH*2\O_J)?jb?gQ\/>Q0msdCg_Q\\Q\O

```

Demonstration.

Explanation:

The first section, `M[Jj"/\\"*hGdjP*G+*2dH*2\O_J)`, defines a function, `g`, which takes two inputs. The first input, `G`, is the number of repetions to use. This is the absolute value of the input. The second input, `H`, is the character to place at the center of the spirals.

The function returns a 3 element list, which consists of the 3 lines of the positive spiral, and the 3 columns of the negative spiral.

The first element is defined by `Jj"/\\"*hGd`. `*hGd` is the string of `G+1` spaces. `j"/\\"*hGd` joins that string with `"/\"` as the delimeter. The `J` at the beginning saves the resultant value for future use.

The second element is `jP*G+*2dH*2\O`. We start with `+*2dH`. This is two spaces followed by the input character. Then, we repeat that string `G` times with `*G`. Then, we remove its final character with `P`. Finally, we surround this string with two `O` characters, with `j ... *2\O`.

The third element is generated with `_J`. This is simply the reverse of the first line.

The latter section, `?jb?gQ\/>Q0msdCg_Q\\Q\O` selects between three different posibilities, positive, negative and zero. The first if-then conditions on `Q`, the input. The second conditions on `>Q0`, whether the input is positive.

If `Q` is zero, `\O`, the character `O`, is printed.

If `Q` is nonzero, we join the result of the second ternary on newlines and print it, with `jb`. If `Q` is positive, the list joined and printed is `gQ\/`, `g(Q,"/")`.

If `Q` is negative, the list joined and printed is `msdCg_Q\\`. We start with `g_Q\\`, which is `g(-Q,"\")`. Then we transpose the rows and columns with `C`. `msd` turns the resultant tuples of characters into strings, ready to be joined on newlines and printed.
> 8 votes

# Answer
## Python 2, 118

```
n=input()
a=[' O '[n==0:]]+['/ \\','\\ /','  /\\ '[n<0::2]]*abs(n)
a[-1]=a[0]
for x in[a,zip(*a)][n>0]:print''.join(x)

```

Creates the vertical double helix from a list of strings and transposes it to get the horizontal one. I'm sure it could be improved.
> 6 votes

# Answer
# Java, ~~500~~ 488 bytes

My first try, and unfortunately it is 10\* longer than the current leader :(. Anyone have any tips (other than use a different language)?

```
import java.util.*;class t{public static void main(String[] args){Scanner sc=new Scanner(System.in);int n=Integer.parseInt(sc.nextLine());if(n>0){for(int i=0;i<n;i++)System.out.print(" /\\");o("");System.out.print('o');for(int i=0;i<n-1;i++)System.out.print("  /");o("  o");for(int i=0;i<n;i++)System.out.print(" \\/");}else if(n<0){o(" o ");for(int i=0;i<-n-1;i++){o("/ \\");o("\\ /");o(" \\ ");}o("/ \\");o("\\ /");o(" o ");}else o("o");}static void o(String s){System.out.println(s);}}

```
> 5 votes

# Answer
# Haskell, 156 bytes

```
h 0="O"
h n|n>0=' ':c n "/\\ "++"\nO"++c(n-1)"  /"++"  O\n "++c n "\\/ "
   |0<1=" O\n/ \\\n"++c(-n-1)"\\ /\n \\\n/ \\\n"++"\\ /\n O"
c x=concat.replicate x

```

You can then write it as:

```
*Main> putStrLn $ h 1
 /\
O  O
 \/
*Main> putStrLn $ h 0
O
*Main> putStrLn $ h (-1)
 O
/ \
\ /
 O
*Main> putStrLn $ h 3
 /\ /\ /\
O  /  /  O
 \/ \/ \/
*Main> putStrLn $ h (-3)
 O
/ \
\ /
 \
/ \
\ /
 \
/ \
\ /
 O
*Main>

```
> 5 votes

# Answer
# C#, ~~242~~ ~~241~~ ~~238~~ ~~230~~ ~~222~~ 219 Bytes

Spurred on by Martin's comment, here's my first attempt at something like this:

```
string h(int n){int x=0;string p="",r=n==0?"O":p;if(n>0){for(;x++<n;){r+=" /\\";p+=" \\/";}r+="\nO  ";for(;x-->2;)r+="/  ";r+="O\n"+p;}else if(n<0){r+=@" O
/ \
";for(--x;x-->n;)r+=@"\ /
 \
/ \
";r+=@"\ /
 O";}return r;}

```

More readably:

```
string h(int n)
{
    int x = 0;
    string p = "",
            r = n==0 ? "O" : p;
    if (n > 0) {
        for (; x++ < n;) {
            r += " /\\";
            p += " \\/";
        }
        r += "\nO  ";
        for (; x-- > 2;) r += "/  ";
        r += "O\n" + p;
    }
    else if(n<0) {
        r += @" O
/ \
";
        for (--x; x-- > n;) r += @"\ /
 \
/ \
";
        r += @"\ /
 O";
    }
    return r;
}

```
> 4 votes

# Answer
# C# ~~199~~ ~~197~~ 196 bytes

```
string f(int n){var u=n<0;int m=u?-n:n;string a="",b=" O ";for(;m-->0;)b+="\n/ \\\n\\ /\n "+(m==0?"O ":u?"\\ ":"/ ");for(;++m<3;)a+=string.Concat(b.Split('\n').Select(s=>s[m]))+"\n";return u?b:a;}

```

Ungolfed version:

```
    string f(int n)
    {
        var u = n < 0;
        int m = u ? -n : n;
        string a = "", b = " O ";
        for (; m-- > 0; ) b += "\n/ \\\n\\ /\n " + (m == 0 ? "O " : u ? "\\ " : "/ ");
        for (; ++m < 3;) a += string.Concat(b.Split('\n').Select(s => s[m])) + "\n";
        return u ? b : a;
    }

```

The idea is to build the horizontal display from the vertical display by rendering the transposed matrix of characters.
> 3 votes

# Answer
# Python 3, 118 bytes

```
x=int(input())
print("O"if x==0else" /\\"*x+"\nO "+" / "*(x-1)+" O\n"+" \\/"*x if x>0else(" O"+"\n/ \\\n\\ /\n \\"*-x)[:-1]+"O")

```

My first ever code golf submission, so it may not be at all impressive.

Just uses Python's ... if ... else ... ternary operator to separate the three scenarios. That gives a string made of repeating some smaller strings a certain number of times to print.
> 3 votes

# Answer
# Julia, 229 bytes

Oh man, this is way, *way* too big. It's the longest answer so far by a large margin. I could probably save a lot by returning the string rather than printing it, or by avoiding the matrix approach altogether. I'll experiment with that later.

```
n->(if n==0 println("O")else m=abs(n);A=B=reshape(split(" / "*(n>0?"/":"\\")*" \\\\ /",""),(3,3));E=[" ";"O";" "];if m>1for i=2:m B=hcat(B,A)end end;B[:,1]=E;B=hcat(B,E);C=n>0?B:B';for i=1:size(C,1) println(join(C[i,:]))end end)

```

This creates a lambda function that takes a single integer and prints the appropriately formatted double helix. To call it, give it a name, e.g. `f=n->(...)`.

Ungolfed + explanation:

```
function f(n)
    if n == 0
        println("O")
    else
        m = abs(n)

        # Split the string into a 3x3 matrix with a slash on the left,
        # or a backslash for n < 0
        A = B = reshape(split(" / " * (n > 0 ? "/" : "\\") * " \\\\ /", ""), (3, 3))

        # We can get the O lines where needed by appending this
        E = [" "; "O"; " "]

        # Grow the helix by abs(n)
        if m > 1
            for i = 2:m
                B = hcat(B, A)
            end
        end

        # Exchange the first column for E
        B[:,1] = E

        # Add E onto the right
        B = hcat(B, E)

        # If n is negative, we actually want the transpose
        C = n > 0 ? B : B'

        # Print the rows of C
        for i = 1:size(C, 1)
            println(join(C[i,:]))
        end
    end
end

```

A couple examples:

```
julia> f(1)
 /\
O  O
 \/

julia> f(-2)
 O
/ \
\ /
 \
/ \
\ /
 O

```
> 2 votes

# Answer
# Python 3, 135 bytes

```
n=int(input());m=abs(n)-1;print({n:" O\n/ \\\n"+m*"\ /\n \\\n/ \\\n"+"\\ /\n O",m+1:n*" /\\"+"\nO"+"  /"*m+"  O\n"+" \/"*n,0:"O"}[n])

```

Try it online here
> 2 votes

# Answer
# Perl, 91 ~~97~~

Transposing proved to be too expensive in the end.

```
#!perl -n
print/-/?"\0\23"^" \\
/ \\
\\ /
"x-$_." O":-$_?" /\\"x$_.("*`"^" / "x$_." O
"." \\/"x$_):O

```

Previous solution:

```
#!perl -n
$".="`"^"/
\\ /
/ \\
 "x abs.O;print/-/?$"=~y!/\\!\\/!r:/^0/?O:map{($"=~/^.{$_}(.)/mg,$/)}2,1,0

```

Test me.
> 2 votes

# Answer
# Scheme, 379 bytes

My first attempt at code golf and, unfortunately, one of the longest ones. :(

```
(define (h i) (define a string-append) (define (k n p q s e) (cond ((= i n) (p s (k (q n 1) p q s e))) ((= 0 n) e) (else (p `("\\ /" ,(if (> i 0) " / " " \\") "/ \\") (k (q n 1) p q s e))))) (if (= i 0) "O\n" (apply a (map (lambda (s) (a s "\n")) (if (> i 0) (k i (lambda (x y) (map a x y)) - '(" /" "O " " \\") '("\\" " O" "/")) (k i append + '(" O" "/ \\") '("\\ /" " O")))))))

```

Ungolfified:

```
(define (h i)
  (define a string-append)

  (define (k n p q s e)
    (cond ((= i n) (p s (k (q n 1) p q s e)))
          ((= 0 n) e)
          (else (p `("\\ /" ,(if (> i 0) " / " " \\") "/ \\")
                   (k (q n 1) p q s e)))))

  (if (= i 0) "O\n"
      (apply a (map (lambda (s) (a s "\n"))
                    (if (> i 0)
                        (k i (lambda (x y) (map a x y)) -
                           '(" /" "O " " \\")
                           '("\\" " O" "/"))
                        (k i append +
                           '(" O" "/ \\")
                           '("\\ /" " O")))))))

```
> 2 votes

# Answer
## Java, 282

My first approach, with particularly nice variable names:

```
class H{public static void main(String[]_){int N=Integer.parseInt(_[0]),í=N;String ì="/ \\\n\\ /\n",I=" o \n",i="",l=I;for(;í-->0;)i+=" /\\";i+="\no";for(í=N;í-->1;)i+="  /";i+="  o\n";for(í=N;í-->0;)i+=" \\/";for(í=1;í++<-N;)l+=ì+" \\ \n";System.out.println(N<0?l+ì+I:N>0?i:"o");}}

```

I have no idea why I am doing this. Must be some recreational thing.
> 2 votes

# Answer
## Java, 317

My first code golf attempt.

```
public class t{public static void main(String[]e){int n=Integer.parseInt(e[0]);String s=new String(new char[n==0?0:(n>0?n:-n)-1]),u="\0";System.out.print(n==0?"O":n>0?s.replace(u," /\\")+" /\\\nO"+s.replace(u,"  /")+"  O\n"+s.replace(u," \\/")+" \\/":" O \n/ \\\n"+s.replace(u,"\\ /\n \\ \n/ \\\n")+"\\ /\n O \n");}}

```
> 2 votes

# Answer
# Groovy, ~~142~~ ~~134~~ ~~129~~ ~~125~~ ~~120~~ 118

```
a=args[0]as int;b="\n/ \\\n\\ /\n ";print!a?"O":a>0?" /\\"*a+"\nO  ${"/  "*(a-1)}O\n"+" \\/"*a:" O$b${"\\$b"*(1-a)}O"

```

Finally tied with python 2!
> 1 votes

# Answer
# Python 3, 165 bytes

```
x,a,b,c,d=int(input())-1,'\ /',' / ','/ \\','\ /\n \\\n/ \\\n'
print([[' O\n/ \\\n'+d*abs(x+2)+'\ /\n O',' /'+a*x+'\\\nO '+b*x+' O\n \\'+c*x+'/'],'OO'][x==-1][x>-1])

```

Try it online here.
> 1 votes

# Answer
# Perl, ~~193~~ ~~197~~ ~~187~~ ~~180~~ ~~166~~ 163B

1 byte penalty for -n commandline switch. Run with `echo 1|perl -M5.10.0 -n scratch.pl`:

```
$_*=3;$s=($m=abs)==$_;$_?map{say if$_=join'',map{(map[/./g]," O ",(('/ \\', '\\ /',$s?' / ':' \\ ')x$m)[0..$m-2]," O")[$s?$_:$j][$s?$j:$_]}0..$m;$j++}0..$m:say'O'

```

With whitespace:

```
$_ *= 3;
$s = ($m = abs) == $_;
$_ ? map{
      say if $_=join '', map {
       ( map[/./g],
          " O ",
          (('/ \\', '\\ /',$s?' / ':' \\ ') x $m)[0..$m-2],
          " O"
        )[$s ? $_ : $j][$s ? $j : $_]
       }0..$m;
      $j++
    } 0..$m
  : say 'O'

```
> 1 votes

# Answer
# R, ~~228~~ 201

```
n=scan();z=cat;f=`for`;if(!n)z("O");if(n>0){f(i,1:n,z(" /\\"));z("\nO  ");if(n>1)f(i,2:n,z("/  "));z("O\n");f(i,1:n,z(" \\/"))};if(n<0){z(" O\n");f(i,-n:1,{z("/ \\\n\\ /\n ");if(i>1)z("\\\n")});z("O")}

```

My first attempt at code golf. I think it works but it is not subtle.

```
n=scan(); # enter number here
z=cat;
if(!n) z("O\n");
if(n>0){
  z(" ");
  for(i in 1:n) z("/\\ ");
  z("\nO");
  if(n>1){
    for(i in 2:n) z("  /")
  };
  z("  O\n ");
  for(i in 1:n) z("\\/ ")
};
if(n<0){
  z(" O \n");
  for(i in -n:1){
    z("/ \\\n\\ /");
    if(i>1) z("\n \\\n")
  };
z("\n O ")
}

```
> 1 votes

# Answer
# PHP, 341

```
$s='';$n=$argv[1];$l=PHP_EOL;if($n>0){for($i=0;$i<$n;$i++)$s.=" /\\";$s.=$l;for($i=0;$i<$n;$i++){if($i==0)$s.='o';if($i<$n-1)$s.='  /';if($i==$n-1)$s.='  o';}$s.=$l;for($i=0;$i<$n;$i++)$s.=" \\/";}else{$n=abs($n);for($i=0;$i<$n;$i++){if($i== 0)$s.=' o '.$l;$s.="/ \\".$l."\\ /".$l;if($i < $n-1)$s.=' \\ '.$l;if($i==$n-1)$s.=' o '.$l;}}echo $s;

```

Ungolfed version

```
$s = '';
$n = $argv[1];
echo PHP_EOL;
if($n > 0)
{
    for($i=0;$i<$n;$i++)
    {
        $s.=" /\\";
    }
    $s.=PHP_EOL;

    for($i=0;$i<$n;$i++)
    {
        if($i==0) {
            $s.='o';
        }
        if($i < $n-1) {
            $s.='  /';
        }
        if( $i == $n-1)
        {
            $s.='  o';
        }
    }
    $s.=PHP_EOL;

    for($i=0;$i<$n;$i++)
    {
        $s.=" \\/";
    }
} else
{
    $n = abs($n);
    for($i=0;$i<$n;$i++)
    {
        if($i == 0) {
            $s.=' o '.PHP_EOL;
        }
        $s.="/ \\".PHP_EOL."\\ /".PHP_EOL;
        if($i < $n-1) {
            $s.=' \\ '.PHP_EOL;
        }
        if( $i == $n-1) {
            $s.=' o '.PHP_EOL;
        }
    }
}

echo $s;

```
> 1 votes

# Answer
# JAVA 377 ~~384~~ bytes

```
class F{public static void main(String[] a){int n=Integer.parseInt(a[0]);if(n>0){for(int i=0;i<n;i++)p(" /\\");p("\n");for(int i=0;i<n;i++){if(i==0)if(n>1)p("O  ");else p("O  O");else if(i==n-1)p("/  O");else p("/  ");}p("\n");for(int i=0;i<n;i++){p(" \\/");}}else{p(" O\n");for(int i=0;i<Math.abs(n);i++){p("/ \\\n\\ /\n O\n");}}}static void p(String s){System.out.print(s);}}

```
> 1 votes

# Answer
# C++ ~~269~~ ~~262~~ 258

```
#include <string>
#include <iostream>
int main(){int i,j;std::cin>>i;std::string s,u,t;if(i>0){for(j=i;j;j--){s+=" /\\";t+="/  ";u+=" \\/";}t[0]='O';t+="O";s=s+'\n'+t+'\n'+u;}else{for(j=i;j;j++)s+=" \\\n/ \\\n\\ /\n";s[1]='O';s+=" O";}std::cout<<(i==0?"O":s);}

```
> 1 votes

# Answer
# Canvas, ~~33~~ ~~32~~ 30 bytes

```
 /¶O：╴⤢╷\ /¶ \×＋；↔＋──╴０＜？↷｝╴‽O

```

Try it here!

Explanation:

```
 /¶O:                           push " /\¶O" twice
     ╴⤢╷                        push the absolute value of the input, -1
        \ /¶ /×                 repeat "\ /¶ /" horizontally that many times
               ＋                append that horizontally to one of the first strings
                ;               and get the other, reverse it
                 ↔+             and then append it to the result of above. Now the top part of the helix is done
                   ──           vertically palindromize with no mirroring (works because of a misake - it just doesn't overlap smartly)
                     ╴0<? }     if the input is less than 0
                         ↷        rotate clockwise the whole thing
                           ╴‽   if the input is falsy (aka 0)
                             O    push O; implicitly output the top of stack

```
> 1 votes

# Answer
# Charcoal, ~~28~~ ~~24~~ 22 bytes

```
↙OＦ↔θ/¶\¶ \¶↗‖ＢO¿›Ｎ⁰⟲Ｔ

```

Try it online! Link is to verbose version of code. Explanation:

```
↙O

```

Print the top `O`, and leave the cursor one space down and left.

```
Ｆ↔θ/¶\¶ \¶

```

Print the strings `/`, `\` and `\` and repeat for the absolute number value of the input.

Move back over the last `\`.

```
‖Ｂ

```

Reflect to create the right-hand side of the helix. I do this here because otherwise the  would not parse unambiguously.

```
O

```

Overwrite the last `\` with an `O`.

```
¿›Ｎ⁰⟲Ｔ

```

If the input was positive then rotate the canvas.
> 1 votes

# Answer
## **C++, 352**

Not at all the shortest answer, but the first in C++ so far :)

```
#include <iostream>
int main(int argc, char* argv[]){int a=argv[0][0]-'0';if(a==0){printf("o");}else if(a>0){for(int i =0; i < a;i++){printf(" /\\");}printf("\no");for(int i=0;i<a-1;i++){printf("  /");}printf("  o\n");for(int i=0;i<a;i++){printf(" \\/");}}else{printf(" o\n/ \\\n\\ /\n");for(int i=0;i>a+1;i--){printf("/ \\\n\\ /\n");}printf(" o");};}

```

Here it is in C++ Shell with whitespace to test
> 0 votes

# Answer
# perl 156

```
$==pop;print$=>0?' /\\'x$=.$/:'',$=>0?'O'.'  /'x$=."\bO
":'',$=>0?' \\/'x$=:'';print$=<0?" O":'';print"
/ \\
\\ /
 \\" for$=..-1;print$=<0?"\bO":!$=?"O":''

```

Pretty straight forward attempt, my second golf. I think newlines count as 1 byte right?

Now to figure out how to join all those ternaries together.. I have a lot of room for improvement with those `:'';` everywhere.
> 0 votes

# Answer
## C, 189 bytes

```
char*h="6Er66 e66Ee 6rE66",*v="6e6 E6r r6E 6r6 6e6",*z="e",*u;b,m,w,c,p;f(n){b=n<0;u=b?v:n?h:z;for(m=b?4:1,w=n*(b?-3:3);u[p];p+=++c%((w+2)*m)==w*m?m:p%(6*m)==m*4?-m*3:0)putchar(u[p++]-22);}

```

With whitespace and newlines:

```
char *h="6Er66 e66Ee 6rE66",
     *v="6e6 E6r r6E 6r6 6e6",
     *z="e",
     *u;
b, m, w, c, p;
f(n) {
    b = n < 0;
    u = b ? v : n ? h : z;
    for (m = b ? 4 : 1, w = n * (b ? - 3 : 3);
         u[p];
         p += ++c % ((w + 2) * m) == w * m ? m : p % (6 * m ) == m * 4 ? - m * 3 : 0)
        putchar(u[p++] - 22);
 }

```

Some notes about the approach:

* Stores the pattern in character arrays. They are shifted by 22 characters to avoid needing a bunch of backslashes to escape special characters.
* Uses separate patterns for horizontal, vertical, and zero. I initially considered using one single pattern, and just traversing it differently for positive and negative values. I didn't implement it, but I had a feeling that it would make the logic quite a bit more complicated. Particularly since the central slash has the opposite direction for the two cases. And the tables are not that large, so this seemed more promising.
* The code is mainly just index calculations, with logic to decide when it's done and when the pattern loops. Much of the math is there so that it works for both cases with their different dimensions and repetition rules.
> 0 votes

# Answer
# Perl, 184 bytes

```
$n=pop;$p=$n>0;$_=' \ /'x(1+abs$n*3);$n=$p?$n*4+1:3;$_=join'
',/.{$n}/g;$r=$p?'.':'.*
';s/($r$r)$r($r)/$1$2/g;$p and s/^\S|\S$/O/gm or s/^ \S $|(?<=^ )\S|\S $/O/g;y~\\/~/\\~if$p;print;

```

I thought this was going to be a lot shorter! There are probably some simple things I can do to save a few bytes. It's been five years since I've programmed seriously in Perl!
> 0 votes

# Answer
# PHP, 155

```
$n=$argv[1];$r='str_repeat';$k="/ \\\n\\ /\n";echo$n>0?" /{$r('\ /',$n-1)}\\\nO{$r('  /',$n-1)}  O\n \\{$r('/ \\',$n-1)}/":" O\n{$r("$k \\\n",-$n-1)}$k O";

```
> 0 votes

# Answer
# C (gcc), ~~161~~ 160 bytes

Now more compliant than ever! Thanks to @EriktheOutgolfer for making it so.

```
#define g(n)for(i=n;i--;)printf(
i;f(n){if(n<0){puts(" O");g(-n)"/ \\\n\\ /\n%2c\n",i?92:79);}else{g(n)" /\\");g(1)"\nO"+!n);g(n)i?"  /":"  O\n");g(n)" \\/");}}

```

Try it online!
> 0 votes

# Answer
# , ~~67 59 55~~ 51 bytes

```
(<&0|:' O '(0},[)(3,~3*|)$' / \\'({~,7$[)0,*) ::'O'

```

Try it online!
> 0 votes

# Answer
# SOGL V0.12, 37 bytes

```
 O¶/”▓:.θH{"⌠λ5⁸‘▓+};↕№+╬⁷.0>?I↔}.‽ O

```

Try it Here!
> 0 votes

# Answer
# Ruby, ~~118~~ 138 bytes

```
->i{print i<0?" O ":" /\\"*i+"\n"*(1-0**i),i<0?("\n/ \\\n\\ /\n \\"*-i)[0..-3]:i==0&&"O"||"O "+" / "*(i-1)+" O\n",i<0?" O ":" \\/"*i+"\n"}

```

Basically a if-else statement on all the 3 parts of the helixes :)

Try it online!

Any tips to get it even smaller would be greatly appericated!

Edit: Silly me forgot to remove all the parantheses, and didnt see the requirement of "O" if 0
> 0 votes

# Answer
# Vyxal, 45 bytes

```
ȧDk/ðp*ð+⅛\/w$‹ẋf\Op\OJṄððdV⅛k\ðp*⅛¾?0<ßÞTvṅ⁋

```

Try it Online!

Transposing the input yields the vertical version :)
> 0 votes

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


title: Convert Chevrons to Soliduses

text:
# Question
Title: Convert Chevrons to Soliduses
Write a program that takes in a string containing only spaces, newlines, and angle brackets: `<`, `>` (*chevrons*). Output a string of spaces, newlines, and slashes: `/`, `\` (*soliduses*) whose shapes correspond to the input, **but rotated a quarter turn clockwise, with a column of spaces inserted between each row of the original input** (for aesthetics).

For example, if the input is this:

```
<>

```

The output would be this:

```
/\
\/

```

If the input is this:

```
><<<>
 <><

```

The output would be this:

```
   \/
/\ /\
\/ /\
/\ /\
   \/

```

If the input is this:

```
>>  <<
<>  <>
  <
  ><

```

The output would be this:

```
      /\ \/
      \/ \/
\/ /\
/\
      /\ /\
      \/ /\

```

Notice how there is a single column of spaces between the original input rows in the last two examples.

You may write a full program that takes the input in any usual way (command line, stdin) and prints the output, or you may write a function with a string argument, that prints or returns the output.

Empty leading and trailing rows or columns of whitespace in the input do not need to be present in the output. Additionally, there may be any amount of leading and/or trailing spaces and/or newlines in the output, in any locations, as long as the resulting shapes are correct. In other words, **the translation of the ascii art does not matter, only the shapes and their relation to one another do**.

You may optionally assume the input has a trailing newline.

**The shortest code in bytes wins.**

# Answer
> 6 votes
# CJam, 35 bytes

```
qN/_s,S*f+{iD%[S3*" \/"_$]=}f%W%zN*

```

Try it online here

# Answer
> 6 votes
# Python 2, 105 bytes

```
def f(s):
 for row in map(None,*s.split("\n")):print" ".join("\/ /\ "[1-cmp(c,"<")::3]for c in row[::-1])

```

For all the wrong reasons, this has got to be one of the nicest uses of `map(None, ...)` I've had so far. The output even pads to perfect rectangle.

Let's take the second example:

```
><<<>
 <><

```

`map(None,*s.split("\n"))` performs a poor man's `zip_longest`, giving:

```
[('>', ' '), ('<', '<'), ('<', '>'), ('<', '<'), ('>', None)]

```

Notice how the second line is shorter than the first, so we get a `None` at the end. Normally this would be a problem, but for *some* reason almost everything is comparable in Python 2, and in particular

```
>>> None < ""
True

```

This means that the expression `1-cmp(c,"<")` returns `0, 1, 2` for `">", "<", None` respectively, allowing us to use the string slicing trick to extract one of `"\/", "/\", " "`. Using this, we print the output line by line, joining the 2-char groups with spaces.

# Answer
> 4 votes
# Jelly, 19 bytes

```
Ỵz⁶UµOHØ^ṙaf⁶;`$)€G

```

Try it online!

While I was writing this, it tormented me to no end that the whole mess with `af⁶;`$` could just be `«`, if the codepoint of backslash were somewhere closer to the ballpark of its forward companion. This can *definitely* be golfed further.

```
Ỵ                       Split the input on newlines.
 z⁶                     Transpose with space as filler.
   U                    Reverse each row.
    µ            )€     For each character in each row:
       Ø^ṙ              rotate "/\" by
      H                 half of
     O                  the character's codepoint;
          a             vectorizing logical and with
             ;          concatenate
           f⁶  $        the character filtered to spaces
              `         to itself.
          a             (The slashes are unaffected if the filter removes everything.)
                   G    Grid format: this builtin can do a lot of things,
                        but in this case it joins each row on spaces
                        then joins the rows on newlines.

```

# Answer
> 3 votes
# CJam, 37 bytes

```
qN/_z,S*f{+"< >""/\    \/ "3/er}W%zN*

```

Try it online in the CJam interpreter.

### How it works

```
qN/                                   e# Read from STDIN and split at linefeeds.
   _z,                                e# Zip a copy and push the results length.
                                      e# This computes the maximum line length.
      S*                              e# Repeat " " that many times.
        f{                     }      e# For each line:
                                      e#   Push the string of spaces.
          +                           e#   Append it to the line.

           "< >""/\    \/ "3/         e#   Push "< >" and ["/\ " "   " "\/ "].
                             er       e#   Perform transliteration.
                                W%z   e# Reverse the lines and zip.
                                      e# This rotates by 90 degrees.
                                   N* e# Join, separating by linefeeds.

```

# Answer
> 3 votes
# Vyxal, 21 bytes

```
ƛ`<> `k/m6↲ǒĿð+;Ṙ∩øɽ⁋

```

Try it Online!

```
ƛ              ;      # For each line
            Ŀ         # Replace
 `<> `                # Each of "<> "
      k/m6↲ǒ          # with corresponding elements of "/\", "\/", "  "
             ð+       # Append a space to each
                Ṙ∩    # Rotate 90°
                  øɽ⁋ # Right align and join by newlines

```

# Answer
> 2 votes
# Husk, 30 bytes

```
mȯσ" ""  "σ"<""/¦"σ">""¦/"T' ↔

```

Try it online!

I made the clunkiest possible solution.

# Answer
> 2 votes
# Stax, 19 bytes

```
Çºòî@f┬U☺≥•:Γ_ƒ←⌠Φô

```

Run and debug it

# Answer
> 1 votes
# Scala, ~~201~~ ~~188~~ 180 characters

```
(s:String)⇒(Seq("")→0/:s.lines.flatMap(l⇒Seq(l,l))){case((v,i),l)⇒(l.map(c⇒if(Set('>','<')(c))if(c%4==i)'/'else'\\'else c)+:v,2-i)}._1.init.transpose.map(_.mkString).mkString("\n")

```

### note:

this only works if the provided string has all lines with equal length (i.e. padded with spaces)

## explanation:

I'm using fold with initial value of tuple of a `Seq[String]` and an `Int` (instead of writing `Seq.empty[String]` im writing the shorter `Seq("")` and `.init` after the fold), the fold operates on a collection of strings, each string is a line in the original input, and every line is doubled. the trick here was to test for modulo of the char. since `'<'` value is 60, and `'>'` value is 62, testing for modulo 4, will yield 0 or 2. that's why the fold also carry a flipping `Int` set to 0. and flipped between 0 and 2 with `2-i`. every odd line should map `'>'` to `'/'` and `'<'` to `'\\'`, and every even line should map `'>'` to `'\\`' and `'<'` to `'/'`. this is why i test for `c%4==i` and hit 2 birds with 1 stone. the fold "rebuilds" the initial sequence of strings in reverse, and then (after dropping the last line), I transpose the sequence (this is why all strings must be of exact same length). because of the implicits involved, I need to `_.mkString` on each line (previously column), and then `mkString("\n")` for the final output.

# Answer
> 1 votes
# Perl - 119

```
@l=map[/./g],reverse<>;do{print;$_=join(' ',map({'<'=>'/\\','>'=>'\/'}->{$_->[$b]}||'  ',@l))."\n";$b++;}while(/[^
]/)

```

First, `@l` is assigned as a list of lists representing the characters on each line of input with lines in reverse order. Then it loops through the columns of characters, replacing the angle brackets with the corresponding slashes, joining the elements with spaces, and printing the joined slashes as a line.

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


title: ASCII Art Archery Arrows

text:
# Question
Title: ASCII Art Archery Arrows
Write a program or function that takes in a positive integer and prints or returns an ASCII art depiction of an archery arrow, scaled according to the input.

If the input is `1` the output is

```
  /\
 /  \
 \__/
  ||
  ||
  ||
  ||
  ||
  ||
  ||
  ||
 /||\
/ || \
/ || \
//  \\
/    \

```

If the input is `2` the output is

```
     /\
    /  \
   /    \
  /      \
  \      /
   \____/
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
   /|  |\
  / |  | \
 /  |  |  \
/   |  |   \
/   |  |   \
/   |__|   \
/  /    \  \
/ /      \ \
//        \\
/          \

```

If the input is `3` the output is

```
        /\
       /  \
      /    \
     /      \
    /        \
   /          \
   \          /
    \        /
     \______/
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
      |    |
     /|    |\
    / |    | \
   /  |    |  \
  /   |    |   \
 /    |    |    \
/     |    |     \
/     |    |     \
/     |    |     \
/     |____|     \
/    /      \    \
/   /        \   \
/  /          \  \
/ /            \ \
//              \\
/                \

```

If the input is `4` the output is

```
           /\
          /  \
         /    \
        /      \
       /        \
      /          \
     /            \
    /              \
    \              /
     \            /
      \          /
       \________/
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
        |      |
       /|      |\
      / |      | \
     /  |      |  \
    /   |      |   \
   /    |      |    \
  /     |      |     \
 /      |      |      \
/       |      |       \
/       |      |       \
/       |      |       \
/       |      |       \
/       |______|       \
/      /        \      \
/     /          \     \
/    /            \    \
/   /              \   \
/  /                \  \
/ /                  \ \
//                    \\
/                      \

```

The pattern continues on for larger input numbers - the arrow is scaled up accordingly.

Notice that for any input N:

* The arrowhead is a pentagon with 2×N underscores at the base, N slashes on each of the sides extending from the base, and 2×N slashes on the two sides that form the arrow tip.
* The shaft (including the part within the fletching) consists of 11×N lines of two vertical bars separated by 2×(N-1) spaces. The very last line has underscores instead of spaces.
* The fletching surrounds the lower 3×N lines of the shaft. Two lines of 2×N slashes extend diagonally downward from either side of the shaft and are joined with vertical columns of slashes.
* The complete arrow is 16×N lines high and 6×N characters wide.

In your output there should be no empty lines before the arrow tip and only up to one trailing newline.

None of the output lines should have unnecessary leading spaces (the left edge of the fletching should be as leftmost as possible) but any of the lines may have any number of trailing spaces.

**The shortest submission in bytes wins.**

# Answer
# Pyth, ~~149~~ ~~147~~ ~~146~~ ~~144~~ 146

*Edit 2015-9-23: had a bug, fixed for 2 bytes. Might be possible to make shorter, I have no time now.*

Still seems too long for a Pyth answer.

```
M*tGHK*11Q=Y*3QA" /"jbC+R*yQG+_Js[ms[*dGHgt-YdG\_gKG\_)tQs[gQGHgyQG\_*K\|)ms[*+QdGH*y-tQdG\\*+*8QydGHgYGH)Qms[*++KQdGHgYGH)tQ+g*13QG*hYH)mXd"\/")J

```

## Explanation (almost up to date)

I basically generate the transpose of the arrow, since its line format is much simpler. Also, I only generate one half and then reverse it to save a lot of bytes.

```
M*tGH                                                       g(a,b) = (a - 1) * b
A" /"                                                       G = " ", H = "/"
              ms[...)tQ                                     N-1 lines inside body
                       s[...)                               1 line of edge of body
                             ms[...)Q                       N lines of tip + fin
                                     m...Q                  N-1 lines of fin
                                          +...              1 line of edge of fin
            s[                                )             flatten the maps to it
           J                                                save to J
          _                                                 reverse
                                                       J    another copy (unreversed)
                                               mXd"\/")     swap "\" and "/" on each line
         +                                                  add to other half
   +R*yQG                                                   add 2*N spaces to each line
  C                                                         transpose
jb                                                          join by newline

m                             tQ       map d over 0...N-2
 s[                          )         concatenate
   *dG                                 d spaces
      H                                "/"
          =Y*3Q                        save 3*N to Y
       gt-     dG                      3*N-d-2 spaces
                 \_                    "_"
                    K*11Q              save 11*N to K
                   g     G             11*N-1 spaces
                          \_           "_"

s[              )                      concatenate
  gQG                                  N-1 spaces
     H                                 "/"
      gyQG                             2*N-1 spaces
          \_                           "_"
            *K\|                       11*N pipes

m                               Q      map d over 0...N-1
 s[                            )       concatenate
   *+QdG                               N+d spaces
        H                              "/"
         *y-tQdG                       2*(N-d-1) spaces
                \\                     "\"
                  *+*8QydG             8*N+2*d spaces
                          H            "/"
                           gYG         3*N-1 spaces
                              H        "/"

m               tQ                     map d over 0...N-2
 +++                                   concatenate
    *++KQdG                            12*N+d spaces
           H                           "/"
            gYG                        3*N-1 spaces
               H                       "/"

+                                      concatenate
 g*13QG                                13*N-1 spaces
       *hYH                            3*N+1 slashes

```
> 2 votes

# Answer
# Perl, 298 bytes

```
for$y(0..($w=<>)*16-1){$r=$w*3;for$x(0..$w*6-1){$z=$x<$r?$x:$w*6-$x-1,$_.=$z==$r-$y-1&&$y<$w*2||!$z&&$y>=$w*13-1||($z==$w*16-1-$y||$z==$w*13-1-$y)&&$z<$w*2?$x<$r?'/':'\\':$z==$y-$w&&$y>=$w*2&&$y<$r?$x<$r?'\\':'/':$z==$r-$w&&$y>=$r&&$y<$w*14?'|':$z>=$r-$w&&($y==$r-1||$y==$w*14-1)?_:$"}$_.=$/}print

```

Multi-line:

```
for$y(0..($w=<>)*16-1){$r=$w*3;  # read input and loop over rows
    for$x(0..$w*6-1){  # loop over columns

        # flip x on right side of arrow:
        $z=$x<$r?$x:$w*6-$x-1;

        # slashes on fletching and tip of arrowhead:
        $_.=$z==$r-$y-1&&$y<$w*2||!$z&&$y>=$w*13-1||($z==$w*16-1-$y||$z==$w*13-1-$y)&&$z<$w*2?$x<$r?'/':'\\':

        # slashes on underside of arrowhead:
        $z==$y-$w&&$y>=$w*2&&$y<$r?$x<$r?'\\':'/':

        # vertical bars on side of shaft:
        $z==$r-$w&&$y>=$r&&$y<$w*14?'|':

        # underscores on base of arrowhead and shaft:
        $z>=$r-$w&&($y==$r-1||$y==$w*14-1)?_:$"
   }
   $_.=$/  # add newline at end of each row
}
print  # print out string

```

Output:

```
2
     /\
    /  \
   /    \
  /      \
  \      /
   \____/
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
    |  |
   /|  |\
  / |  | \
 /  |  |  \
/   |  |   \
/   |  |   \
/   |__|   \
/  /    \  \
/ /      \ \
//        \\
/          \

```

Thanks to Dom Hastings for helping me save 5 (and counting) bytes
> 4 votes

# Answer
# Julia, 452 bytes

This answer isn't very inspired, and I haven't golfed it beyond the glaringly obvious. I intend for this to be a score for other people to beat.

```
function R(c,x,y,e,f,n)
for i=1:n
a[y,x]=c
x+=e
y+=f
end
end
function f(n::Int)
global a=fill(' ',16n,6n)
F='/'
B='\\'
q=3n+1
r=2n+1
R(F,3n,1,-1,1,2n)
R(B,q,1,1,1,2n)
R(B,n+1,r,1,1,n)
R(F,5n,r,-1,1,n)
R('_',r,3n,1,0,2n)
R('|',r,q,0,1,11n)
R('|',4n,q,0,1,11n)
R('_',r+1,14n,1,0,r-3)
R(F,2n,11n+1,-1,1,2n)
R(B,4n+1,11n+1,1,1,2n)
R(F,1,13n,0,1,3n)
R(B,6n,13n,0,1,3n)
R(F,2n,14n+1,-1,1,2n)
R(B,4n+1,14n+1,1,1,2n)
for b = 1:16n
println(join(a[b,:]))
end
end

```

Try it out:

```
julia> f(1)
  /\
 /  \
 \__/
  ||
  ||
  ||
  ||
  ||
  ||
  ||
  ||
 /||\
/ || \
/ || \
//  \\
/    \

```

ungolfed:

```
# Repeat a character through array a from (x,y) -> (x+n*dx,y+n*dy)
function R(a::Array{Char,2},c::Char, x::Int, y::Int, dx::Int, dy::Int, n::Int)
    for i = 1:n
        a[y,x] = c
        x += dx
        y += dy
    end
end

function arrow(n::Int)
    a = fill(' ',16n,6n)
    # upper left of head
    R(a,'/',3n,1,-1,1,2n)
    # upper right of head
    R(a,'\\',3n+1,1,1,1,2n)
    # lower left of head
    R(a,'\\',n+1,2n+1,1,1,n)
    # lower right of head
    R(a,'/',5n,2n+1,-1,1,n)
    # bottom of head
    R(a,'_',2n+1,3n,1,0,2n)
    # shaft
    R(a,'|',2n+1,3n+1,0,1,11n)
    R(a,'|',4n,3n+1,0,1,11n)
    R(a,'_',2n+2,14n,1,0,2n-2)
    # upper fletching edges
    R(a,'/',2n,11n + 1,-1,1,2n)
    R(a,'\\',4n+1,11n+1,1,1,2n)
    # fletching sides
    R(a,'/',1,13n,0,1,3n)
    R(a,'\\',6n,13n,0,1,3n)
    # lower fletching edges
    R(a,'/',2n,14n + 1,-1,1,2n)
    R(a,'\\',4n+1,14n+1,1,1,2n)
    for r = 1:16n
        println(join(a[r,:]))
    end
end

```
> 2 votes

# Answer
# Ruby, 233

```
->n{(16*n).times{|i|j=i/n
m=n*3
e=' '*6*n
i%(11*n)==m-1&&e[2*n..4*n-1]=?_*2*n
j%14>2&&e[m+n-1]=e[m-n]=?|
k=(i-n)%m
k<n||j<11||(e[m+k]=?\\;e[m-1-k]=?/)
j>12&&(e[-1]=?\\;e[0]=?/)
j<3&&(e[n+l=(i-n*2)%(n*4)]=?\\;e[5*n-l-1]=?/)
puts e}}

```

I am particularly pleased with the wraparound technique I used to draw all `\` in the head with a single expression (and likewise for `/`)

**Ungolfed in test program**

```
f=->n{
  #loop line by line, 0..16*n-1
  (16*n).times{|i|

  #convenience variables
  j=i/n
  m=n*3

  #setup a string of spaces
  e=' '*6*n

  #draw the ___ at top and bottom of shaft
  i%(11*n)==m-1&&e[2*n..4*n-1]=?_*2*n
  #draw the |, overwriting the _ in the bottom corners
  j%14>2&&e[m+n-1]=e[m-n]=?|

  #draw the diagonal fletching
  k=(i-n)%m
  k<n||j<11||(e[m+k]=?\\;e[m-1-k]=?/)

  #draw the ends of the fletching (note index -1, meaning last character in string)
  j>12&&(e[-1]=?\\;e[0]=?/)

  #draw the arrow head, wrapping round with %(n*4)
  j<3&&(e[n+l=(i-n*2)%(n*4)]=?\\;e[5*n-l-1]=?/)

  #output the line
  puts e}
}

f.call(gets.to_i)

```
> 2 votes

# Answer
# Vyxal, 128 bytes

```
d(\/n꘍⁰3*↳øṀ,)(⁰n+\\꘍⁰d‹n- n⁰‹=[\_|ð]*+øṀ,)8*(⁰d\|꘍⁰‹꘍m,)d(\/n꘍⁰d↳\|+⁰‹꘍øṀ,)(\/⁰d↲\|+n⁰‹=[\_|ð]⁰‹*+øṀ,)d(\/n꘍⁰d‹↳:L⁰d≠[\/p]⁰꘍øṀ,

```

Try it Online!

Generates the rocket bit by bit.
> 1 votes

# Answer
## Python 3, 336 bytes

```
def f(n):
 N=n+n;R=[*range(3*n)]
 L = [f'/{i*"  "}\\' for i in R[:N]] + [f'\\{2*(N+~i)*"_ "[i+1<n]}/' for i in R[:n]] + [f'|{"  "*~-n}|']*8*n + [
  f'/{"|"+2*~-n*"_ "[i+1<3*n]+"|":^{2*min(i,N-1)+N}}\\' for i in R
 ] + ["/"*(i+1<N)+f'/{"  "*(n+i)}\\'.center(6*n-2)+"\\"*(i+1<N) for i in R[:N]]
 return "\n".join(u.center(6*n).rstrip() for u in L)

```
> 1 votes

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


title: Implement Malbolge's "crazy" operator

text:
# Question
Title: Implement Malbolge's "crazy" operator
One of many unique features of the Malbolge programming language is its highly unintuitive `OP` operator, referred to only as "op" in the documentation and source code but popularly known as the "crazy" operator. As described by Ben Olmstead, the creator of the language, in its documentation: "*don't look for pattern, it's not there*."

op is a "tritwise" operator -- it operates on corresponding ternary digits of its two arguments. For each trit (ternary bit), the result of op is given by the following lookup table:

```
           a
op(a,b)  0 1 2
       +-------
     0 | 1 0 0
   b 1 | 1 0 2
     2 | 2 2 1

```

For example, to calculate `op(12345, 54321)`, first write out both numbers in ternary and then look up each pair of trits in the table:

```
   0121221020   (12345_3)
op 2202111220   (54321_3)
--------------
   2202220211   (54616_3)

```

The last important point is that all values in Malbolge are 10 trits wide, so input values should be padded with zeroes to a width of 10. (For instance, `op(0, 0)` is `1111111111` in ternary.)

Your task is to take two integers 0 ≤ `a`, `b` \< 59049 as input, and output the integer value of `op(a,b)`.

Test cases (in the format `a b op(a,b)`):

```
0 0 29524
1 2 29525
59048 5 7
36905 2214 0
11355 1131 20650
12345 54321 54616

```

Here is a reference implementation (copied directly from the Malbolge source code).

# Answer
> 45 votes
# C (gcc), ~~99~~ ~~98~~ 96 bytes

* Saved a byte thanks to ceilingcat; golfing `19683` to `L'䳣'`.
* Saved two bytes; golfing `108609` to `L''`.

```
M,a,l,b,o;L(g,e){for(o=b=L'䳣',l=0;o/=2.4;b/=3)M=g/b,g%=b,a=e/b,e%=b,l+=b*(L''>>M+6*a+M&3);g=l;}

```

Try it online!

# Answer
> 30 votes
# JavaScript (ES7), 56 bytes

```
f=(a,b,k=9)=>~k&&(a%3|b%3<<9|8)**2%82%3+3*f(a/3,b/3,k-1)

```

Try it online!

## How?

Given \\$a\\$ and \\$b\\$ in \\$\[0..2\]\\$, we compute:

$$f(a,b)=((a+512b+8)^2 \bmod 82) \bmod 3$$

Leading to:

```
 a | b | 512b | a + 512b |  + 8 | squared | MOD 82 | MOD 3
---+---+------+----------+------+---------+--------+-------
 0 | 0 |    0 |      0   |    8 |      64 |   64   |   1                  a
 1 | 0 |    0 |      1   |    9 |      81 |   81   |   0                0 1 2
 2 | 0 |    0 |      2   |   10 |     100 |   18   |   0              +-------
 0 | 1 |  512 |    512   |  520 |  270400 |   46   |   1            0 | 1 0 0
 1 | 1 |  512 |    513   |  521 |  271441 |   21   |   0    -->   b 1 | 1 0 2
 2 | 1 |  512 |    514   |  522 |  272484 |   80   |   2            2 | 2 2 1
 0 | 2 | 1024 |   1024   | 1032 | 1065024 |    8   |   2
 1 | 2 | 1024 |   1025   | 1033 | 1067089 |   23   |   2
 2 | 2 | 1024 |   1026   | 1034 | 1069156 |   40   |   1

```

### Function choice

There are several other possible candidate functions of the form:

$$f\_{k,c,p,m}(a,b)=((a+kb+c)^p \bmod m) \bmod 3$$

One of the shortest ones being:

$$f(a,b)=((a+5b+2)^4 \bmod 25) \bmod 3$$

But the good thing about \\$(a+512b+8)\\$ is that it can be performed with bitwise operators, thus implicitly discarding the decimal parts of \\$a\\$ and \\$b\\$. This is why we can simply divide them by \\$3\\$ without rounding between each iteration.

### Commented

```
f = (a, b,            // given the input integers a and b
           k = 9) =>  // and starting with k = 9
  ~k &&               // if k is not equal to -1:
    ( a % 3           //   compute (a mod 3)
      | b % 3 << 9    //   add 512 * (b mod 3)
      | 8             //   add 8
    ) ** 2            //   square the result
    % 82              //   apply modulo 82
    % 3               //   apply modulo 3, leading to crazy(a % 3, b % 3)
    + 3 * f(          //   add 3 times the result of a recursive call with:
      a / 3,          //     a / 3  \__ no rounding required
      b / 3,          //     b / 3  /   (see 'Function choice')
      k - 1           //     k - 1
    )                 //   end of recursive call

```

# Answer
> 13 votes
# 05AB1E, 18 bytes

### Code:

```
3Tm+3Bø5+3m5(^3%3β

```

Uses the **05AB1E** encoding. Try it online!

### Algorithm Explanation

In order to get the number padded with zeroes, we need to add **59049** to both numbers (because 59049 in ternary is **10000000000**). We do not have to leave out the leading **1** as \\$(1, 1) \rightarrow 0\\$. We convert the numbers from decimal to ternary and join each pair as each own number.

For example, for input **12345** and **54321**, these get mapped to:

$$ \begin{array} & 12345 \rightarrow & 1 & 0 & 1 & 2 & 1 & 2 & 2 & 1 & 0 & 2 & 0 \\ 54321 \rightarrow & 1 & 2 & 2 & 0 & 2 & 1 & 1 & 1 & 2 & 2 & 0 \end{array} $$

Which gives the following list of joined integers:

$$ 11, 2, 12, 20, 12, 21, 21, 11, 2, 22, 0 $$

These integers need to be mapped by the given lookup table in the OP. The formula we currently use that maps these numbers to their corresponding trits (\\$0 \rightarrow 1, 10 \rightarrow 0, \dots\\$) is:

$$ f(x) = \left((x + 5)^3 \oplus -5\right) \text{ mod }3 $$

Whereas \\$\oplus\\$ denotes the bitwise **xor** function.

Eventually after mapping this function on the list of joined integers, we treat this resulting list as a number represented in base 3 and convert it from base 3 to decimal.

### Code Explanation

```
3Tm+                  # Add 59049 to pad the ternary number with zeroes.
    3B                # Convert to base 3.
      ø               # Zip the list to get each joined integer.
       5+             # Add 5 to each element.
         3m           # Raise each element to the power of 3.
           5(^        # XOR each element with -5.
              3%      # Modulo each element with 3.
                3β    # Convert from base 3 to decimal.

```

# Answer
> 11 votes
# , ~~64~~ 62 bytes

```
function(a,b,x=3^(9:0))30801%/%x[a%/%x%%3*3+b%/%x%%3+1]%%3%*%x

```

Try it online!

*Thanks to JAD for some ~~black magic~~ golfing tricks and -2 bytes!*

`30801`, when converted to a 10-trit ternary integer, is `1120020210` which just adds a trailing zero to the operation table, when read down the columns. Then we convert the ternary digits of `a` and `b` elementwise into an integer and use that as an index into the ternary digits of `30801`.

# Answer
> 11 votes
# C (gcc), ~~74~~ ~~72~~ 71 bytes

```
f(a,b,i,r){for(r=0,i=59049;i/=3;)r+=(108609>>a/i%3*2+b/i%3*6&3)*i;i=r;}

```

Try it online!

## Breakdown

The truth table

```
           a
op(a,b)  0 1 2
       +-------
     0 | 1 0 0
   b 1 | 1 0 2
     2 | 2 2 1

```

Can be thought of as a 3x3 array, where a is the column, and b is the row. Transforming that into a one-dimensional list gives us 100102221. To save space we avoid lists and strings and make it into a number instead. To do that, we flip the order and transform every trit into a 2-bit number. Glue them together and we have a binary number we can "index" into by shifting to the right by `2 * (b * 3 + a)` and masking:

```
 1 0 0 1 0 2 2 2 1
 1 2 2 2 0 1 0 0 1
011010100001000001

```

Next, we massage the expression using the power of operation precedence to become the abomination above.

~~3^9 = 19683 so that is a good loop limit. Since we multiply the counter by 3 each time, we can write the limit as `2e4` instead. Also we save ourselves the bother of `pow()` or similar.~~

On second thought, let's start at 3^10 and work downwards with a pre-loop divide-and-test.

# Answer
> 8 votes
# Haskell, 108 bytes

```
2%2=1
_%2=2
0%_=1
2%1=2
_%_=0
g=take 10.map(`mod`3).iterate(`div`3)
(foldr((.(3*)).(+))0.).(.g).zipWith(%).g

```

Try it online!

# Answer
> 7 votes
# APL (Dyalog), ~~41~~ 25 bytes

*9 bytes saved thanks to @Adám*

```
3⊥(b⊤6883)[3⊥⍉⎕⊤⍨3,b←9⍴3]

```

Try it online!

# Answer
> 6 votes
# Jelly,  ~~23~~  18 bytes

-1 thanks to Erik the Outgolfer (rearrange `3*⁵¤` to `⁵3*`)

```
⁵3*+b3Zḅ3ị⁽½Ṡb3¤ḅ3

```

A monadic link accepting a list of two integers.

**Try it online!** Or see a test-suite.

`⁹*%733%3` is a byte longer than `ị⁽½Ṡb3¤` :(

### How?

```
⁵3*+b3Zḅ3ị⁽½Ṡb3¤ḅ3 - Link: [a, b]      e.g. [11355,1131]
⁵                  - literal ten            10
 3                 - literal three          3
  *                - exponentiation         59049
   +               - addition (vectorises)  [70404,60180]
     3             - literal three          3
    b              - to base (vectorises)   [[1,0,1,2,0,1,2,0,1,2,0],[1,0,0,0,1,1,1,2,2,2,0]]
      Z            - transpose              [[1,1],[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2],[0,0]]
        3          - literal three          3
       ḅ           - from base (vectorises) [4,0,3,6,1,4,7,2,5,8,0]
               ¤   - nilad followed by link(s) as a nilad:
          ⁽½Ṡ      -   literal 3706         3706
              3    -   literal three        3
             b     -   to base              [1,2,0,0,2,0,2,1]
         ị         - index into             [0,1,0,0,1,0,2,2,2,1,1]
                 3 - literal three          3
                ḅ  - from base              20650

```

---

Also 18: `⁵3*+b3ZḌ19*%74%3ḅ3` (uses a magic-formula after getting the pair-wise trits of converting from base ten then taking 19 to that power, modulo 74, modulo 3 to get the required trits of the output - found using a search in Python)

# Answer
> 5 votes
# Python 2, ~~79~~ ~~65~~ ~~63~~ 61 bytes

thanks to Arnauld for his formula (-2 bytes).

```
f=lambda a,b,i=9:i+1and(a%3+b%3*5+2)**4%25%3+f(a/3,b/3,i-1)*3

```

Try it online!

# Answer
> 4 votes
# , 37 bytes

```
((3 3$d 30801){~{@,.)&.(d=.(10$3)&#:)

```

Explanation:

```
((3 3$d 30801){~{@,.)&.(d=.(10$3)&#:)
                       (d=.(10$3)&#:)   convert to 10 trits, and name this function as d
                     &.                 ... which is done on both args and inverted on the result
                {@,.                    make boxed indices: 1 2 3 4 {@,. 5 6 7 8  ->  1 5 ; 2 6 ; 3 7 ; 4 8
              {~                        index out of a lookup table
 (3 3$d 30801)                          reusing the trits conversion function to make the table

```

Ended up being relatively readable, tbh.

# Answer
> 3 votes
# Charcoal, 31 bytes

```
Ｉ↨³⮌⭆χ§200211⁺∨﹪÷θＸ³ι³¦⁴﹪÷ηＸ³ι³

```

Try it online! Link is to verbose version of code. Explanation:

```
     χ                          Predefined variable 10
    ⭆                           Map over implicit range and join
                    ι        ι  Current index
                  Ｘ³       Ｘ³   Power of 3
                 θ              Input `a`
                          η     Input `b`
                ÷        ÷      Integer divide
               ﹪     ³  ﹪     ³ Modulo by 3
              ∨       ¦⁴        Replace zero ternary digit of `a` with 4
             ⁺                  Add
      §200211                   Index into literal string `200211`
   ⮌                            Reverse
 ↨³                             Convert from base 3
Ｉ                               Cast to string
                                Implicitly print

```

Alternative solution, also 31 bytes:

```
Ｉ↨³Ｅ↨⁺Ｘ³χθ³§200211⁺∨ι⁴§↨⁺Ｘ³χη³κ

```

Try it online! Link is to verbose version of code.

```
        χ                  χ    Predefined variable 10
      Ｘ³                 Ｘ³     Power of 3 i.e. 59049
         θ                      Input `a`
                            η   Input `b`
     ⁺                  ⁺       Sum
    ↨     ³            ↨     ³  Convert to base 3
   Ｅ                            Map over elements
                    ι           Current ternary digit of `a`
                   ∨ ⁴          Replace zero with 4
                      §       κ Index into ternary digits of `b`
                  ⁺             Add
           §200211              Index into literal string `200211`
 ↨³                             Convert from base 3
Ｉ                               Cast to string
                                Implicitly print

```

# Answer
> 3 votes
# Python 2, ~~90~~ 87 bytes

```
f=lambda a,b,A='':f(a/3,b/3,'100102221'[a%3+b%3*3]+A)if a+b else int(A.rjust(10,'1'),3)

```

Try it online!

# Answer
> 3 votes
# Stax, 22 bytes

```
é╨¼aûé∟ç⌂zπb![5┬◘«╜‼╞♠

```

Run and debug it

# Answer
> 3 votes
# K (ngn/k), ~~25~~ 22 bytes

```
3/(3\10267)@3/+(10#3)\

```

Try it online!

# Answer
> 2 votes
# Ruby, 70 bytes

```
->a,b,l=10{l>0?6883.digits(3)[8-b%3*3-a%3]*3**(10-l)+f[a/3,b/3,l-1]:0}

```

Try it online!

Decomposes `a` and `b` recursively until we get 10 digits of each. `6883` gives the flattened ternary table (reversed). Reconstructs from ternary to decimal by multiplying by `3**(10-l)`.

# Answer
> 2 votes
## Cjam, 31 bytes

```
{{3bA0e[\}2*.{3*+"100102221"=}}

```

Try it online!

# Answer
> 2 votes
# , 43 bytes

```
3#.((3 3$t 6883){~<@,~"0)&(_10{.t=.3&#.inv)

```

It can certainly be golfed further.

## Explanation:

```
                         &(               ) - for both arguments
                                t=.3&#.inv  - convert to base 3 (and name the verb t)
                           _10{.            - pad left with zeroes
   (              <@,~"0)                   - box the zipped pairs (for indexing)
    (3 3$t 6883)                            - the lookup table
                {~                          - use the pairs as indeces in the table
3#.                                         - back to decimal

```

Try it online!

# Answer
> 2 votes
# Pyth ~~26 25~~ 24 bytes

*Saved 1 byte, thanks to @ErikTheOutgolfer*

*Save another byte, inspired by @JonathanAllan's answer*

```
im@j3422 3id3Cm.[0Tjd3Q3

```

Input is a 2 element list `[a,b]`. Try it online here, or verify all test cases here.

```
im@j3422 3id3Cm.[0Tjd3Q3   Implicit: Q=eval(input())
              m       Q    Map each element d of the input using:
                   jd3       Convert to base 3
               .[0T          Pad to length 10 with 0's
             C             Transpose
 m                         Map each element d of the above using:
   j3422 3                   The lookup table [1,1,2,0,0,2,0,2]
  @                          Modular index into the above using
          id3                Convert d to base 10 from base 3
i                      3   Convert to base 10 from base 3, implicit print

```

# Answer
> 2 votes
# Japt, ~~24~~ 23 bytes

Getting the ball rolling on Japt's run as language of the month \- I fully expect to be outgolfed on this!

Takes input in reverse order as an integer array (i.e., `[b,a]`).

```
ms3 ùTA y_n3 g6883ì3Ãì3

```

Try it

```
ms3 ùTA y_n3 g6883ì3Ãì3      :Implicit input of array U=[b,a]
m                            :Map
 s3                          :  Convert to base-3 string
    ù                        :Left pad each
     T                       :  With zero
      A                      :  To length 10
        y                    :Transpose
         _                   :Map
          n3                 :  Convert from base-3 string to decimal
             g               :  Index into
              6883ì3         :    6883 converted to a base-3 digit array
                    Ã        :End map
                     ì3      :Convert from base-3 digit array to decimal

```

# Answer
> 1 votes
# MMIX, 77 bytes (17 instrs + 9 data bytes)

```
00000000: e303000a f4040010 e3020000 e3050001  ẉ¤¡½ṡ¥¡Ñẉ£¡¡ẉ¦¡¢
00000010: 25030301 1d000003 fe060006 1d010103  %¤¤¢ø¡¡¤“©¡©ø¢¢¤
00000020: feff0006 28060606 200606ff 80060406  “”¡©(©©© ©©”⁰©¥©
00000030: 18060506 20020206 28050505 5b03fff5  ð©¦© ££©(¦¦¦[¤”ṫ
00000040: f8030000 01010200 00020002 01        ẏ¤¡¡¢¢£¡¡£¡£¢

```

```
malop   SET   $3,10         // i = 10
        GETA  $4,1F         // oparr = {1,1,2,0,0,2,0,2,1}
        SET   $2,0          // r = 0
        SET   $5,1          // p = 1
0H      SUB   $3,$3,1       // loop: i--
        DIV   $0,$0,3
        GET   $6,rR         // x:xr = x /% 3
        DIV   $1,$1,3
        GET   $255,rR       // y:yr = y /% 3
        2ADDU $6,$6,$6
        ADD   $6,$6,$255
        LDB   $6,$4,$6      // j = oparr[xr * 3 + yr]
        MUL   $6,$5,$6      // j *= p
        ADD   $2,$2,$6      // r += j
        2ADDU $5,$5,$5      // p *= 3
        PBNZ  $3,0B         // if(i) goto loop
        POP   3,0           // return r
1H      BYTE  1,1,2,0,0,2,0,2,1

```

# Answer
> 0 votes
# Perl 5 `-p`, 102 bytes

```
sub t{map{("@_"%3,$_[0]/=3)[0]}0..9}@a=t$_;@b=t<>}{$\=(1,1,2,0,0,2,0,2,1)[(3*pop@a)+pop@b]+$\*3while@a

```

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), ~~75~~ ~~72~~ 60 bytes

```
(d=IntegerDigits)[6883,3][[{1,3}.d[#,3,10]+1]]~FromDigits~3&

```

Try it online!

un-golfed version:

```
M[{a_, b_}] :=
  FromDigits[{1, 0, 0, 1, 0, 2, 2, 2, 1}[[
    IntegerDigits[a, 3, 10] + 3*IntegerDigits[b, 3, 10] + 1
  ]], 3];

```

Both `a` and `b` are converted to ten-trit lists, then used pairwise as a 2D index into a lookup table of numbers `{1, 0, 0, 1, 0, 2, 2, 2, 1}`. The result is again interpreted as a ten-trit list and converted back to integer form.

The lookup table is coded as `IntegerDigits[6883,3]`, which is short because we are recycling the `IntegerDigits` symbol.

---
Tags: code-golf, number
---


title: Side to side, not up and down

text:
# Question
Title: Side to side, not up and down
# Task

Given a list of nodes representing a binary tree of positive integers serialized depth-first, return a list of nodes representing the same tree serialized breadth-first. To represent an absent child, you may use `null`, `0`, `'X'`, `Nothing`, `[]`, or any other value that is distinct from your representation of a node's value, which can be represented by an integer or an integer in a singleton list or other collection.

For example, here is an example tree :

```
         1
      /     \
     /       \
    5         3
   / \       / \
  #   4     10  2
     / \   / \ / \
    4   6 #  # #  7
   /\  /\         /\
  # # #  #       #  #

```

Serialized depth-first, this would be `[1, 5, #, 4, 4, #, #, 6, #, #, 3, 10, #, #, 2, #, 7, #, #]` (here, `#` indicates that a child does not exist). This list was made using a pre-order traversal (add a node's value to the list, serialize its left child or add `#` if it doesn't exist, serialize its right child or add `#` if it doesn't exist).

Serialized breadth-first, this would be `[1, 5, 3, #, 4, 10, 2, 4, 6, #, #, #, 7, #, #, #, #, #, #]` (you may trim as many of the `#`'s at the end as you want, I just wanted to make them explicit). Here, you write the root node's value, then the values of all the nodes on the level below, left to right (with a `#` where a node doesn't exist), then values of the level below, until all the nodes are added to the list.

# Test cases

```
[1] -> [1, #, #] //or [1], whatever you wish

Tree: 1   //or just 1
     / \
    #   #
([1, #, #] and [1, #] yield the same result as above)

[100, 4, 5, #, #, #, #] -> [100, 4, #, 5, #, #, #]
Tree:    100
        /   \
       4     #
      / \
     5   #
    / \
   #   #

[10, 5, 2, 2, #, #, 2, #, #, #, 4, 8, 4, #, #, #, 1, #, #] -> [10, 5, 4, 2, #, 8, 1, 2, 2, 4, #, #, #, #, #, #, #, #, #]
Tree:     10
        /    \
       5      4
      / \    / \
     2   #  8   1
    / \    / \  / \
   2   2  4  # #  #
  /\  /\  /\
 # # # # # #

[100, #, 4, 5, #, #, #] -> [100, #, 4, 5, #, #, #]
Tree:    100
        /   \
       #     4
            / \
           5   #
          / \
         #   #

```

This is , so shortest code wins!

Brownie points for coming up with a better name for this question

# Answer
# Python 3, 194 bytes

```
def f(x):
	c=x[:1]+[0]*3
	for k in x[1:]:
		p=-(k<1)or[k,0,0,c];c[1+(c[1]!=0)]=p
		if k:c=p
		while k<all(c[2:4]):c=c[3]
	while c[3]:c=c[3]
	q=[c]
	for x in q:
		if-1!=x:x,*w,_=x;q+=w
		print(x)

```

Try it online!

**-24 bytes thanks to Jakque**
**-35 bytes thanks to ovs**

Very bad solution, but it implements the task directly and shouldn't be extremely inefficient at least. It basically deserializes iteratively by just taking each element and storing a current list maintaining `[value, left-child, right-child, parent]` (since Python handles recursive lists perfectly fine), and then re-serializes using a trivial queue method.

Commented and ungolfed version:

```
def f(x):                                            # Accept a list with null values as 0

	c = [x[0], 0, 0, 0]                          # Maintain current list [value, left child, right child, parent], starting at the root

	for k in x[1:]:                              # For each element after the first
		p = k and [k, 0, 0, c] or -1         # p is the child - if the value is null, -1, otherwise, another 4-list of the right format
		a = c[1] != 0                        # a is true if and only if the left child is already taken
		c[1] = [p, c[1]][a]                  # if the left child isn't taken, set the left child, otherwise, leave it
		c[2] = [c[2], p][a]                  # if the left child is taken, set the right child, otherwise, leave it

		if k < 1:                            # if this is a null value
			while c[3] and c[2] != 0:    # so long as both children are full
				c = c[3]             # step back up once

		else:                                # if this isn't a null value
			c = c[1 + a]                 # descend to the new child

	while c[3]:                                  # as long as this isn't the root
		c = c[3]                             # step up (this just goes to the root)

	q = [c]                                      # start a queue with just the root
	for x in q:                                  # keep going through the queue
		print(x == -1 and -1 or x[0])        # if the current value is -1, output it, otherwise, you get a 4-list, and output the value from it
		q += x != -1 and x[1:3] or []        # if the current value is -1, nothing, otherwise, add the left and right children to the queue

```

Try it online!
> 4 votes

# Answer
# JavaScript (ES10),  ~~90 80~~  78 bytes

Uses `undefined` for an absent child.

```
a=>(g=d=>(b[d]=b[d]||[]).push(x=a[p++])*x&&[++d,d].map(g))(p=0,b=[])&&b.flat()

```

Try it online!

### Commented

We recursively walk through the input array `a[]`, using the depth-first way. While doing so, we fill the array `b[]` where the values are organized by depth. At the end of the process, we just need to flatten `b[]` to get the final output.

```
a =>                  // a[] = depth-first input
( g = d =>            // g is a recursive function taking a depth d
  (b[d] = b[d] || []) //   create b[d] if it doesn't exist
  .push(              //   and push the value ...
    x = a[p++]        //   ... stored in a[] at position p; increment p afterwards
  )                   //
  * x &&              //   if this value is defined:
    [++d, d].map(g)   //     do two recursive calls to g with d + 1
)(                    // initial call to g with:
  p = 0,              //   d = p = 0
  b = []              //   b[] initialized to an empty array
)                     //
&& b.flat()           // end of call: return a flattened version of b[]

```
> 4 votes

# Answer
# Python 3, ~~126 110~~ 84 bytes

```
def f(a,d=0,L=[]):L+=[[]];L[d]+=a[:1];a.pop(0)and f(a,d+1)+f(a,d+1);return sum(L,[])

```

Try it online!

## How it works:

The main idea is to reconstruct the layers of the graph in `L`. To do that, we will be doing some recursion and store the current depth in `d`.

### Ungolfed and commented version:

```
def f(a, d=0, L=[]): # a is our array, d is the currend depth, L are the layers
    L += [[]]          # append an empty layer in L to avoid future IndexError
    L[d] += a[:1]      # add the root of our current tree in the right layer

    if a.pop(0) != 0:  # Remove the first element of our tree and check if it is a root of a sub tree
        f(a, d+1) +      # compute the first sub-tree (append the nodes to the layers and remove them)
        f(a, d+1)        # compute the second sub-tree (same)

    return sum(L,[])   # return the flatened list of the layers

```

## Note:

As the program use the variable `L` as a reference, re-use the function after its first call will not return the good result because `L` won't have been reinitialized.

edit : In my previous answer, I cared a lot about the length of the sub-trees to recurse `a` at the right indice but it is no longer the case since we discard the elements of a when we visit them. The consequence of that is that `a` is empty at the end of the function, but who cares in a golf challenge ¯\\\_(ツ)\_/¯
> 4 votes

# Answer
# Haskell, 88 bytes

```
(concat=<<).foldr(#)[]
0#a=[[0]]:a
x#(p:q:a)=([x]:p%q):a
(u:p)%(v:q)=(u++v):p%q
p%q=p++q

```

Try it online!

### also 88 bytes

```
(concat=<<).foldr(#)[]
0#a=[[0]]:a
x#(p:q:a)=([x]:zipWith(++)(p++([]<$q))(q++([]<$p))):a

```

Try it online!
> 4 votes

# Answer
# , ~~118~~ ~~114~~ 113 bytes

```
f=function(x,d=1,G=new.env()){G$g=c(G$g,d)
o=x[-1]
if(sum(o|1)&x)o=f(f(o,d+1,G),d+1,G)
`if`(d<2,x[order(G$g)],o)}

```

Try it online!

**The idea**

Traverse the array by reviving the DFS and keeping track of the visited recursion depths; then use the depths to order the array BFS-wise.

**Unrolled code and explanation:**

```
f=function(       # function args:
     x,           #  - vector x
     d=1,         #  - current recursion depth d (default=1)
     G=new.env()  #  - a passed-by-reference obj (enviroment)
     ){
  G$g=c(G$g,d)    # concat curr.depth to vector of depths
                  # (the vector is a var. inside the enviroment, initially NULL)
  o=x[-1]         # remove first element of x storing the result in o
  if(sum(o|1)&x){ # if o has elements and the first element of x > 0
    o=f(o,d+1,G)  #  recurse on left branch increasing d and updating o
    o=f(o,d+1,G)  #  recurse on right branch increasing d and updating o
  }
  if(d<2){        # if d == 1
    x[order(G$g)] #  use the stored depths to reorder x and return it
  }else{          # else
    o             #  return o
  }
}

```
> 4 votes

# Answer
# Jelly, 28 bytes

```
Ḣ;ß},ß}ɗ¥WAƑ?
J×ṠÇAœiⱮJẈż$Ụị

```

Try it online!

Uses `-1` for an absent child. This recreates a binary tree of the list indices and then sorts the original list based on the depth and position of the indices.

## Explanation

### Helper link

Takes a list of integers representing a depth-first binary tree and recursively turns it into a representation of that tree using nested lists

```
Ḣ             | Head
          AƑ? | If non-negative:
        ¥     | - Then:
 ;            |   - Concatenate to:
  ß},ß}ɗ      |   - The results of calling this link recursively using the remainder of the list, pairing the results of each call together
         W    | - Else: wrap in a list

```

### Main link

```
J              | Sequence along list
 ×Ṡ            | Multiplied by the signs of the original list
   Ç           | Call helper link
    A          | Absolute
     œiⱮJ      | Find multi-dimensional indices of each list index
         Ẉż$   | Prepend the list lengths (i.e. depth)
            Ụ  | Indices required for this sort order
             ị | Index into original list

```
> 3 votes

# Answer
# , 80 bytes

```
for(i in x<-scan()){F=c(F,T);T=T+(i>0)*T+!i;while(!T%%2+i)T=T/2};x[order(F[-1])]

```

Try it online!

Full program, takes leaf nodes as \\$0\\$. Runs through the input and keeps track of the current depth in the following way:

* Store the current value of depth accumulator `T` (preinitialized to \\$1\\$) in `F`.
* If the current node is positive, move to the next level (multiply `T` by 2).
* Otherwise increase `T` by 1. If after this addition, `T` is divisible by 2, we've already had two child nodes in this level, and need to keep backing up (divide `T` by 2) until it is no longer divisible.

In other words, we can imagine `T` as a binary number, where each bit represents a level, \\$0\\$ is its first branch, and \\$1\\$ is its second branch. Moving to a new level is equivalent to adding another zero bit, and when the number "wraps around" all trailing zeroes are removed. For example, in the demo input:

`[1, 5, #, 4, 4, #, #, 6, #, #, 3, ...]`

```
Input     Next depth
          1
1     ->  10
5     ->  100
0     ->  101
4     ->  1010
4     ->  10100
0     ->  10101
0     ->  1011
6     ->  10110
0     ->  10111
0     ->  11
3     ->  110
...

```

Finally, return x sorted in the order of `F`.
> 3 votes

# Answer
# Stax, 31 bytes

```
ü§!■YΦ─Ä↓Θ½(-²9♂^♀_¡#{Σ├j↨à,lqƒ

```

Run and debug it

null nodes are represented by `0`, and are required in the input in all places applicable.

parses the given traversal into a nested list, and then flattens it into layers. The parsing part is actually much smaller than the portion which prints the layers, somehow.

Golfed a bit with some help from recursive.

## Explanation

```
Gd{c{|4!fsn|-:f:fcwLr$J}Bsn!CGG~2l]+,
| printing             || parsing   |

Bsn!CGG~2l]+,
B               remove first element and push
 sn!C           if zero, stop recursion
    GG          do 2 recursive calls
      ~         move array to input stack
        2l]+    create a pair from the recursive calls, prepend previous iteration
            ,   retrieve array from input stack

Gd{c{|4!fsn|-:f:fcwLr$J}
G                      } run after recursive operation is over
 d                       delete empty list
  {              cw      run as long as tree isn't empty
   c{|4!f                copy, get elements at depth 0
         sn|-            remove those from the original tree
             :f:f        flatten twice
                   Lr    put all levels in a list
                     $   flatten
                      J  join with spaces

```
> 1 votes

---
Tags: code-golf, binary-tree
---


title: Encode a Lenguage

text:
# Question
Title: Encode a Lenguage
The Len(language,encoding) family of languages is a variety of Lenguage derivatives. To encode a program into a Len language, you replace every character with its representation in a certain encoding, then turn that into a giant integer.

Your challenge is to write a function or program that encodes your language into a Len language. However, you can make up your own encoding, and it only needs to encompass the subset of your language that is used in your program. **But, you must have at least two distinct bytes in your program.**

# Rules

Your program must be able to take itself as input.

You can just output a number as the length of the compiled program, to avoid memory problems.

**Your program must be reversible.**

# Scoring

Your score is the result of your program run on itself. You're trying to minimise this.

# Answer
> 7 votes
# Zsh, 40 bytes, score 0

```
grep -FqxfI $0&&od||od -An<I|tr -c 0-7 8

```

Try it online!

Encodes itself as 0, and all other programs in some horrendous octal/decimal mishmash. Takes input from a file `I`.

* `grep`: search for a string that matches
    + `F`: exactly (non-regex)
    + `x`: the whole line
    + `fI`: the pattern taken from the `f`ile `I`
    + `q`: do not print the matching string; only exit with success or failure
    + `$0`: this source code file
* `&&od`: if the match succeeds, print `0000000`
* `||`: otherwise:
    + `od -An<I`: encode the input file in octal
    + `|tr -c 0-7 8`: replace all characters except `01234567`s with `8`s (ensures it's a valid number with no leading 0s)

Doesn't support newlines (nor null bytes).

# Answer
> 8 votes
# 05AB1E, ~~7845~~ ~~535~~ 34

```
BC

```

Try it online!

This converts the input from base `2` according to 05AB1E's codepage. `B` is mapped to 11 and `C` to 12. Digits larger or equal to the base are allowed and *"overflow"* into the next digit.
This can be inverted by iterating the digits of the output in reverse:

```
[D0Q#    "loop while TOS != 0"\
2‰`      "divmod 10"\
i        "if the last digit was 1:"\
 'Bˆ5-   "append ö to global array and subtract 5 from TOS"\
ë        "else:"\
 'Cˆ6-   "append T to global array and subtrac 6 from TOS"\
]¯RJ     "after the loop: reverse global array and join"\

```

Try it online!

# Answer
> 7 votes
# Charcoal, ~~11 bytes, score 96697523013522~~ 14 bytes, score 10230313233344

```
⭆Ｓ⌕´Ｓ´⭆´⌕´´´ιι

```

Try it online! Explanation: Now uses @AviFS's approach of looking up the possible characters in a table. However, the table itself more than triples the length of the code, which leaves no room to do base conversion, so instead I just output the digits individually as base 10, but fortunately it's still slightly lower than my original score.

# Answer
> 6 votes
# , ~7.0689\*10^69

```
cat(utf8ToInt(scan(,''))-29,sep='')

```

Try it online!

Converts the input to ASCII codepoints, subtracts 29, and concatenates all the 2-digit numbers obtained. I chose 29 because the lowest ASCII codepoint I need is 39 (for `'`); this ensures that all the numbers are between 10 and 98. Reversing is thus easy: split into groups of 2 digits, add 29 and convert back to characters.

Works on any string which does not include the characters  `!"#$%&`.

A more naïve implementation would omit the `-29` and use the plain ASCII codepoints; it is easy to convince oneself that this remains reversible even with some 3-digit numbers, but it leads to a score of 9.997\*10^75.

# Answer
> 4 votes
# Dyalog APL, 2.7370885894231567 * 10^18

This is the most naive algorithm I could come up with, so I suppose it sets a baseline. Given the structure `{n⊥n|⎕UCS⍵}`, I wrote a script to check the lowest that *n* could be, and 28 is our answer.

That is, the lowest that *n* could be and still yield a unique codepoint for each symbol in the program, when it's unicode is reduced mod *n*.

The program simply takes the unicode codepoint of each symbol, mods it by 28, and then converts it to base 28. It's not very clever or optimized, I challenge you to be less lazy!

```
{28⊥28|⎕UCS⍵}

```

Try it online!

# Answer
> 3 votes
# Vyxal, 16 bytes, score 81040998233

```
`\`\\v\ḟ6\β`vḟ6β

```

Try it online!

There may be better languages to do this, but the idea is simple.

The other answers reduce the codepoints mod *n* where *n* is the smallest number that will yield unique codepoints. But that's rarely an efficient encoding. You usually end up with lots of numbers unused. Eg. your program becomes *\[6,3,9,7,2\]* rather than *\[0,1,2,3,4\]*.

This just packs every symbol used into a list, and for each symbol in the program, gets its index in the list. So you're guaranteed to get the lowest numbers you can: *\[0..n\]*. In addition, the symbols in the list are in the order they appear in the program, because we want the lower numbers to show up first. In every base, *\[0,1,2,3\]* is a much smaller number than *\[3,2,1,0\]*. Finally, I used 6 unique symbols, so I converted it to base 6.

**Example execution with `v6ḟ` as input:**

```
               # Implicit input                          -> "v6ḟ"
`\`\\v\ḟ6\β`   # This is just the string "`\vḟ6β" [1]    -> "v6ḟ", "`\vḟ6β"
vḟ             # Vectorized find index in list           -> [2,4,3]
6β             # Convert list to base 6                  -> 99
               # Implicit output

```

\[1\]: Unfortunately for this challenge, non-ASCII characters have an (really cool) encoding scheme in strings. So in order to have them interpreted literally, all the non-ASCII characters in the string are escaped, which adds many orders of magnitude to the score.

# Answer
> 3 votes
# , 176 bytes, score=0

```
'->a;b=paste0(sQuote(a),a);s=readLines(,1);`if`(s==b,cat(0),cat(utf8ToInt(s)-24,sep=""))'->a;b=paste0(sQuote(a),a);s=readLines(,1);`if`(s==b,cat(0),cat(utf8ToInt(s)-24,sep=""))

```

Try it online!

Despite the enormously increased byte-count, this is basically just an extension of Robin Ryder's approach, optimized for the challenge's scoring system instead of for `code-golf`.

We first construct a quine string of the program (`'...'->a;b=paste0(sQuote(a),a)`) in variable `b`, and then check if this is equal to the input (`s=readLines(,1);`if`(s==b,...`). If it is, we output zero (`cat(0)`): that is, we hard-code this particular progam as zero. Otherwise, we use Robin's approach to output the program's numerical value, which can never be less than `10`.

Valid programs can only use characters with ASCII values 34-123: so, no newlines, and no "`|}~`" characters. The 'empty program' is not valid for this version (it also encodes to zero), but a slight modification can fix this, while keeping a score of zero for this challenge.

# Answer
> 1 votes
# Jelly, 29 bytes, score 0 bytes

```
“Ṿ;⁾v,;⁾¥ ¤-iⱮḅL{ɗ⁼?ʋ/+1”v,¥

```

Try it online!

Returns 0 when supplied itself as an input. Otherwise looks up the supplied input in the characters `“Ṿ;⁾v,;⁾¥ ¤-iⱮḅL{ɗ⁼?ʋ/+1”v,¥`  and converts back from bijective base 29 before adding 1 (so that an empty input will result in 1 rather than being the same as the encoder itself).

Inspired by @pxeger’s Zsh answer so be sure to upvote that one too (implementation quite different though).

Decoder - Try It Online!

## Explanation

### Main link

```
“Ṿ…”v,¥  | Evaluate this string as a Jelly link with itself paired to the overall link’s argument (the program to encode)

```

### Code run within eval

```
                   ʋ/   | Reduce using the following:
Ṿ                       | - Uneval (effectively wraps the string in “”)
 ;⁾v,;⁾¥ ¤              | - Append "v,¥ " (thus restoring the source for the encoder)
                 ⁼?     | - If equal to the original argument (the program to encode):
          -             |   - Then -1
                ɗ       |   - Else:
           iⱮ           |     - Indices of each character of program to encode in the string
             ḅ          |     - Convert from base given by:
              L{        |       - The length of the string
                     +1 | Add 1

```

Note the program has a trailing space because of the need to use  within `“”` which takes a pair of characters.

---

# Jelly, 2 bytes, score 7842

```
OḄ

```

Try it online!

A monadic link that converts to Unicode code points and unbinaries. This is a similar approach as @ovs’s 05AB1E answer so be sure to upvote that one too!

The TIO link includes a decoder in the header and generates a table of the first 32 possible programs including their decimal representation and the decoded program.

---
Tags: code-challenge, encoding, open-ended-function, self-referential
---


title: Counting uniquely solvable polylinks

text:
# Question
Title: Counting uniquely solvable polylinks
Related: Counting polystrips

## Background

Link-a-Pix is a puzzle on a rectangular grid, where the objective is to reveal the hidden pixel art by the following rules:

* Connect two cells with number N with a line spanning N cells, so that the two cells are at the two ends of the line.
* The number 1 is considered connected to itself (which makes it an exception to the rule of "connect *two* cells").
* Two different lines are not allowed to overlap.
* The puzzle is solved when all the given numbers on the grid are connected by the above rules. There may be some unused cells after the puzzle is solved.

The following is an example puzzle and its unique solution.

(Source: The NP completeness of some lesser known logic puzzles, 2019)

A **polylink** is defined as a single line on a Link-a-Pix puzzle. It is identified by the collection of cells (i.e. a polyomino) the line passes through, the endpoints, and the path (i.e. a Hamiltonian path) defined by the line. It is somewhat similar to a polystrip, except that the strip can touch itself side-by-side, and the two endpoints of the strip are marked.

The following are pairwise distinct polylinks (X's are the endpoint cells and O's are the other cells on the strip). A rotation or reflection of a polylink is different from the original unless they perfectly coincide.

```
X-O   X X   X-O   O-O
  |   | |     |   | |
X O   O O   O-O   O O
| |   | |   |     | |
O-O   O-O   O-X   X X

```

Some distinct polylinks have the same underlying polyomino and endpoints, as follows. When such a link is used in a Link-a-Pix puzzle, it makes the entire puzzle have multiple solutions, which is not desirable.

```
O-O-O   O-O-O
|   |   |   |
O-X O   O X O
    |   | | |
X-O-O   X O-O

```

Therefore, let's define a **uniquely solvable** polylink as one which does not have another different polylink with the same polyomino and endpoints.

## Challenge

Given the number \\$n\\$, count the number \\$a(n)\\$ of distinct uniquely solvable polylinks with \\$n\\$ cells. Due to the definition of a polylink, \\$a(1) = 1\\$ (the single cell with only one endpoint is a valid "line" on a Link-a-Pix puzzle).

Standard rules apply. The shortest code in bytes wins.

## Test cases

The "uniquely solvable" makes the sequence deviate from A002900 from n = 9. There are exactly 10 "ambiguous" polylinks of 9 cells, all of which happen to have the shape of a 3x3 square:

```
O O O      O O O      X O O
O X O x4;  O O O x4;  O O O x2
X O O      X O X      O O X

```

Main test cases:

```
a(1) = 1
a(2) = 2 (horizontal and vertical)
a(3) = 6 (2 orientations of I, 4 for L)
a(4) = 18 (L*8, I*2, S*4, O*4, T is not a link)
a(5) = 50 (I*2, L*8, N*8, P*8*2, U*4, V*4, W*4, Z*4)
a(6) = 142
a(7) = 390
a(8) = 1086
a(9) = 2938
a(10) = 8070
a(11) = 21690
a(12) = 59022
a(13) = 158106

```

a(6) through a(13) were generated using a reference program in Python.

# Answer
# , 99 bytes

```
1#.3>[:#/.~[:(2({.,&(/:~)}.)_1(-"1<./)@|.+/\)"2(#~([:*/@~:+/\)"2)@([:,/,~"1 2/)~&((,-)=0 1)&(,:,.0)

```

Try it online!

Builds up paths starting with `0 0`, filtering the ones that cross themselves. Then it normalizes each path so that every coordinate is non-negative. To check if the path is a unique solvable polylink, the end tiles and the path tiles get sorted and the results are compared to each other. If the count is 1 (for `n=1`) or 2 (both directions are created), it's a hit.
> 5 votes

# Answer
# Python 2, ~~292~~ ~~268~~ 265 bytes

A slow golf of the reference program. \\$a(10)=8070\\$ took close to 8 minutes locally.

```
n=input()-1
G=[]
for x in-1j,1,1j,-1:
 for q in range(3**n):v=[0];w=x;exec'v+=w,;w=w+(w-v[-2])*(-1j)**(q%3+3);q/=3;'*n;G+=[{n-min(n.real for n in v)-min(n.imag for n in v)*1j:0<j<len(v)-1for j,n in enumerate(v)}][len(v)-len(set(v)):]
print map(G.count,G).count(6)/6

```

Try it online!
> 4 votes

# Answer
# Jelly, 40 bytes

```
0ị+ⱮØ.,U;N$¤ḟṭ€)Ẏ
Ø0WWÇ⁸’¤¡ṪṭṢƊ€ċⱮ`ỊSH»1

```

Try it online!

A pair of links that takes an integer and returns the value of \\$a(n)\\$. The last two bytes handle the special case of \\$n=1\\$ since that’s the the only situation where there aren’t pairs of poly links swapping start and end. Handles up to \\$n=10\\$ in the time limit on TIO but times out for higher values.

## Explanation

### Helper link

Takes a list of lists of coordinates and extends it by moving each final coordinate up, down, left and right, filtering out any intersections with the existing list

```
               )  | For each list of coordinates:
0ị                | - Last member (i.e. most recently visited coordinate)
  +Ɱ       ¤      | - Add each of the results of the following:
    Ø.            |   - [0, 1]
      ,U          |   - Paired with its reverse [0,1],[1,0]
        ;N$       |   - Concatenated to its negative [0,1],[1,0],[0,-1],[-1,0]
            ḟ     | - Filter out those already in the list
             ṭ€   | - Tag each onto the end of a new copy of the list
                Ẏ | Join all outer lists together

```

### Main link

Takes an integer argument n and returns the value of a(n)

```
Ø0                      | [0,0]
  W                     | Wrapped in a list [[0,0]]
   W                    | Wrapped in a list [[[0,0]]]
    Ç⁸’¤¡               | Call the helper link n-1 times
            Ɗ€          | For each of the lists of coordinates:
         Ṫ              | - Tail
          ṭṢ            | - Tagged onto sorted list of the rest
              ċⱮ`       | Count the number of times each list appears
                 Ị      | <= 1
                  S     | Sum
                   H    | Half
                    »1  | Max of this and 1

```
> 1 votes

---
Tags: code-golf, combinatorics, grid, puzzle-solver, polyomino
---


title: Drop some boxes

text:
# Question
Title: Drop some boxes
Say I have a pile of boxes:

```
AAA
BBB

```

I can create it in two steps:

```
BBB
 ↓
(empty)
---
AAA
 ↓
BBB

```

But with this:

```
AB
BA

```

I need three steps:

```
 A
 ↓
(empty pile)
---
BB
 ↓
 A
---
A
↓
 B
BA

```

# Your challenge

Given a pile of boxes, output the minimum number of steps needed to create that pile.

A step consists of dropping a row of boxes of the same type onto the current pile.

For example, `AAA` can be dropped as a step, so can `A A`, but `A B` and

```
 A
AAA

```

can't.

Input can be as a matrix, text, whatever. The input will always be a solid block - nothing like

```
BB
AAA

```

Will ever be inputted, so you don't have to parse spaces / empty values.

# Scoring

This is , shortest wins!

# Testcases

```
AB
BA
=> 3

A
B
C
D
E
=> 5

AAA
AAA
AAA
=> 3

ABCAB
DEACB
=> 7

POTATOS
DOBEYUM
=> 12

```

# Answer
# Pyth, 22 bytes

```
L&lbhSmhyfT>RqhkhdbbyC

```

Try it online! Or run all test cases at once.

This is basically ovs's Python solution translated verbatim to Pyth (it seems that their solution's exact algorithm is also shortest in Pyth), so I'm posting it as community wiki. Doesn't time out thanks to Pyth's memoization.
> 9 votes

# Answer
# Python 2, ~~103~~ 91 bytes

-12 bytes thanks to PurkkaKoodari!

```
lambda s:f(zip(*s))
f=lambda s:len(s)and-~min(f({r[r[0]==x[0]:]for r in s}-{()})for x in s)

```

Try it online! The last testcase times out.

The first function just transposes the input, if we can take input as a list of columns it can be omitted.
> 9 votes

# Answer
# Charcoal, 57 bytes

```
ＷＳ⊞υι≔⟦Ｅθ⮌⭆υ§λκ⟧η≔⁰ζＷ⌊η«≦⊕ζ≔ηθ≔⟦⟧ηＦθＦκ⊞ηΦＥκΦμ∨π¬⁼ξ§λ⁰μ»Ｉζ

```

Try it online! Link is to verbose version of code. Uses brute force so too slow for the last test case on TIO. Explanation:

```
ＷＳ⊞υι

```

Input the pile.

```
≔⟦Ｅθ⮌⭆υ§λκ⟧η

```

Rotate the pile by 90° and put it into a list.

```
≔⁰ζ

```

Start counting the number of steps.

```
Ｗ⌊η«

```

Repeat until there is at least one empty pile.

```
≦⊕ζ

```

Increment the number of steps.

```
≔ηθ≔⟦⟧ηＦθ

```

Make a copy of the list of piles so that it can be looped over while starting a new list of piles.

```
Ｆκ

```

Loop over each column of the pile.

```
⊞ηΦＥκΦμ∨π¬⁼ξ§λ⁰μ

```

Remove the letter at the bottom of that column from all of the columns that have it as its bottom letter and push any remaining non-empty columns to the list.

```
»Ｉζ

```

Print the number of steps needed.
> 8 votes

# Answer
# Brachylog, 31 bytes

```
∧≜.&z{{⟨k≡t⟩|;X}ᵐRtᵛ∧Rhᵐ}ⁱ↖.zĖ∧

```

Try it online!

It's a *bit* less efficient than even the other two answers so far (it does the classic recompute everything if it hasn't reached the end in as many steps as it's trying), so I might just delete this when I wake up if it still hasn't spit something out for the second-to-last test case.
> 5 votes

# Answer
# Jelly, 24 bytes

```
ZWṖ€ṛ¦Ɱ0ịⱮĠƊ$€Ẏ$Ẹ€Ạ$Ð¿L’

```

Try it online!

A monadic link taking a list of Jelly strings (a list of lists of characters) and returning an integer.

## Explanation

```
Z                        | Transpose
 W                       | Wrap in a list
                   $Ð¿   | While the following is true:
                Ẹ€       | - Any list is non-empty for each list of lists
                  Ạ      | - All
               $         | Do the following, collecting up intermediate results
            $€           | - For each list:
  Ṗ€ṛ¦Ɱ    Ɗ             |   - Remove the last character of the lists for each of the groups of indices determined by the following:
       0ịⱮ               |     - Last character of each list
          Ġ              |     - Group indices of identical characters
               Ẏ         | - Tighten (join outermost lists together)
                      L  | Length
                       ’ | Subtract 1

```

All cases (uses `Q` for 1 extra byte to make it more efficient, but would complete eventually without it)
> 4 votes

# Answer
# , 55 bytes

```
(1+[:<./$:"1)@((]}.~1{.=)&.>"0/~' '-.~{.&>)`0:@.(''-:;)

```

Try it online!

Brute force recursion taking away boxes until none are left, and returning the minimum number of steps.
> 1 votes

# Answer
# Ruby, 73 bytes

```
->l{l.permutation.map{|x|x*=?_;1while x.sub!(/(.*)_\1/,'\1');x.size}.min}

```

Try it online!

Assuming I can accept a list of columns in input

# Ruby, 108 bytes

```
->l{l.map(&:chars).transpose.map(&:join).permutation.map{|x|x*=?_;1while x.sub!(/(.*)_\1/,'\1');x.size}.min}

```

Try it online!

Otherwise
> 1 votes

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