title: Join up the rooms

text:
# Question
Title: Join up the rooms
So, here's a map of, let's say, a dungeon...

```
##########
#    #####
#    #####
##########
##########
##########
##########
####    ##
####    ##
##########

```

Let's say that the hero is in Room A (at the top left) and their goal (a prince in distress?) is in Room B (to the bottom right). Our map does not allow the hero to progress to their goal.

We need to add a passageway...

```
##########
#    #####
#    #####
####.#####
####.#####
####.#####
####.#####
####    ##
####    ##
##########

```

There, much better!

---

## Rules

* A program or function which accepts a dungeon map (made up of hashes and spaces, with rows separated by new line characters).
* It will output a map with dots added to denote passages in all spaces which are on a direct path between the space characters.
* It will not change the line length, or number of lines.
* Passages are all in a direct line from spaces to spaces.
    + Passages can not turn around corners
    + They will not be between spaces and the edge of the map.
* Use any language.
* Attempt to perform the conversion in the fewest bytes.
* If no passageways can be drawn, return the map, unchanged.
* The map should always have hashes around all edges (You do not need to handle spaces at the edge).
* Input maps are always rectangular, each row should be the same width.

## Test cases

```
####       ####
#  #   =>  #  #
#  #       #  #
####       ####

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ####.#####
##########    =>  ####.#####
##########        ####.#####
##########        ####.#####
####    ##        ####    ##
####    ##        ####    ##
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ##########
##########    =>  ##########
##########        ##########
##########        ##########
######  ##        ######  ##
######  ##        ######  ##
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ####.#####
##########    =>  ####.#####
####   ###        ####   ###
##########        ######.###
######  ##        ######  ##
######  ##        ######  ##
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        ##..######
##########    =>  ##..######
##########        ##..######
##########        ##..######
## #######        ## .######
##  ######        ##  ######
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        #.########
##########    =>  #.########
##########        #.########
#######  #        #.#####  #
#######  #        #.#####  #
# #####  #        # .....  #
##########        ##########

##########        ##########
#    #####        #    #####
#    #####        #    #####
##########        #.########
#####  ###    =>  #.###  ###
#####  ###        #.###  ###
#######  #        #.#####  #
#######  #        #.#####  #
# #####  #        # .....  #
##########        ##########

##########        ##########
##       #        ##       #
##########        ##......##
##########        ##......##
##########    =>  ##......##
##########        ##......##
##########        ##......##
##########        ##......##
#       ##        #       ##
##########        ##########

##########        ##########
####  ####        ####  ####
####### ##        ####..# ##
###### ###        ####.. ###
# ### ## #    =>  # ... .. #
# ## ### #        # .. ... #
### ######        ### ..####
## #######        ## #..####
####  ####        ####  ####
##########        ##########

```

# Answer
> 7 votes
# Jelly, 17 bytes

```
ỴḲaLḊṖƊ¦”.KƊ€Z$⁺Y

```

Try it online!

Tricky -1 thanks to user202729.

Explanation:

```
ỴḲaLḊṖƊ¦”.KƊ€Z$⁺Y Arguments: S
Ỵ                 Split S on newlines
 ḲaLḊṖƊ¦”.KƊ€Z$   Monadic link
 ḲaLḊṖƊ¦”.KƊ€      Map over left argument
 ḲaLḊṖƊ¦”.KƊ        Monadic link
 Ḳ                   Split on spaces
  aLḊṖƊ¦”.           Dyadic link with right argument '.'
  aLḊṖƊ¦              Apply at specific indices
  a                    Logical AND (vectorizes)
   LḊṖƊ                Monadic link
   L                    Length
    Ḋ                   Range [2..n]
     Ṗ                  Remove last element
          K          Join with spaces
             Z     Zip
               ⁺  Previous link
                Y Join with newlines

```

# Answer
> 5 votes
# Perl 5 `-p0`, 56 bytes

```
#!/usr/bin/perl -p0
/
/;$n="(.{@+})*";s%#%/ #*\G#+ |(?= )$n\G$n /s?".":$&%eg

```

Try it online!

# Answer
> 3 votes
# APL+WIN, 87 bytes

Prompts for character matrix:

```
n←(' '=m←⎕)⋄c←(∨⍀n)+⊖∨⍀⊖n⋄r←(∨\n)+⌽∨\⌽n⋄((,c>1)/,m)←'.'⋄((,r>1)/,m)←'.'⋄((,n)/,m)←' '⋄m

```

# Answer
> 3 votes
## **Haskell, 209 165 162 bytes.**

```
import Data.List
t=transpose
k=concat
j a=(foldr1 max<$>)<$>t<$>t[a,f<$>a,t$f<$>t a]
f b|(e:g:d@(h:_:_))<-group b=k[f$e++g,'.'<$h,drop(length h)$f$k d]|1>0=' '<$b

```

Try it online!

Not the most efficient way of doing it in Haskell I'm sure. It's got too many parentheses for my liking but I'm not sure how to remove any more.

# Answer
> 2 votes
# Python 2, ~~173~~ 148 bytes

```
m=input().split('\n')
exec"m=zip(*[[c*(c!='#')or'#.'[(' 'in r[i:])*(' 'in r[:i])]for i,c in enumerate(r)]for r in m]);"*2
for r in m:print''.join(r)

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 95 bytes

```
+`(?<=(.)*)#(?=.*¶(?>(?<-1>.)*)[ .])
.
+`\.(?=(.)*)(?<![ .](?>(?<-1>.)*)¶.*)
#
 (\S+)
 $.1$*.

```

Try it online! Explanation:

```
+`(?<=(.)*)#(?=.*¶(?>(?<-1>.)*)[ .])
.

```

This looks for `#` signs that are above spaces or `.`s and turns them into dots until there are none left. The lookbehind finds the `#`'s column and then the lookahead skips to the next line and atomically to the same column below so that the space or `.` can only match if it's exactly below the `#`.

```
+`\.(?=(.)*)(?<![ .](?>(?<-1>.)*)¶.*)
#

```

This looks for `.`s that are not below spaces or `.`s and turns them back into `#`s until there are none left. The lookahead finds the `.`'s column and then the lookbehind skips to the previous line and atomically to the same column above in much the same way so that the space or `.` can only match if it's exactly above the `#`. A negative lookbehind is used so that this also works for `.`s in the top row.

```
 (\S+)
 $.1$*.

```

(Note trailing space on both lines) This simply looks for all runs of non-whitespace characters between spaces and ensures that they are all `.`s.

# Answer
> 1 votes
# Ruby, 104 bytes

```
->s{2.times{s=((0...s=~/\n/).map{|i|s.lines.map{|b|b[i]}*""}*"\n").gsub(/ [#.]+(?= )/){$&.tr(?#,?.)}};s}

```

Try it online!

Well, it's not great, but at least it's convoluted. I'm sure it can be improved.

# Answer
> 1 votes
# JavaScript (Node.js),205 193 190 186 181 175 172 bytes

```
r=>r.split`
`.map(x=>[...x]).map((R,y,r)=>R.map((c,x)=>{for(D=2;c<"#"&&D--;){for(;(T=(r[y+=D]||0)[x+=!D])>" ";);for(;r[y-=D][x-=!D]>c;)T?r[y][x]=".":0}})&&R.join``).join`
`

```

Try it online!

### Commented

```
f=r=>r.split`
` ->                                     //getting as string with lines
.map(x=>[...x])                          //to 2d string array
  .map((R,y,r)=>                         //r - the new 2d string array
    R.map((c,x)=>{                       //
      for(D=2;c<"#"&&D--;)              //instead of using if joining c==" " with the loop,D=1/0
        {for(;                           //
         (T=(r[y+=D]||0)[x+=!D])>" ";);  //0[num] = undefined. checking for a path - consisting of # or .(or not consisting of space or undefined), we dont need temp (X,Y) because in the next loop we will return to our original position regardless of the correctness of the path
           for(;T&&r[y-=D][x-=!D]>c;)    //again instead of if(T) combine with loop. if T is not undefined it will be a space because the array can return .#(space). and we then go back to the source(x,y)
                                         //remeber that c==" "
             r[y][x]="."                 //and just putting . where weve been
     }})&&R.join``                       //instead of return r as string at the end , we know that we cant change a row at a smaller index(due to D-0/1) so we can return R.join`` already
    ).join`
`

```

# Answer
> 1 votes
# Stax, 19 bytes

```
╛XA╟φkôα`æbπ┐w↨╙j≥☺

```

Run and debug it

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


title: Arithmetic Cycle

text:
# Question
Title: Arithmetic Cycle
### Input:

Integer `n` which is `>=0` or `>=1` (`f(0)` is optional)

### Output:

The `n`'th number in the sequence below, OR the sequence up to and including the `n`'th number.

### Sequence:

```
(0),1,-1,-3,0,5,-1,-7,0,9,-1,-11,0,13,-1,-15,0,17,-1,-19,0,21,-1,-23,0,25,-1,-27,0,29,-1,-31,0,33,-1,-35,0,37,-1,-39,0,41,-1,-43,0,45,-1,-47,0,49,-1,-51,0,53,-1,-55,0,57,-1,-59,0,61,-1,-63,0,65,-1,-67,0,69,-1,-71,0,73,-1,-75,0,77,-1,-79,0,81,-1,-83,0,85,-1,-87,0,89,-1,-91,0,93,-1,-95,0,97,-1,-99

```

How is this sequence build?

`f(n=0) = 0` (optional)
`f(n=1) = f(0) + n` or `f(n=1) = 1`
`f(n=2) = f(1) - n`
`f(n=3) = f(2) * n`
`f(n=4) = f(3) / n`
`f(n=5) = f(4) + n`
etc.

Or in pseudo-code:

```
function f(integer n){
  Integer result = 0
  Integer i = 1
  Loop as long as i is smaller than or equal to n
  {
    if i modulo-4 is 1:
      result = result plus i
    if i modulo-4 is 2 instead:
      result = result minus i
    if i modulo-4 is 3 instead:
      result = result multiplied with i
    if i modulo-4 is 0 instead:
      result = result integer/floor-divided with i
    i = i plus 1
  }
  return result
}

```

But as you may have noted there are two patterns in the sequence:

```
0, ,-1,  ,0, ,-1,  ,0, ,-1,   ,0,  ,-1,   ,0,  ,-1,   ,...
 ,1,  ,-3, ,5,  ,-7, ,9,  ,-11, ,13,  ,-15, ,17,  ,-19,...

```

so any other approaches resulting in the same sequence are of course completely fine as well.

## Challenge rules:

* 0-indexed and 1-indexed inputs will result in the same result (which is why the `f(0)` is optional for 0-indexed inputs if you want to include it).
* You are allowed to output the `n`'th number of this sequence. Or the entire sequence up and including the `n`'th number. (So `f(5)` can result in either `5` or `0,1,-1,-3,0,5`.)
    + If you choose to output the sequence up to and including the `n`'th number, output format is flexible. Can be a list/array, comma/space/new-line delimited string or printed to STDOUT, etc.
* The divide (`/`) is integer/floor division, which rounds towards 0 (not towards negative infinity as is the case in some languages).

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

## Additional test cases above `n=100`:

```
Input     Output

1000      0
100000    0
123       -123
1234      -1
12345     12345
123456    0

```

# Answer
# JavaScript (ES6), 19 bytes

```
n=>[0,n,-1,-n][n&3]

```

Try it online!

### Proof

Let's assume that we have the following relations for some **n** multiple of 4. These relations are trivially verified for the first terms of the sequence.

```
f(n)   = 0
f(n+1) = n+1
f(n+2) = -1
f(n+3) = -(n+3)

```

And let **N = n + 4**. Then, by definition:

```
f(N)   = f(n+4) = f(n+3) // (n+4) = -(n+3) // (n+4) = 0
f(N+1) = f(n+5) = f(n+4) + (n+5)  = 0 + (n+5)       = N+1
f(N+2) = f(n+6) = f(n+5) - (n+6)  = (n+5) - (n+6)   = -1
f(N+3) = f(n+7) = f(n+6) * (n+7)  = -1 * (n+7)      = -(N+3)

```

Which, by mathematical induction, proves that the relations hold for any **N** multiple of **4**.
> 19 votes

# Answer
# 05AB1E, 8 bytes

Outputs the `nth` number

```
ÎD(®s)sè

```

Try it online!

# 05AB1E, 14 bytes

Outputs a list of numbers upto N using the patterns in the sequence

```
ÅÉāÉ·<*āÉ<‚øí˜

```

Try it online!

**Explanation**

Example using N=7

```
ÅÉ               # List of odd numbers upto N
                 # STACK: [1,3,5,7]
  ā              # Enumerate 1-based
   É             # is odd?
                 # STACK: [1,3,5,7],[1,0,1,0]
    ·<           # double and decrement
                 # STACK: [1,3,5,7],[1,-1,1,-1]
      *          # multiply
                 # STACK: [1,-3,5,-7]
       āÉ<       # enumerate, isOdd, decrement
                 # STACK: [1,-3,5,-7],[0,-1,0,-1]
          ‚ø     # zip
                 # STACK: [[1, 0], [-3, -1], [5, 0], [-7, -1]]
            í    # reverse each
             ˜   # flatten
                 # RESULT: [0, 1, -1, -3, 0, 5, -1, -7]

```
> 4 votes

# Answer
# Python 2, 25 bytes

Port of Arnauld's answer:

```
lambda n:[0,n,-1,-n][n%4]

```

Try it online!

---

Naive solutions:

# Python 3, ~~50~~ 49 bytes

```
lambda n:n and eval('int(f(n-1)%sn)'%'/+-*'[n%4])

```

Try it online!

---

# Python 2, ~~78~~ ~~77~~ ~~76~~ ~~58~~ ~~57~~ ~~53~~ 52 bytes

```
lambda n:n and eval('int(1.*f(n-1)%sn)'%'/+-*'[n%4])

```

Try it online!

Used a bunch of bytes on `int`, because python floor divides, and not towards `0`, as in the question.
> 4 votes

# Answer
# , 12 bytes

Port of Arnauld's answer:

```
4&|{0,],_1,-

```

Try it online!

# , 28 bytes

Naive solution:

```
{(0 _1$~]),@,.(_1^i.)*1+2*i.

```

Outputs the nth number

Try it online!
> 3 votes

# Answer
# TIS `-n` `2` `1`, 123 bytes

Outputs the `n`th number for `0 <= n <= 999`. (The upper limit is due to language limitations).

```
@0
MOV UP ACC
MOV ACC ANY
L:SUB 4
JGZ L
JEZ L
ADD 5
JRO -5
@1
MOV UP ACC
JRO UP
SUB ACC
JRO 3
MOV 1 ACC
NEG
MOV ACC ANY
HCF

```

Try it online!

---

# TIS `-n` `2` `1`, 124 bytes

Outputs the `n`th number for `0 <= n <= 999`. (The upper limit is due to language limitations). Multiple `n` may be provided, separated by whitespace.

```
@0
MOV UP ACC
MOV ACC ANY
L:SUB 4
JGZ L
JEZ L
ADD 5
MOV ACC ANY
@1
MOV UP ACC
JRO UP
SUB ACC
JRO 3
MOV 1 ACC
NEG
MOV ACC ANY

```

Try it online!

---

# TIS `-n` `3` `1`, 192 bytes

Outputs the values for `0..n` for `0 <= n <= 999`. (The upper limit is due to language limitations).

```
@0
MOV UP ACC
ADD 1
MOV ACC ANY
JRO -1
@1
SUB UP
JLZ C
HCF
C:ADD UP
MOV ACC ANY
ADD 1
SWP
ADD 1
MOV ACC ANY
SUB 4
JEZ W
ADD 4
W:SWP
@2
MOV UP ACC
JRO UP
SUB ACC
JRO 3
MOV 1 ACC
NEG
MOV ACC ANY

```

Try it online!

---

All use numeric I/O (the `-n` flag). The first two solutions use two compute nodes, one positioned above the other. The third has a stack of three nodes.

For the first two solutions, the upper node reads input, sends the original number on, then repeatedly subtracts 4 until we go negative, then adds 5 to index for our jump table. This is equivalent to `(n % 4) + 1`.

The third solution split this task across two nodes; the top one just repeats the limit until the end of time, and the middle node counts up in parallel the index (compared against that limit) and the modulo like above.

The lower node of all three solutions is the same; it has a jump table, and this is where the magic happens. We store the original number in `ACC`, then `JRO` (probably **J**ump **R**elative **O**ffset) forward by `1`, `2`, `3`, or `4`, depending on what the node above says.

Working backward:

* `4` will *a*) `NEG`ate `ACC`, and *b*) move `ACC` down for output.
* `3` will put `1` into `ACC`, then perform steps `4`*a* and `4`*b*.
* `2` will jump directly to step `4`*b*.
* `1` will `SUB`tract `ACC` off itself (effectively zeroing `ACC`), then do step `2`, which jumps to `4`*b*.
> 3 votes

# Answer
# C (gcc), 62 bytes

```
f(n,k){k=~-n;n=n?n%4?k%4?n-2&3?f(k)*n:f(k)-n:f(k)+n:f(k)/n:0;}

```

Try it online!
> 2 votes

# Answer
# Jelly, 8 bytes

```
,-;N;0⁸ị

```

Try it online!

-1 thanks to Lynn.

What others are doing (port of Arnauld's solution), supports `0`.

# Jelly, 17 bytes

```
A:A}××Ṡ¥
R_×ç+4ƭ/

```

Try it online!

`0` is not supported.
> 1 votes

# Answer
# Java (JDK 10), 25 bytes

```
n->n%2>0?n*(2-n%4):n%4/-2

```

Try it online!

Shorter than the contender algorithm in other languages with 28 bytes

```
n->new int[]{0,n,-1,-n}[n%4]

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Classic), 22 12 bytes

Massive 10 bytes saved due to Erik the Outgolfer's remarks. Thank you!

```
4∘|⊃0,⊢,¯1,-

```

Try it online!

Outputs the nth number

I don't know APL, I just tried to make my J port of Arnauld's solution work in Dyalog APL.
> 1 votes

# Answer
# Retina, 46 bytes

```
.+
*
r`(____)*$
_$.=
____
-
___.*
-1
__

_.*
0

```

Try it online! Explanation:

```
.+
*

```

Convert to unary.

```
r`(____)*$
_$.=

```

Convert back to decimal, but leave `n%4+1` underlines.

```
____
-

```

In the case that that's 4, then the result is `-n`.

```
___.*
-1

```

Case 3: `-1`

```
__

```

Case 2: `n`

```
_.*
0

```

Case 1: `0`
> 1 votes

# Answer
# Haskell, 50 bytes

```
f 0=0
f n=([(+),(-),(*),quot]!!mod(n-1)4)(f(n-1))n

```

Try it online!

Arnauld's solution, ported to Haskell is 23 bytes:

```
z n=cycle[0,n,-1,-n]!!n

```
> 1 votes

# Answer
# Cubix, ~~20~~ 19 bytes

```
Iun:^>s1ns:u@Ota3s0

```

Try it online!

Ports the same approach to cubix.

On a cube:

```
    I u
    n :
^ > s 1 n s : u
@ O t a 3 s 0 .
    . .
    . .

```

The first bit `^Iu:n>s1ns:u0s` builds the stack and then `3at` copies the appropriate item to TOS, then `O` outputs and `@` ends the program.
> 1 votes

# Answer
# Whitespace, ~~84~~ 83 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][T   T   S _Store][S S S T   S N
_Push_2][S S T  T   N
_Push_-1][T T   S _Store][S S S T   N
_Push_1][S N
S _Duplicate_1][T   N
T   T   _Read_STDIN_as_integer][S S S T T   N
_Push_3][S S S T    N
_Push_1][T  T   T   ][S S T T   N
_Push_-1][T S S N
_Multiply][T    T   S _Store][T T   T   _Retrieve_input][S S S T    S S N
_Push_4][T  S T T   _Modulo][T  T   T   _Retrieve_result][T N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Port of *@Arnauld*'s JavaScript answer.

**Explanation (example input `n=7`):**

```
Command   Explanation         Stack        Heap                  STDIN   STDOUT   STDERR

SSSN      Push 0              [0]
SNS       Duplicate top (0)   [0,0]
TTS       Store               []           {0:0}
SSSTSN    Push 2              [2]          {0:0}
SSTTN     Push -1             [2,-1]       {0:0}
TTS       Store               []           {0:0,2:-1}
SSSTN     Push 1              [1]          {0:0,2:-1}
SNS       Duplicate top (1)   [1,1]        {0:0,2:-1}
TNTT      Read STDIN as nr    [1]          {0:0,1:7,2:-1}        7
SSSTTN    Push 3              [1,3]        {0:0,1:7,2:-1}
SSSTN     Push 1              [1,3,1]      {0:0,1:7,2:-1}
TTT       Retrieve input      [1,3,7]      {0:0,1:7,2:-1}
SSTTN     Push -1             [1,3,7,-1]   {0:0,1:7,2:-1}
TSSN      Multiply (-1*7)     [1,3,-7]     {0:0,1:7,2:-1}
TTS       Store               [1]          {0:0,1:7,2:-1,3:-7}
TTT       Retrieve input      [7]          {0:0,1:7,2:-1,3:-7}
SSSTSSN   Push 4              [7,4]        {0:0,1:7,2:-1,3:-7}
TSST      Modulo (7%4)        [3]          {0:0,1:7,2:-1,3:-7}
TTT       Retrieve            [-7]         {0:0,1:7,2:-1,3:-7}
TNST      Print as integer    []           {0:0,1:7,2:-1,3:-7}           -7
                                                                                error

```

Stops with error: Exit not defined.
> 0 votes

---
Tags: code-golf, number, sequence, arithmetic, integer
---


title: Falcon Heavy stages

text:
# Question
Title: Falcon Heavy stages
Choose a set of four bytes without replacement (i.e. no byte repeated), and not necessarily in any particular order, from any one of the following four sets:

1. The characters of any one single-byte encoding
2. The Unicode characters in the range 00–FF
3. The signed decimal integers in the range −128–127
4. The unsigned decimal integers in the range 0–255

The four values you chose (please state which they are) will be the valid inputs. You must pair each value with one of the below ASCII artworks.

Given (by any means) one of your four valid inputs, respond (by any means, even list of strings) with the corresponding ASCII art. Extra white-space is allowed on all sides, as long as the image is in there in one contiguous 2D area.

First byte:

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

```

Second byte:

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

```

Third byte:

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

```

Fourth byte:

```
 db
_/\_
\__/
|  |
|  |
|  |
|__|
 /\

```

> What's new about this ASCII art Kolmogorov complexity challenge?
>
> 1. The ability to select valid inputs presents a new aspect to the challenge. The inputs are clearly too limited to encode the entire result, but can carry enough information to merit attention.
> 2. The multiple possible outputs share a lot of structure, so reuse of code or sub-images is feasible both within each image and between images.
> 3. There is enough duplication that even languages which are not well-geared towards challenges like this have a fair chance of being able to use clever code rather than just hard-coding strings extensively.

# Answer
> 41 votes
# JavaScript (ES6), 247 bytes

RegPack'ed. Expects 0...3 as input.

```
n=>[...'BigFu!#?%$Rocket'].reduce((s,c)=>(x=s.split(c)).join(x.pop()),`oF#$!
FRFRFRF|??|$i$t$t$t$t%# t #
!t!BBB
uuceeeeeee%c%|?|
o#, db
_#_
iggg
|?|%#g|o|e%t%t%tkgttgttcu,o#%!
RRR|??|%ieF R|oo|
$
oo%
 ?__#/\\!/o\\uAAAAFo g
ti\\?/Bkkk`).split`,`[n]

```

Try it online!

# Answer
> 13 votes
# Charcoal, 67 bytes

```
ＮθＦ⁼³θ«ＰAA↑↑¹⁸↗²‖ＭＭ⁴±χ»¿θ«↙²↓⁴Ｍ↗__¶\_¶»↓d/_¶ _\↓×⁴∨›²θ⁶¿‹¹θAA↑¶/_‖Ｍ

```

Try it online! Link is to verbose version of code. Takes input as a number 3-0. Explanation:

```
Ｎθ

```

Input the number.

```
Ｆ⁼³θ«ＰAA↑↑¹⁸↗²‖ＭＭ⁴±χ»

```

If it is 3, draw half the booster, then mirror it, then move to the tip of the rocket.

```
¿θ«↙²↓⁴Ｍ↗__¶\_¶»

```

If it is not 0, draw the left half of the front fuel tank.

```
↓d/_¶ _\

```

But if it is 3, draw left half of the nose cone.

```
↓×⁴∨›²θ⁶

```

Draw the left side of the rocket.

```
¿‹¹θAA↑¶/_‖Ｍ

```

Draw the appropriate base of the rocket and then mirror to finish.

# Answer
> 7 votes
# Clean, ~~292~~ ~~278~~ ~~273~~ ~~271~~ ~~262~~ 261 bytes

*-5 bytes thanks to Adám*

```
import StdEnv,Text
e=[k,k,k,"|__|",m]
l=repeatn
o="\\__/"
n="/  \\"
m="/\\"
u="|    |"
s="AAAA"
k="|  |"
?z=[m,n,u,u,u,"|____|",o:z]

```

#

```
\i=[cjustify 12[c\\c<-:q]\\q<-[?[k,k,k,k,m+" "+k+" "+m,n+k+n,k+k+k:l 18(k+k+k)]++[s+s+s],?(l 24k++[s]),?e,["db","_/\\_",o:e]]!!i]

```

Try it online!

A lambda function, mapping the `Int` values `0..3` to the images in the order listed in the OP.

# Answer
> 5 votes
# Ruby, ~~234~~ ~~212~~ 205 bytes

```
->n{y=*"| "
h=%w{/ /\ }+["|  "]*3+%w{|__ \\_}+y*3
t=%w{|_ /}
[h+["| ","/\\ | ","/  \\| ",*["|  || "]*18,?A*6],h+y*21<<?A*2,h+t,%w{d _/ \\_}+y*3+t][n].map{|a|a.rjust(6," ")+a.reverse.tr("\\\\/d","/\\\\b")}}

```

Try it online!

Takes an integer 0-3. Builds an array of the left halves of each phase, indexes in, then pads and reflects each row. All padding is to the same width, so the latter phases have leading whitespace. Returns an array of strings.

-2 bytes: Declare `y` as an array right away instead of needing `*[y]` later.

-5 bytes: Replace `x="\\"` with `t=%w{_| \\}`.

-5 bytes: Less dereferencing, more array addition.

-1 bytes: `h+y*21+[?A*2]` -\> `h+y*21<<?A*2` in phase 1.

-3 bytes: The spec allows the omission of `*$/` to join the result.

-4 bytes: `["b","\\_","_/"]` -\> `%w{b \\_ _/}` in phase 3.

-2 bytes: Use `%w` notation in the head array also.

-7 bytes: Use `rjust` instead of manual padding (this also means generating the left side and mirroring it, instead of starting with the right side)

Ungolfed:

```
->n{
  y=*"| "                                            # Same as y=[" |"]
  h=%w{/ /\ }+["|  "]*3+%w{|__ \\_}+y*3              # Head for phases 0-2
  t=%w{|_ /}                                         # Tail for phases 2,3
  [
    h+["| ","/\\ | ","/  \\| ",*["|  || "]*18,?A*6], # Phase 0
    h+y*21<<?A*2,                                    # Phase 1
    h+t,                                             # Phase 2
    %w{d _/ \\_}+y*3+t                               # Phase 3
  ][n].map{|a|                                       # Choose phase
    a.rjust(6," ") +                                 # Pad left to width 6
    a.reverse.tr("\\\\/d","/\\\\b")                  # Add mirror (right side)
  }
}

```

# Answer
> 5 votes
# Python 2, ~~292~~ ~~290~~ ~~284~~ ~~282~~ 281 bytes

```
i,j,d,e,x,y=input()," "," /\\ ","/  \\","|  |","\__/"
f=i<1
l,m,n,p,q,s=3*f*j,j*(i<3),d*f,e*f,x*f,j*(i>0)
print"\n".join(([l+j+d,l+j+e]+[l+"|    |"]*3+[l+"|____|",l+j+y],[" db\n_/\_",y])[i>2]+([l+j+x]*4+[n+s+x+n,p+s+x+p]+[q+s+x+q]*18+[s+"A"*(4,12)[f]],[m+x]*3+[m+"|__|",m+d])[i>1])

```

Try it online!

Takes an integer 0 to 3 as input and uses list indexing (1 or 0) to build each output.

-2 for an unneeded pair of brackets.

-6 by removing a variable assignment that was only used once.

-2 for another single use variable.

-1 with a tip from @Rod

# Answer
> 2 votes
# Red, 333 bytes

```
f: func[g][t:{    }b:{ /\ }c:{/  \}d:{   |}e:{|}j:{\__/}k:{|  |}a:{AAAA}h:[1[t b]1[t c]3[d t e]1[d{____}e]1[t j]]z:[3[t k]1[t{|__|}]1[t b]]r: func[w][foreach[i v]w[loop i[print rejoin v]]]switch g[1 do[r h r[4[t k]1[b k b]1[c k c]18[k k k]]r[1[a a a]]]2 do[r h r[24[t k]]r[1[t a]]]3 do[r h r z]4 do[r[1[t{ db}]1[t{_/\_}]1[t j]]r z]]]

```

Try it online!

Takes 1 - 4 as input

```
f: func [ g ] [
    t: {    }
    b: { /\ }
    c: {/  \}
    d: {   |}
    e: {|}
    j: {\__/}
    k: {|  |}
    a: {AAAA}
    h: [1 [t b] 1 [t c] 3 [d t e] 1 [d {____} e ] 1 [t j]]
    z: [3 [t k] 1 [t {|__|}] 1 [t b]]
    r: func [ w ] [
        foreach [ i v ] w [
            loop i [print rejoin v]]]
    switch g [
        1 do [r h r [4 [t k] 1 [b k b] 1 [c k c] 18 [k k k]] r [1 [a a a]]]
        2 do [r h r [24 [t k]] r [1 [t a]]]
        3 do [r h r z]
        4 do [r [ 1 [t { db}] 1 [t {_/\_}] 1 [t j] ] r z]
    ]
]

```

## Rebol, 258 bytes

I made an experiment with Rebol's `compress` function, compressing a string of all the 4 stages and printing the corresponding part of it after decompression:

```
f: func[n][o:[[1 374][374 196][570 74][644 37]]
b: decompress debase{eJzjUgAB/RguMKWgAGbUgDg1OFnxQABmKcTEx+uDGTVQOZwM/RgwA2QTyBYQG2wbiAHDw5vjiAS4IEEOCwGoWmQKGsaQAIYE4eAhqeMFSCICGZKSxBWvHxPPBVYKDzkoAVamHwMAjkWmoKkCAAA=}
repeat i o/(n)/2[prin b/(i + o/(n)/1)]]

 f 3
  /\
 /  \
|    |
|    |
|    |
|____|
 \__/
 |  |
 |  |
 |  |
 |__|
  /\

```

# Answer
> 2 votes
# SOGL V0.12, 90 bytes

```
┐∙2╚;+ƨA+.1>?jj■|_ /√+}R
3<?'».1>⌡9R"    kΓC+SA}‘03ž}.‽'⁴R╬³2±6«ž}.3=?4R╬³"XƧ⁸│\׀2⁴‘4n10žP}╬³

```

Try it Here!

Inputs 0/1/2/3 correspondingly to the bytes 1/2/3/4

# Answer
> 2 votes
# Ruby, ~~209~~ 183 bytes

```
->n{z=[a=' /\\ ',b='/  \\']+['|    |']*3+%w{|____| \__/}+[c='|  |']*24+[?A*n]
n>4&&z[10..-n/6]=n>8?[c,a+c+a,b+c+b]+[c*3]*18:['|__|',a]
n==5&&z[0,6]=%w{db _/\_}
z.map{|i|i.center(12)}}

```

Try it online!

Required inputs as follows:

```
Centre core + upper stage + fairing: 4
As above + boosters : 12
Upper stage + fairing: 6
Upper stage without fairing 5

```

The idea is to take the `centre core + upper stage + fairing` as a default and modify it for the other outputs.

**Commented**

```
->n{
  #z = array of parts for centre core + upper stage + fairing, with n A's at the bottom
  z=[a=' /\\ ',b='/  \\']+['|    |']*3+%w{|____| \__/}+[c='|  |']*24+[?A*n]

  #if n not 4, z from element 10 to the last [10..-1] or last but one [10..-2] =
  n>4&&z[10..-n/6]=
    n>8?[c,a+c+a,b+c+b]+[c*3]*18:   #centre core + boosters#
    ['|__|',a]                      #upper stage engine
  n==5&&z[0,6]=%w{db _/\_}        #if n==5, replace first 6 elements with unfaired payload
  z.map{|i|i.center(12)}          #pad each element of array to 12 characters
}                                 #return array of strings (format allowed by question)

```

# Answer
> 1 votes
# Jstx, 124 bytes

```
↕t▌ÇÇÉÇ~éÇÇÇÇÇÇÇÉΘçK↑ε♀▄ü╙Çz⌡"#ße┐é+\òEhZ█╣S♪[ƒuø>!f♪K▌;0♂9☺}ås══½☻eP▌◙&£óZß:&╝af$V≈-wº[√D(♪╘Pφó√ò▲¶>å⌡◘├^∟z◘αßj◙÷»|æ⌠┼øk&£b

```

Explanation

```
↕t▌ÇÇÉÇ~éÇÇÇÇÇÇÇÉΘçK↑ε♀▄ü╙Çz⌡"#ße┐é+\òEhZ█╣S♪[ƒuø>!f♪K▌;0♂9☺}ås══½☻eP▌◙&£óZß:&╝af$V≈-wº[√D(♪╘Pφó√ò▲¶>å⌡◘├^∟z◘αßj◙÷»|æ⌠┼ # Push literal      /\\n    /  \\n   |    |\n   |    |\n   |    |\n   |____|\n    \__/\n    |  |\n    |  |\n    |  |\n    |  |\n /\ |  | /\\n/  \|  |/  \\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\n|  ||  ||  |\nAAAAAAAAAAAA0\n  /\\n /  \\n|    |\n|    |\n|    |\n|____|\n \__/\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n |  |\n AAAA0\n  /\\n /  \\n|    |\n|    |\n|    |\n|____|\n \__/\n |  |\n |  |\n |  |\n |__|\n  /\0\n db\n_/\_\n\__/\n|  |\n|  |\n|  |\n|__|\n /\
ø                                                                                # Push literal 0
k                                                                                # Push a list of strings obtained by splitting the second stack value with the first stack value.
&                                                                                # Swap the top two stack values.
£b                                                                                # Push the value in the list of the second stack value at the index of the first stack value.

```

Try it online!

# Answer
> 0 votes
# C (clang), ~~421~~ 408 bytes

```
r,d,i;f(t){char *s="    ",*e="\n",*l[]={" /\\ ","/  \\","|    |","|____|","\\__/","|  |","AAAA","|__|"," /\\ ","_/\\_","\n"," db","|  ||  ||  |"},*p[]={"VABU3C1DVE8FFF1G","VABU3C1DVE4F1RYAFAKBFBKZ9MM1YGGG","VABU3C1DVE3F1HI","VLJE3F1HI"},*a="",*b,*c=e,*q=p[t];for(r=1;d=*q++;r=(d/48&&57/d)?d-48:r,c=(d/89&&90/d)?e+90-d:c,a=(d/82&&86/d)?s+86-d:a)if(d/65&&77/d)for(b=l[d-65],i=0;i<r;i++)printf("%s%s%s",a,b,c);}

```

Try it online!

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


title: Create a FizzBuzz compiler

text:
# Question
Title: Create a FizzBuzz compiler
Welcome to the world of compiler golf. Your task is to write a program that generates another program to play a variant of FizzBuzz on spec.

# Your compiler

Write a compiler that generates variants of the FizzBuzz program to spec. The spec of this variant is expressed in the form of an array of integer/string pairs.

* The input may be in any form that is convenient to your language. (My examples use n:xxxx, but this is just for illustrative purposes.)
* Each integer input may only be used once per invocation of your compiler.
* The integer of each pair will have a value of at least one.
* The string of each pair will be made of only exactly four ASCII letters.
* The output must be a single complete program that conforms to the rules below.
* The output may be in any convenient form, as long as it is a textual program. (So no returning lambda expressions.)

Behavior is undefined for inputs not conforming to the above rules.

# Your generated FizzBuzz program

The program generated by your compiler will take a single integer, *n*, as input. It will output a sequence of numbers starting from one up to and including *n*, replacing numbers with FizzBuzz strings when required.

* The generated program must be in the same language as the compiler.
* The input *n* may be in any form convenient to your language.
* *n* will have a value of at least one.
* A number that is a multiple of at least one of the integers input to the compiler must be replaced by all of the strings paired with those integers joined together.
* A number that is not to be replaced by a FizzBuzz string must be output in decimal ASCII.

For example;

```
> GenFizzBuzz 3:Fizz 5:Buzz
> a.out 5
1
2
Fizz
4
Buzz

```

# Scoring

Your entry will be scored by the length of the programs your compiler generates added to the length of your compiler. Run your compiler many times with each the following parameters and add the lengths of the generated programs together with the length of the compiler to find your score.

1. Just Count. (No inputs - The generated program will count 1 to *n* without replacements.)
2. Just Golf. (1:Golf - The generated program will output "Golf" *n* times.)
3. Classic FizzBuzz. (3:Fizz, 5:Buzz)

(Note that your compiler is required to generate code for any valid input, not just these listed.)

# Answer
# Python 3 - 168 162 + 230 = 392

Oh, Python, you try so hard, but multiplying the `import sys;sys.argv` stuff by 4 really hurts!

```
import sys;a=eval(sys.argv[1])
print("import sys\nfor i in range(1,int(sys.argv[1])+1):print("+"+".join('"%s"*(i%%%d==0)'%t for t in a)+(a and"or str(i))"or"i)"))

```

Output programs:

```
import sys
for i in range(1,int(sys.argv[1])+1):print(i)
import sys
for i in range(1,int(sys.argv[1])+1):print("Golf"*(i%1==0)or str(i))
import sys
for i in range(1,int(sys.argv[1])+1):print("Fizz"*(i%3==0)+"Buzz"*(i%5==0)or str(i))

```
* Expected input for the main program is an eval-able sequence of Python tuples or `'()'` for no input. (You did say "convenient".) Example input: `'()'`, `'("Golf",1),'`, `'("Fizz",3),("Buzz",5)'` Note quoting for shell and trailing comma for one input.
* Fixed 1am mistake by changing from dict (undefined ordering!) to tuples.
* Expected input for the other programs is just the number
> 8 votes

# Answer
# perl6 376 340 84+115=199

UPDATE: switched from perl5 to perl6 to get `say` without `use feature`.

UPDATE: three test cases instead of five

There are hundreds of already-golfed solutions to FizzBuzz, and many contests end with the same result, so that's where I started. My compiler just produces a customized version of that solution. A few extra characters were inserted to account for the "just count" variation.

compiler, expects arguments like so: "Fizz 3" "Buzz 5"

```
print'say(('.(join'.',map{'('.(join')[$_%',split).']'}@ARGV).')||$_)for 1..$ARGV[0]'

```

compiled programs, expect argument like so: 100

```
say(()||$_)for 1..$ARGV[0]
say(((Golf)[$_%1])||$_)for 1..$ARGV[0]
say(((Fizz)[$_%3].(Buzz)[$_%5])||$_)for 1..$ARGV[0]

```

compiled programs for old test cases:

```
say(((Twoo)[$_%2].(Four)[$_%4].(Eiht)[$_%8])||$_)for 1..$ARGV[0]
say(((Twoo)[$_%2].(Thre)[$_%3].(Five)[$_%5].(Sevn)[$_%7])||$_)for 1..$ARGV[0]

```
> 6 votes

# Answer
# Pyth - 51 + (38 + 43 + 50) = 182 bytes

Can probably golf the compiler a few bytes. The links on all of them are permalinks to the online interpreter.

### Compiler \- 51 bytes

```
%"K[%s)=dc\"%s\"dFGr1hQJkFNKI!%%GN~J@dxKN))?JJG",zw

```

Just does string formatting with an input tuple. Takes input like:

```
3 5
Fizz Buzz

```

### Nothing \- 38 bytes

```
K[)=dc""dFGr1hQJkFNKI!%GN~J@dxKN))?JJG

```

### Just Golf\- 43 bytes

```
K[1)=dc"Golf"dFGr1hQJkFNKI!%GN~J@dxKN))?JJG

```

### Classic Fizz Buzz \- 50 bytes

```
K[3 5)=dc"Fizz Buzz"dFGr1hQJkFNKI!%GN~J@dxKN))?JJG

```
> 3 votes

# Answer
## Common Lisp, ~~636~~ 577

```
(ql:quickload'cl-ppcre)(lambda(z)(princ(subseq(ppcre:regex-replace-all" *([(')]) *"(with-output-to-string(@)(print`(lambda(n)(dotimes(i n)(loop for(m s)in ',z if(=(mod(1+ i)m)0)do(princ s))(do()((fresh-line))(princ (1+ i)))))@))"\\1")1)))

```

I took my other answer and wrapped it in quasiquotes while adding input parameters. I print the resulting form as a single-line and remove unnecessary whitespace characters. The compiler is a little longer than the previous version, but the resulting score is reduced.

### Score

```
(let ((*standard-output* (make-broadcast-stream)))
  (loop
     for form in '(215                      ; Compiler
                   ()                       ; Count
                   ((1 "Golf"))             ; Golf
                   ((3 "Fizz")(5 "Buzz")))  ; FizzBuzz
     for length = (if (numberp form) form
                      (length (funcall *fun* form)))
     collect length into lengths
     sum length into sum
     finally (return (values sum lengths))))

```

Returned values:

```
574
(215 111 119 129)

```

## Pretty

```
(defun fizz-buzz-compiler (z)
  (princ (subseq
          (cl-ppcre:regex-replace-all
           " *([(')]) *"
           (with-output-to-string (stream)
             (print
              `(lambda (n)
                 (dotimes(i n)
                   (loop for (m s) in ',z
                      if (=(mod(1+ i)m)0)
                      do (princ s))
                   (do () ((fresh-line))
                     (princ (1+ i))))) stream))
             "\\1") 1)))

```

The input format is a list of `(number string)` couples. For example:

```
(fizz-buzz-compiler '((3 "Fizz")(5 "Buzz")))

```

... prints to standard output:

```
(LAMBDA(N)(DOTIMES(I N)(LOOP FOR(M S)IN'((3 "Fizz")(5 "Buzz"))IF(=(MOD(1+ I)M)0)DO(PRINC S))(DO NIL((FRESH-LINE))(PRINC(1+ I)))))

```

... which, pretty-printed, is:

```
(lambda (n)
  (dotimes (i n)
    (loop for (m s) in '((3 "Fizz") (5 "Buzz"))
          if (= (mod (1+ i) m) 0)
          do (princ s))
    (do () ((fresh-line)) (princ (1+ i)))))

```

Testing the resulting function:

```
CL-USER> ((lambda (n)
  (dotimes (i n)
    (loop for (m s) in '((3 "Fizz") (5 "Buzz"))
          if (= (mod (1+ i) m) 0)
          do (princ s))
    (do () ((fresh-line)) (princ (1+ i))))) 20)
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

```
> 3 votes

# Answer
# Stax, 23+5+17+29=74

```
╥╟.└ç╘SJ∞CF╔v=▌╝Σ@∞ìé«g

```

Run and debug it

~~Shortest answer so far~~ Not surprisingly beaten by Jelly. The string template provided in Stax is really neat and provides printf-like functions. The programs generated by the compiler are almost always as short as the best one can achieve by manually codegolfing, without using packing.

The compiler itself is 23 bytes long.

The ASCII equivalent is:

```
{H34|S_h"_`c%z`n?+"m"mz`cc_?

```

Provided input `[]`, generates this one (5 bytes)

```
mzc_?

```

Run and debug it

Provided input `[[1,"Golf"]]`, generates this one (17 bytes)

```
mz_1%z"Golf"?+c_?

```

Run and debug it

Provided input `[[3,"Fizz"],[5,"Buzz"]]`, generates this one (29 bytes)

```
mz_3%z"Fizz"?+_5%z"Buzz"?+c_?

```

Run and debug it
> 3 votes

# Answer
# Ruby 99 + (86 + 94 + 103) = 382

```
puts"(1..ARGV[0].to_i).each{|i|x=[];#{ARGV[0]}.each{|k,v|x<<v if i%k==0};puts x.size>0?x.join():i}"

```

Usage:

```
wc -c main.rb # 99 chars
ruby main.rb "{}" | ruby - 100 # 1..2..3..
ruby main.rb "{}" | wc -c # 86 chars
ruby main.rb "{1=>:Golf}" | ruby - 100 # Golf..Golf..Golf..
ruby main.rb "{1=>:Golf}" | wc -c # 94 chars
ruby main.rb "{3=>:Fizz,5=>:Buzz}" | ruby - 100 # 1..2..Fizz..4..Buzz..
ruby main.rb "{3=>:Fizz,5=>:Buzz}" | wc -c # 103 chars

```
> 2 votes

# Answer
# C, 1080 bytes total

# **Compiler \[369 bytes\]**

```
#include<stdlib.h>
r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

```

# **Fizz Buzz \[241\]**

```
#include<stdlib.h>
r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

```

# **Golf \[237\]**

```
#include<stdlib.h>
r,t,f=1,b=0,n;char*F="golf",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

```

# **Count \[233 bytes\]**

```
#include<stdlib.h>
r,t,f=0,b=1,n;char*F="",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

```
> 2 votes

# Answer
# Jelly, ~~88~~ ~~84~~ ~~83~~ 73 bytes

Shortest answer so far (beats the previous "shortest answer" by 1 byte)

Compiler:

```
Ṿ€“ḍ@€“ẋ"Ð€F€ȯ"”jµFF?⁾RY

```

Try it online! (compiler)

Try it online! (verify the bytecount)

---

Statistics:

```
~~19~~ 24 compiler
   20 golf
~~17~~  2 count
   27 fizzbuzz
~~83~~ 73 total

```
> 2 votes

# Answer
# C++11 ~ 486 + (234 + 244 + 255) = 1219

First participation here, this challenge is not among the most difficult ones so I thought I'd give it a try. Using C++ though, and even with C++11 additions it is still a pretty verbose language, but I'm sure there's room for improvement.

### Compiler (486):

```
#include<sstream>
#include<iostream>
using namespace std;main(int c,char**v){stringstream t;int i;string s,o;o="#include <iostream>\n#include <map>\nusing namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{";int z=2;for(int j=1;j<c;++j){t.str(v[j]);t.clear();t >> i; t >> s;o+="{"+to_string(i)+",\""+s+"\"}"+(z++==c?"":",");}o+= R"(};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}})";cout<<o;}

```

It assumes arguments in the form of `3Fizz 5Buzz` etc.

### Count (234):

```
#include <iostream>
#include <map>
using namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}}

```

### Golf (244):

```
#include <iostream>
#include <map>
using namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{{1,"Golf"}};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}}

```

### FizzBuzz (255):

```
#include <iostream>
#include <map>
using namespace std;main(int c,char**v){int i,n=stoi(v[1]);map<int,string> f{{3,"Fizz"},{5,"Buzz"}};bool p;for(i=1;i<n;++i){p=true;for(auto e:f){if(i%e.first==0){cout<<e.second;p=false;}}cout<<(p?to_string(i):"")+"\n";}}

```

### Additional information

Tested with GCC 4.8.1, no compiler cheats.

Here is a small makefile to automate the generation of the test cases and run them (use `make run`):

```
run:
    g++ main.cpp --std=c++11 -o fbc

    ./fbc > count.cpp
    g++ count.cpp --std=c++11
    echo "======= Count ========"
    ./a.out 15

    ./fbc 1Golf > golf.cpp
    g++ golf.cpp --std=c++11
    echo "======= Golf ========"
    ./a.out 15

    ./fbc 3Fizz 5Buzz > fizzbuzz.cpp
    g++ fizzbuzz.cpp --std=c++11
    echo "======= FizzBuzz ========"
    ./a.out 15

```
> 1 votes

# Answer
# Perl 5, 77 + 93, 170 bytes

```
say"say",(map{++$i%2?"'$_":"'x!(\$_%$_)".($i<$#F?'.':'||$_')}@F),' for 1..<>'

```

Try the compiler online!
Try just count online!
Try just golf online!
Try fizz buzz online!
> 1 votes

# Answer
# vim, 122 (compiler) + 73 (empty) + 90 (golf) + 123 (fizzbuzz) = 392 bytes

## Compiler

```
:%s/\v(.*):(.*)/qq\1jA\2<C-V><C-V><C-V><ESC>q=@qgg
VgggJAddGdd:%s/\v[0-9]*([^0-9])/\1
<C-V><ESC>:%@n
:w
:so! %
<ESC>ggii%s/=/<C-V><ESC><C-V><C-A>a/g<C-V><ESC>"ncc:%!seq 0 =
<ESC>

```

## Input format

```
3:Fizz
5:Buzz

```

## Generated code for FizzBuzz case

```
i%s/=/<ESC><C-A>a/g<ESC>"ncc:%!seq 0 =
qq3jAFizz<C-V><ESC>q=@qggqq5jABuzz<C-V><ESC>q=@qggddGdd:%s/\v[0-9]*([^0-9])/\1
<ESC>:%@n
:w
:so! %

```

### Generated Code, Annotated

```
# replace the input number with a regex that replaces the placeholder (=)
# with the real number + 1 (we'll need an extra line as a terminator later)
i%s/=/<ESC><C-A>a/g<ESC>

# pull the substitution command into register c and enter insert mode
"ncc

# create the numbers 0..N+1
:%!seq 0 =

# for each word, scan down k lines at a time and append the word to each
qq3jAFizz<C-V><ESC>q=@qgg
qq5jABuzz<C-V><ESC>q=@qgg

# delete the 0 and N+1 lines
ddGdd

# remove the numbers from any line with words
:%s/\v[0-9]*([^0-9])/\1
<ESC>

# Run the command we created at the beginning, replacing the placeholder
# with the real number
:%@n

# The file now contains yet another program, with the constants defined.
# Save and run.
:w
:so! %

# The file now contains a program that, when run on a buffer containing
# a single line with a number, will produce the appropriate output

```

`<C-V>` is 0x16. `<ESC>` is 0x1b. `<C-A>` is 0x01.

# Example session

```
$ cat code.txt
2:Foo
4:Bar
$ cat input.txt
8
$ { cat compile.vim; echo ':wq'; } | vim code.txt
# code.txt now contains the generated code
$ { cat code.txt; echo ':wq'; } | vim input.txt
$ cat input.txt
1
Foo
3
FooBar
5
Foo
7
FooBar

```
> 1 votes

# Answer
# dc, 434 bytes

```
[:a]sa[91Pn93Pznlanps_znlanz0<R]sR[[[lj1-;aP1sb]sB0sj[dljd2+sj;a%0=Bljlz>F]sF[p2Q]sP]P]sI[[[]sF[pq]sP]nq]sN[z0=Nzn[sz]PlRxlIx]x[sn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx]P

```

Try it online!

Input for the compiler (168 bytes) should be placed on the stack as integer, string, integer, string, and so on (`3 [Fizz] 5 [Buzz]`). It should be given in the order one wants their fizzes and buzzes to be printed, which may be a bit of a cheat (having implemented bubble sort in `dc` before, I believe it would cost me around 100 bytes) but it also allows the user to, say, still have 'Fizz' run on 3 and 'Buzz' run on 5, but have 15 yield 'BuzzFizz'.

I'm sure this can be golfed a bit more; the main macro in the final program (`M`) relies on two macros (`F` and `P`) that are rather unnecessary given no input. Right now the compiler checks for input and outputs different (much smaller) versions of these macros if there is none, but I'm not sure the whole setup is optimal.

The compiler itself is pretty straightforward, it just checks to see if there are 'rules' on the stack, and if so it prints code that stores the stack depth in `z`, stores the stack in a 0-indexed array `a`, and then prints the generalized FizzBuzz code. If there was nothing on the stack, it really just prints a modified version of the FizzBuzz code. Test cases:

No input (46 bytes):

```
[]sF[pq]sPsn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx

```

3\[Fizz\]5\[Buzz\] (117 bytes):

```
4sz[Buzz]3:a5
2:a[Fizz]1:a3
0:a[lj1-;aP1sb]sB0sj[dljd2+sj;a%0=Bljlz>F]sF[p2Q]sPsn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx

```

1\[Golf\] (103 bytes):

```
2sz[Golf]1:a1
0:a[lj1-;aP1sb]sB0sj[dljd2+sj;a%0=Bljlz>F]sF[p2Q]sPsn0dsb[1+0sjlFx[lb0=PAP]x0sbdln>M]dsMx

```

They all expect the *n* value on the stack, this gets stored in `n`. The ones that have 'rules' place them in the array `a`, with the strings at odd indices and the integers at evens. The main macro, `M`, increments whatever is on the stack, runs macro `F` which checks the value against array `a`, checks whether `F` set register `b` to truthy or not and prints the top of stack if so or a newline if not, resets `b` to falsy, and then keeps running itself if `n` hasn't been reached yet. Macro `F`, given rules, goes through the whole array looking for matches. It increments by two since our integers and strings are woven through the array, and on a match it calls macro `B`. Macro `B` just retrieves the string (current position in array less one), and prints it. It also sets `b` to truthy. Our compiler doesn't bother to print `B` for no input, and essentially makes `F` a nop.
> 0 votes

# Answer
# SlooSarksi .Lang, 179

```
%%--43^jjk"/][][0[#!#111# h SD G ergDFGdfg[]9--99+==

```
> -2 votes

---
Tags: code-challenge, code-generation, compiler, fizzbuzz
---


title: Google's Hopping Bunny

text:
# Question
Title: Google's Hopping Bunny
On December 4, 2017, the Google Doodle was a graphical programming game featuring a bunny. The later levels were nicely non-trivial and they seemed like a great candidate for an challenge.

## Details

### Game

* **There are four available moves: hop forward, turn left, turn right, and loop. Each of these moves is one token**, corresponding to the fact that they are each one tile in the game.
* The bunny can face four orthogonal directions (i.e. north, south, east, west).
* The bunny can hop forward (move one square in the direction it's facing) and turn left or right.
* Loops may have any number of other moves inside them, including other loops, and their iteration count is any positive integer (though the game technically allows an iteration count of 0).
* The board is a set of grid-aligned squares and the bunny can hop between adjacent squares.
* **The bunny cannot hop into the void.** Meaning that an attempt to hop off the board does nothing. *(This was apparently a surprise for some people and a disappointment for others.)*
* Squares are either marked or unmarked. When the bunny is on a square, it becomes marked.
* The level is complete when all squares are marked.
* You may assume a solution exists.

### Your code

* **Objective: given a board, find one or more shortest solutions.**
* Input is a list of square locations forming the board (distinguishing marked and unmarked squares) and output is a list of moves. Input and output *format* does not matter at all, so long as they are human-readable and understandable.
* **Winning criterion:** sum of number of moves of shortest solutions found within one minute for each board. If your program does not find a solution for any particular board, your score for that board is (5 * number of squares).
* **Please do not hardcode solutions in any manner.** Your code should be able to take any board as input, not just the ones given as examples below.

## Examples

**Solutions are hidden in spoilers to give you a chance to play the game first and attempt some of these yourself.** Also, only one solution is provided below for each.

`S` is the bunny's starting square (facing east), `#` is an unmarked square, and `O` is a marked square. For moves, my notation is `F` = hop forward, `L` = turn left, `R` = turn right, and `LOOP(<num>){<moves>}` denotes a loop that iterates `<num>` times and does `<moves>` each time. If the loop can run any number of times beyond some minimum number, `<num>` may be omitted (i.e. infinity works).

**Level 1:**

```
S##

```

> F F

**Level 2:**

```
S##
  #
  #

```

> LOOP(2){F F R}

**Level 3:**

```
S##
# #
###

```

> LOOP{F F R}

**Level 4:**

```
###
# #
##S##
  # #
  ###

```

> LOOP{ F LOOP(7){F L} } (found by DJMcMayhem)

**Level 5:**

```
#####
# # #
##S##
# # #
#####

```

> LOOP(18){ LOOP(10){F R} L}
> Source: Reddit

**Level 6:**

```
 ###
#OOO#
#OSO#
#OOO#
 ###

```

> LOOP{ LOOP(3){F} L }

**Huge boards:** (shortest solutions currently unknown)

12x12:

```
S###########
############
############
############
############
############
############
############
############
############
############
############

```

Level 5 but way bigger:

```
#############
# # # # # # #
#############
# # # # # # #
#############
# # # # # # #
######S######
# # # # # # #
#############
# # # # # # #
#############
# # # # # # #
#############

```

More holey boards:

```
S##########
###########
## ## ## ##
###########
###########
## ## ## ##
###########
###########
## ## ## ##
###########
###########

```

and

```
S#########
##########
##  ##  ##
##  ##  ##
##########
##########
##  ##  ##
##  ##  ##
##########
##########

```

Finally, asymmetry can be a real pain in the butt:

```
#######
# ##  #
#######
###S###
# ##  #
# ##  #
#######

```

and

```
#########
# ##  ###
###S  ###
# #######
###    ##
#####   #
####  ###
#########
#########

```

# Answer
> 12 votes
# Python 3, 67 tokens

```
import sys
import time

class Bunny():
    def __init__(self):
        self.direction = [0, 1]
        self.coords = [-1, -1]

    def setCoords(self, x, y):
        self.coords = [x, y]

    def rotate(self, dir):
        directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        if dir == 'L':
            self.direction = directions[(directions.index(self.direction) + 1) % 4]
        if dir == 'R':
            self.direction = directions[(directions.index(self.direction) - 1) % 4]

    def hop(self):
        self.coords = self.nextTile()

    # Returns where the bunny is about to jump to
    def nextTile(self):
        return [self.coords[0] + self.direction[0], self.coords[1] + self.direction[1]]

class BoardState():
    def __init__(self, map):
        self.unvisited = 0
        self.map = []

        self.bunny = Bunny()
        self.hopsLeft = 0

        for x, row in enumerate(map):
            newRow = []
            for y, char in enumerate(row):
                if char == '#':
                    newRow.append(1)
                    self.unvisited += 1

                elif char == 'S':
                    newRow.append(2)

                    if -1 in self.bunny.coords:
                        self.bunny.setCoords(x, y)
                    else:
                        print("Multiple starting points found", file=sys.stderr)
                        sys.exit(1)

                elif char == ' ':
                    newRow.append(0)

                elif char == 'O':
                    newRow.append(2)

                else:
                    print("Invalid char in input", file=sys.stderr)
                    sys.exit(1)

            self.map.append(newRow)

        if -1 in self.bunny.coords:
            print("No starting point defined", file=sys.stderr)
            sys.exit(1)

    def finished(self):
        return self.unvisited == 0

    def validCoords(self, x, y):
        return -1 < x < len(self.map) and -1 < y < len(self.map[0])

    def runCom(self, com):
        if self.finished():
            return

        if self.hopsLeft < self.unvisited:
            return

        if com == 'F':
            x, y = self.bunny.nextTile()
            if self.validCoords(x, y) and self.map[x][y] != 0:
                self.bunny.hop()
                self.hopsLeft -= 1

                if (self.map[x][y] == 1):
                    self.unvisited -= 1
                self.map[x][y] = 2

        else:
            self.bunny.rotate(com)

class loop():
    def __init__(self, loops, commands):
        self.loops = loops
        self.commands = [*commands]

    def __str__(self):
        return "loop({}, {})".format(self.loops, list(self.commands))

    def __repr__(self):
        return str(self)

def rejectRedundantCode(code):
    if isSnippetRedundant(code):
        return False

    if type(code[-1]) is str:
        if code[-1] in "LR":
            return False
    else:
        if len(code[-1].commands) == 1:
            print(code)
            if code[-1].commands[-1] in "LR":
                return False

    return True

def isSnippetRedundant(code):
    joined = "".join(str(com) for com in code)

    if any(redCode in joined for redCode in ["FFF", "RL", "LR", "RRR", "LLL"]):
        return True

    for com in code:
        if type(com) is not str:
            if len(com.commands) == 1:
                if com.loops == 2:
                    return True

                if type(com.commands[0]) is not str:
                    return True

                if com.commands[0] in "LR":
                    return True

            if len(com.commands) > 1 and len(set(com.commands)) == 1:
                return True

            if isSnippetRedundant(com.commands):
                return True

    for i in range(len(code)):
        if type(code[i]) is not str and len(code[i].commands) == 1:
            if i > 0 and code[i].commands[0] == code[i-1]:
                return True
            if i < len(code) - 1 and code[i].commands[0] == code[i+1]:
                return True

        if type(code[i]) is not str:
            if i > 0 and type(code[i-1]) is not str and code[i].commands == code[i-1].commands:
                return True
            if i < len(code) - 1 and type(code[i+1]) is not str and code[i].commands == code[i+1].commands:
                return True

            if len(code[i].commands) > 3 and all(type(com) is str for com in code[i].commands):
                return True

    return False

def flatten(code):
    flat = ""
    for com in code:
        if type(com) is str:
            flat += com
        else:
            flat += flatten(com.commands) * com.loops

    return flat

def newGen(n, topLevel = True):
    maxLoops = 9
    minLoops = 2
    if n < 1:
        yield []

    if n == 1:
        yield from [["F"], ["L"], ["R"]]

    elif n == 2:
        yield from [["F", "F"], ["F", "L"], ["F", "R"], ["L", "F"], ["R", "F"]]

    elif n == 3:
        for innerCode in newGen(n - 1, False):
            for loops in range(minLoops, maxLoops):
                if len(innerCode) != 1 and 0 < innerCode.count('F') < 2:
                    yield [loop(loops, innerCode)]

        for com in "FLR":
            for suffix in newGen(n - 2, False):
                for loops in range(minLoops, maxLoops):
                    if com not in suffix:
                        yield [loop(loops, [com])] + suffix

    else:
        for innerCode in newGen(n - 1, False):
            if topLevel:
                yield [loop(17, innerCode)]
            else:
                for loops in range(minLoops, maxLoops):
                    if len(innerCode) > 1:
                        yield [loop(loops, innerCode)]

        for com in "FLR":
            for innerCode in newGen(n - 2, False):
                for loops in range(minLoops, maxLoops):
                    yield [loop(loops, innerCode)] + [com]
                    yield [com] + [loop(loops, innerCode)]

def codeLen(code):
    l = 0
    for com in code:
        l += 1
        if type(com) is not str:
            l += codeLen(com.commands)

    return l

def test(code, board):
    state = BoardState(board)
    state.hopsLeft = flatten(code).count('F')

    for com in code:
        state.runCom(com)

    return state.finished()

def testAll():
    score = 0
    for i, board in enumerate(boards):
        print("\n\nTesting board {}:".format(i + 1))
        #print('\n'.join(board),'\n')
        start = time.time()

        found = False
        tested = set()

        for maxLen in range(1, 12):
            lenCount = 0
            for code in filter(rejectRedundantCode, newGen(maxLen)):
                testCode = flatten(code)
                if testCode in tested:
                    continue

                tested.add(testCode)

                lenCount += 1
                if test(testCode, board):
                    found = True

                    stop = time.time()
                    print("{} token solution found in {} seconds".format(maxLen, stop - start))
                    print(code)
                    score += maxLen
                    break

            if found:
                break

    print("Final Score: {}".format(score))

def testOne(board):
    start = time.time()
    found = False
    tested = set()
    dupes = 0

    for maxLen in range(1, 12):
        lenCount = 0
        for code in filter(rejectRedundantCode, newGen(maxLen)):
            testCode = flatten(code)
            if testCode in tested:
                dupes += 1
                continue

            tested.add(testCode)

            lenCount += 1
            if test(testCode, board):
                found = True
                print(code)
                print("{} dupes found".format(dupes))
                break

        if found:
            break

        print("Length:\t{}\t\tCombinations:\t{}".format(maxLen, lenCount))

    stop = time.time()
    print(stop - start)

#testAll()
testOne(input().split('\n'))

```

This program will test a single input board, but I find **this test driver more useful**. It will test every single board at the same time and print how long it took to find that solution. When I run that code on my machine (Intel i7-7700K quad core CPU @ 4.20 GHz, 16.0 GB RAM), I get the following output:

```
Testing board 1:
2 token solution found in 0.0 seconds
['F', 'F']

Testing board 2:
4 token solution found in 0.0025103092193603516 seconds
[loop(17, [loop(3, ['F']), 'R'])]

Testing board 3:
4 token solution found in 0.0010025501251220703 seconds
[loop(17, [loop(3, ['F']), 'L'])]

Testing board 4:
5 token solution found in 0.012532949447631836 seconds
[loop(17, ['F', loop(7, ['F', 'L'])])]

Testing board 5:
5 token solution found in 0.011022329330444336 seconds
[loop(17, ['F', loop(5, ['F', 'L'])])]

Testing board 6:
4 token solution found in 0.0015044212341308594 seconds
[loop(17, [loop(3, ['F']), 'L'])]

Testing board 7:
8 token solution found in 29.32585096359253 seconds
[loop(17, [loop(4, [loop(5, [loop(6, ['F']), 'L']), 'L']), 'F'])]

Testing board 8:
8 token solution found in 17.202533721923828 seconds
[loop(17, ['F', loop(7, [loop(5, [loop(4, ['F']), 'L']), 'F'])])]

Testing board 9:
6 token solution found in 0.10585856437683105 seconds
[loop(17, [loop(7, [loop(4, ['F']), 'L']), 'F'])]

Testing board 10:
6 token solution found in 0.12129759788513184 seconds
[loop(17, [loop(7, [loop(5, ['F']), 'L']), 'F'])]

Testing board 11:
7 token solution found in 4.331984758377075 seconds
[loop(17, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]

Testing board 12:
8 token solution found in 58.620323181152344 seconds
[loop(17, [loop(3, ['F', loop(4, [loop(3, ['F']), 'R'])]), 'L'])]

Final Score: 67

```

This last test just barely squeaks in under the minute restriction.

### Background

This was one of the most fun challenges I've ever answered! I had a blast pattern hunting and looking for heuristics to cut down on things.

Generally, here on PPCG I tend to answer relatively easy questions. I'm especially fond of the tag because it's generally pretty well suited for my languages. One day, about two weeks ago, I was looking through my badges and I realized that I had never gotten the revival badge. So I looked through the *unanswered* tab to see if anything caught my eye, and I found this question. I decided that I would answer it no matter the cost. It ended up being a bit harder than I thought it would, but I finally got a brute-force answer that I can say I'm proud of. But this challenge is totally out of the norm for me since I don't usually spend more than an hour or so on a single answer. This answer took me a little over 2 weeks and at least 10+ of work to finally get to this stage, though I wasn't keeping careful track.

The first iteration was a pure brute force solution. I used the following code to generate all snippets up to length **N**:

```
def generateCodeLenN(n, maxLoopComs, maxLoops, allowRedundant = False):
    if n < 1:
        return []

    if n == 1:
        return [["F"], ["L"], ["R"]]

    results = []

    if 1:
        for com in "FLR":
            for suffix in generateCodeLenN(n - 1, maxLoopComs, maxLoops, allowRedundant):
                if allowRedundant or not isSnippetRedundant([com] + suffix):
                    results.append([com] + suffix)

    for loopCount in range(2, maxLoopComs):
        for loopComs in range(1, n):
            for innerCode in generateCodeLenN(loopComs, maxLoopComs, maxLoops - 1, allowRedundant):
                if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)]):
                    continue

                for suffix in generateCodeLenN(n - loopComs - 1, maxLoopComs, maxLoops - 1, allowRedundant):
                    if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)] + suffix):
                        continue

                    results.append([loop(loopCount, innerCode)] + suffix)

                if loopComs == n - 1:
                    results.append([loop(loopCount, innerCode)])

    return results

```

At this point, I was sure that testing every single possible answer would be way too slow, so I used `isSnippetRedundant` to filter out snippets that could be written with a shorter snippet. For example, I would refuse to yield the snippet `["F", "F", "F"]` because the exact same effects could be achieved with `[Loop(3, ["F"])`, so if it we get to the point where we test length-3 snippets, we know that no length-3 snippet could solve the current board. This used a lot of good mnemonics, but ultimately was *waaaay* too slow. Testcase 12 took just over 3,000 seconds using this approach. This is clearly significantly too slow. But using this information and a bunch of computer cycles to brute force short solutions to every board, I could find a new pattern. I noticed that almost every solution found would generally look like something like the following:

```
[<com> loop(n, []) <com>]

```

nested several layers deep, with the single coms on each side being optional. This means that solutions like:

```
["F", "F", "R", "F", "F", "L", "R", "F", "L"]

```

would never appear. In fact, there was never a sequence of more than 3 non-loop tokens. One way to utilize this would be to filter out all of these and not bother to test them. But generating them was still taking a non-negligible amount of time, and filtering through the millions of snippets like this would barely cut time off. Instead I drastically rewrote the code-generator to only generate snippets following this pattern. In pseudo code, the new generator follows this general pattern:

```
def codeGen(n):
    if n == 1:
        yield each [<com>]

    if n == 2:
        yield each [<com>, <com>]

    if n == 3:
        yield each [loop(n, <com length 2>]
        yield each [loop(n, <com>), <com>]

    else:
        yield each [loop(n, <com length n-1>)]
        yield each [loop(n, <com length n-2>), <com>]
        yield each [<com>, loop(n, <com length n-2>)]

        # Removed later
        # yield each [<com>, loop(n, <com length n-3>), <com>]
        # yield each [<com>, <com>, loop(n, <com length n-3>)]
        # yield each [loop(n, <com length n-3>), <com>, <com>]

```

This cut the longest test case down to 140 seconds, which is a ridiculous improvement. But from here, there were still some things I needed to improve. I started more aggressively filtering out redundant/worthless code and checking to see if code has been tested before. This cut it down further, but it wasn't enough. In the end, the final piece that was missing was the loop counter. Through my highly advanced algorithm (read: *random trial and error*) I determined that the optimal range to allow loops to run in is \[3-8\]. But there's a huge improvement in there: If we know that `[loop(8, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]` can't solve our board, then there's absolutely no way that `[loop(3, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]` or any loop count from 3-7 could solve it. So rather than iterating through all the loop sizes from 3-8, we set the loop count on the outer loop to the max. This ends up cutting the search space down by a factor of `maxLoop - minLoop`, or 6 in this case.

This helped a lot, but ended up inflating the score. Certain solutions I had found earlier by brute force require larger loop numbers to run (for example, boards 4 and 6). So rather than setting the outer loop count to 8, we set the outer loop count to 17, a magical number also calculated by my highly advanced algorithm. We know we can do this because increasing the loop count of the outermost loop has no effect on the solution's validity. This step actually reduced our final score by 13. So not a trivial step.

---
Tags: code-challenge, atomic-code-golf, metagolf
---


title: Un-average temperatures!

text:
# Question
Title: Un-average temperatures!
There was a discussion going on in TNB once about the best temperature scale, and we agreed on something: Take the average of all four main temperature scales! That is, Celsius, Kelvin, Fahrenheit, and Rankine (Sorry Réaumur).

So, now the issue is, most people don't use this system. So, I need a program to convert back from this average!

# Challenge

Given the average of the Celsius, Fahrenheit, Kelvin, and Rankine representations of a certain temperature, output the individual standard representations, in any prespecified and consistent order. It turns out that this is possible, based on my whiteboard calculations. Input will be a single floating-point value in whatever range your language can handle, and output will be four floating-point values in any reasonable format. You can restrict the input to force the output to be in the range of your language, but you must be able to support down to Absolute Zero (thus, you need to be able to handle negative numbers).

# Test Cases

```
input -> (Celsius, Fahrenheit, Kelvin, Rankine)
100 -> (-70.86071428571424, -95.54928571428565, 202.28928571428574, 364.12071428571437)
20 -> (-128.0035714285714, -198.4064285714286, 145.14642857142857, 261.2635714285714)
-10 -> (-149.43214285714282, -236.97785714285715, 123.71785714285716, 222.69214285714287)
10000 -> (7000.567857142858, 12633.022142857144, 7273.717857142858, 13092.692142857144)

```

These values were generated with Uriel's Python program, and I verified that they were correct.

# Answer
> 4 votes
# Pyth, ~~40~~ ~~37~~ 36 bytes

```
~~-BJ+c36641 280c*5Q7 273.15-B*J1.8 459.67~~
~~-BJc+916.025*5Q7 273.15-B*J1.8 459.67~~
-BJc+916.025*5Q7 273.15-B*1.8J459.67

```

Try it online!

### Specs

* Input: `100`
* Output: `[Kelvin, Celcius]\n[Rankine, Fahrenheit]`

### Math

```
kelvin = (average*5+916.025)/7

```

# Answer
> 10 votes
# Python, 63 bytes

```
def f(a):x=(a+183.205)*5/7;m=x*9/5;return x-273.15,m-459.67,x,m

```

`a` is the average, returns a tuple of the results as `(celsius, fahrenheit, kelvin, rankine)`

**Math involved:**

```
kelvin = x
celsius = x - 273.15
fahrenheit = x * 9/5 - 459.67
rankine = x * 9/5

a = (x + x - 273.15 + x * 9/5 - 459.67 + x * 9/5) / 4 = x * 7/5 - 183.205
x = (a + 183.205) * 5/7

```

# Answer
> 10 votes
## JavaScript (ES6), 49 bytes

```
f=
a=>[a=(a-199.205)/1.4,a+=273.15,a*=1.8,a-=459.67]
```

```
<input oninput=f(this.value).map(function(x,i){o.rows[i].cells[1].textContent=x})>
<table id=o>
<tr><th>Celsius:</th><td></td></tr>
<tr><th>Kelvin:</th><td></td></tr>
<tr><th>Rankine:</th><td></td></tr>
<tr><th>Fahrenheit:</th><td></td></tr>
</table>
```

# Answer
> 3 votes
# Dyalog APL, ~~46~~ 40 bytes

*6 bytes saved thanks to @Adám*

```
273.15 459.67 0 0-⍨4⍴63 35÷⍨45×183.205+⊢

```

Try it online!

Anonymous monad, uses the Dyalog Classic character set.

# Answer
> 2 votes
# PHP, 62 Bytes

Order Kelvin , Celsius , Rankine , Fahrenheit

```
print_r([$t=($argn+183.205)/1.4,$t-273.15,$t*=1.8,$t-459.67]);

```

Online Version

## PHP, 64 Bytes

Order Kelvin , Rankine , Fahrenheit , Celsius

```
print_r([$k=($argn+183.205)/1.4,$r=1.8*$k,$r-459.67,$k-273.15]);

```

Online Version

# Answer
> 2 votes
# dc, 37 ~~38~~ bytes

*\[Edit 1: Added third form, per Neil's comment\]*

These *\[first two\]* are both the same length :( The first one produces Fahrenheit, Celsius, Kelvin, Rankine (top to bottom on the stack), and the second one produces Fahrenheit, Rankine, Celsius, Kelvin.

```
9k?183.205+1.4/d1.8*rd273.15-d1.8*32+f
9k?183.205+1.4/d273.15-rd1.8*d459.67-f
9k?199.205-1.4/d273.15+d1.8*d459.67-f

```

Example outputs (`dc` uses _ to signal negative numbers on input): *\[from first two forms; see edit below for third form.\]*

```
20
-198.406428572
-128.003571429
145.146428571
261.263571427

20
-198.406428573
261.263571427
145.146428571
-128.003571429

_10
-236.977857144
-149.432142858
123.717857142
222.692142855

_10
-236.977857145
222.692142855
123.717857142
-149.432142858

```

# How it works

```
9k?183.205+1.4/d1.8*rd273.15-d1.8*32+f

```

`9k` sets 9-place arithmetic.
`?` reads input from stdin, leaving it at top of stack (TOS).
`183.205+` adds 183.205 to TOS
`1.4/` divides TOS by 1.4 or 7/5, giving degrees Kelvin.
`d` duplicates TOS. (Ie, duplicates degrees Kelvin)
`1.8*r` computes Rankine from Kelvin, then reverses top two of stack.
`d273.15-` duplicates TOS and subtracts 273.15 to get degrees Celsius.
`d1.8*32+` duplicates TOS, multiplies by 9/5, and adds 32, for Fahrenheit.
`f` prints contents of stack.

---

*Edit 1, continued:*

```
9k?199.205-1.4/d273.15+d1.8*d459.67-f

```

This form, suggested by Neil, begins by computing Celsius instead of Kelvin. This saves a rotate (an `r`) when computing Rankin from Kelvin.

It computes Celsius = (Average - 199.205)\*5/7 via `199.205-1.4/`, adds 273.15 to get Kelvin, multiplies by 1.8 to get Rankin, and subtracts 459.67 to get Fahrenheit. For example:

```
20
-198.406428571
261.263571429
145.146428572
-128.003571428

```

# Answer
> 1 votes
# CJam, 38 bytes

```
rd5*916.025+7/_p_273.15-p1.8*_p459.67-

```

Kelvins = `(5*input+916.025)/7`

Outputs as

```
Kelvin
Celsius
Rankine
Fahrenheit

```

Try it online!

# Answer
> 1 votes
# Whispers v2, 168 bytes

```
> Input
> 5
> 7
> 183.205
>> 2÷3
>> 1+4
>> 6⋅5
>> 7-11
>> 7⋅12
>> 9-13
> 273.15
> 1.8
> 459.67
>> Output 7
>> Output 8
>> Output 9
>> Output 10
>> Then 14 15 16 17

```

Try it online!

Outputs as `Kelvin\nCelsius\nRankine\nFahrenheit`

# Answer
> 0 votes
**Python 3, 67 bytes**

```
c=(5*float(input())-996.025)/7;t=[c,c*1.8+32,c+273.15,c*1.8+491.67]

```

This code does some algebra to get the temperature in Celcius, then I convert it to the other temperature units. The temperatures are stored in the list `t`.

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


title: Hexadecimal, octal, binary, oh my!

text:
# Question
Title: Hexadecimal, octal, binary, oh my!
This is a code golf puzzle: shortest byte count wins. The program should do the following (standard loopholes obviously forbidden):

1. Input a hexadecimal number
2. Convert to octal
3. Then interpret the digits as if in decimal (765 octal -\> 765 decimal)
4. Divide the number by two
5. Convert to hexadecimal

## Example:

Input: 4a3d Output: 5809.8

```
4a3d -> 45075 -> 45075 -> 22537.5 -> 5809.8

```

# Answer
> 0 votes
# Perl 6, 30 bytes

```
{(:16($_).base(8)/2).base(16)}

```

Try it online!

# Answer
> 1 votes
# Javascript,~~56~~ ~~53~~ 52 bytes

-3 bytes thanks to @ovs

-1 byte thanks to @Arnauld

```
p=parseInt,a=>(p(p(a,16)[s='toString'](8))/2)[s](16)

```

toString on an integer converts the integer to a string in that base.

Try it online!

---
Tags: code-golf, base-conversion
---