title: Create a simple 2048 game clone

text:
# Question
Title: Create a simple 2048 game clone
2048 is an incredibly fun and addictive game in which the goal is to create a tile with 2048 on it.

Here's a short description of the game:

---

Pressing an arrow key will slide all the blocks in the stage in that direction. For example, if `x` represents a block, and you pressed the up arrow in this case:

```
...x
.x..
..x.
xx..

```

Then the board would become

```
xxxx
.x..
....
....

```

Furthermore, the blocks are numbered, starting at `2`. If two of the same numbered blocks are moved together, they will merge into the next number. For example, pressing "up" on this board:

```
.2..
..22
.2..
....

```

Would create this:

```
.422
....
....
....

```

And then after pressing "right," it would become `..44`, and therefore pressing right again would create an "8" block, and so on.

Each turn, a new "2" block is created on a random open square. (It's actually not *always* a "2," but for simplicity let's keep it at that.) If there are no possible moves left (i.e., the board is full and you can't merge anything), the game is lost, and if a 2048 block is created, you win!

---

Your challenge is to recreate this game, golfed!

* For edge-cases, such as pressing "right" on this board:

```
....
.222
....
....

```

you must merge the tiles closest to the edge of the arrow key pressed. For example, this would become `..24`, because the second and third "2"s are the closest to the right edge.
* If the player presses an invalid move (such as "up" on a board like `2.2. / .... / .... / ....`), you must ignore the move.
* Moves can be accepted in any way, such as clicking, arrow keys, `ULRD`, etc.
* The tiles must all be the same shape—a "1024" tile should be the same size as a "2" tile.
* The tiles must be separated in some way. For example, `|1024| 2|1024|1024|` is a valid example of a row (assuming that the tiles are squares), while `1024 210241024` is not.
* You must output "you win" if the player creates a 2048 tile, or "you lose" if there are no valid moves left.
* This is , so the shortest code in bytes will win!

# Answer
# APL (Dyalog APL), ~~153~~ ~~150~~ ~~167~~ ~~156~~ ~~155~~ 151 bytes

```
'you ',{2048∊⍵:'win'
(z/∊n)[?+/z←0=∊n←⍵]←2
⎕←4↑¨⍕¨n
1∊(⍉2=⌿n),(2=/n),0=n:∇{⍵≡r←R⍣¯1⎕UCS{4↑⍺⍺t⎕R(1⌽∪¨t←2/¨⍺⍺2*⍳16)⍺⍺⍵~0}¨(R←↓⍉∘⌽⍣⎕)⍵:∇⍵⋄r}n
'lose'}4 4⍴0

```

Prompts for move; 0=Left, 1=Up 2=Right, 3=Down

Try it online!

### Ungolfed, with whitespace

```
C ← ⎕UCS
'you ', {
    2048 ∊ ⍵: 'win'
    n ← ⍵
    z ← 0 = ∊n
    (z / ∊n)[? +/z] ← 2
    ⎕ ← 4 ↑¨ ⍕¨n
    1 ∊ (⍉ 2 =⌿ n) , (2 =/ n) , 0 = n: ∇ {
        R←↓⍉∘⌽⍣⎕
        r ← R⍣¯1 ⎕UCS {
            t ← 2 /¨ ⍺⍺ 2 * ⍳16
            4 ↑ ⍺⍺ t ⎕R (1 ⌽ ∪¨t) ⍺⍺ ⍵ ~ 0
        }¨ R ⍵
        ⍵ ≡ r: ∇ ⍵
        r
    } n
    'lose'
} 4 4⍴0

```

### Explanation

Blank lines indicate a newline, while blocks of lines belong on a single line

> `'you ',` "you" prepended to the result of the function `{`...
>
> > `2048 ∊ ⍵: 'win'` if the argument (the board) contains 2048, then return "win"
> >
> > `n ← ⍵` assign the right argument to *n* (so it may be modified in-place)
> >
> > `z ← 0 = ∊n`*z* gets the Boolean list where flattened *z* is 0
> >
> > `(z / ∊n)`*z* filters the flattened *n* (to get only the zeros)
> > `[? +/z]` use a random number between 1 and the count of zeros (the sum of the Boolean *z*) to select which zero-containing position
> > `← 2` gets a 2
> >
> > `⎕ ←` output the
> > `4 ↑¨` each extended-to-length-4 (with spaces)
> > `⍕¨n` string representation of each number
> >
> > `1 ∊` if any of the following are found;
> > `(⍉2=⌿n)` pairwise vertical equalities (transposed to be concatenable)
> > `,` or (concatenated to)
> > `(2=/n)` pairwise horizontal equalities
> > `,` or (concatenated to)
> > `0=n` zeros
> > `:` then:
> > call this function on the result of the function `{`...
> >
> > > `R ←`*R* (for *R*ows of *R*otated) is
> > > the split-into-rows
> > > `⍉∘⌽⍣⎕` prompt for numeric input, then rotate (literally mirror horizontally, then transpose) the argument (the board) –90° times the inputted number
> > >
> > > `r ←`*r* (for *r*esult) gets
> > > `R⍣¯1` the inverse of *R* (rotate back, then merge rows into matrix) applied to the result of the function `⎕UCS{`... (where `⍺⍺` means convert to/from UCS points)
> > >
> > > > `t ←`*t* gets
> > > > `2 /¨` two of each of
> > > > `⍺⍺` the characters corresponding to the code points
> > > > `2 * ⍳16` 2¹, 2², 2³,... 2¹⁶
> > > >
> > > > `4↑` pad with zeros on the right until length 4
> > > > `C` convert the following UCS characters to code points
> > > > `t ⎕R (1 ⌽ ∪¨t)` regex replace each pair *t* with the unique characters from the next *t* on the right
> > > > `C ⍵~0` the argument (board) without zeros (compacted to the left), then converted to UCS code points
> > >
> > > \[end of function\] applied to each of
> > > `R ⍵`*R* applied to the argument (the board)
> > >
> > > `⍵ ≡ r:` if the argument (the old board state) is identical to *r* (new board state), then:
> > > `∇⍵` call this function on the unmodified argument (because the user made an invalid move), else
> > >
> > > `r` return *r* (the new board state)
> >
> > `} n` \[end of function\] applied to *n* (the new board state), else
> >
> > `'lose'` return "lose"
>
> `} 4 4 ⍴ 0` \[end of function\] applied to a 4-by-4 table of zeros (the initial state)
> 10 votes

# Answer
### GolfScript, 323 characters

```
1,16*{16,{1$=!},.,rand=)/()2++\[]*+4/{.['-----']4*'+'*'++'1/*n+:^\{'|''     ':X'|'+4*n++:Y.@{X\`+-5>'|'\+}%'|'+n+Y+Y+^+}%+puts}:P~"wasd":Q{1$.@{Q\?[{zip}{}{-1%zip-1%}{{-1%}%}]=\1$~{0-[{.2$={+)}*}*0...]4<{1|(}%}%\~}:^~=!},:F{0{;'"#{'9.?rand';STDIN.getc()}"'++~.F\?0<}do^[]*.2048?0<.!{'you win'@@}*}{'you lose'@@*0}if}do 4/P;

```

The keys you have to use are `wasd` but you can change the constant in the code to whatever keys you like. It gracefully ignores any unknown key or illegal move. Unfortunately you have to press enter after each key.

### 256 character solution

```
1,16*{16,{1$=!},.,rand=)/())+\[]*+4/{.{{.9>7*+48+}%n+}%puts}:P~"wasd":Q{1$.@{Q\?[{zip}{}{-1%zip-1%}{{-1%}%}]=\1$~{0-[{.2$={;21+}*}*0...]4<{20%}%}%\~}:^~=!},:F{0{;'"#{'9.?rand';STDIN.getc()}"'++~.F\?0<}do^[]*.10?0<.!{'you win'@@}*}{'you lose'@@*0}if}do 4/P;

```

Here the output is hexadecimal logarithmic, i.e. `0` stands for `.`, `1` for `2`, `2` for `4`, `3` for `8` ... `B` for `2048`. Since we all know hexadecimals and the powers of two this shouldn't be a limitation at all.

*Example run (first moves):*

```
0000
0000
0010
0000
w
0011
0000
0000
0000
a
2000
0000
0001
0000
s
0000
0000
0100
2001
d
0000
0000
1001
0021
w
1022
0000
0001
0000
a
1301
0000
1000
0000
s
0000
1000
0000
2301
d
0000
1001
0000
0231

```
> 21 votes

# Answer
# J - 240 230 216 char

This counts the trailing newline, because you need it to start running the game at the console. Play by typing one of `udlr` and then hitting Enter. Moves that do nothing to the board are handled properly, but the program will get mad at you if you give it any bad input.

```
'you ',>lose`win{~$:@".@('o b=:2 t}^:(1-b-:])s ',' b',~1!:1@1:)`w@.((w=:2048 e.,)+(s d-:s u=:l d=:r(&.|:))*s r-:(s=:[:p(2(=/(0,+/^:)@{.,}.),)/@p=:\:=&0)l=:&.|.r=:"1)(o=:[2:1!:2~4<@":"0])b=:2(t=:(?&#{])[:I.0=,)}4 4$0

```

The readable version and explanation are a little too large to fit comfortably into the post: you can find a writeup at **this link**.

Usage:

```
   'you ',>lose`win{~$:@".@('o b=:2 t}^:(1-b-:])s ',' b',~1!:1@1:)`w@.((w=:2048 e.,)+(s d-:s u=:l d=:r(&.|:))*s r-:(s=:[:p(2(=/(0,+/^:)@{.,}.),)/@p=:\:=&0)l=:&.|.r=:"1)(o=:[2:1!:2~4<@":"0])b=:2(t=:(?&#{])[:I.0=,)}4 4$0
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   2|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
r
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   2|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   2|   0|   0|
+----+----+----+----+
u
+----+----+----+----+
|   0|   2|   0|   2|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   2|
+----+----+----+----+
d
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   2|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   2|   0|   4|
+----+----+----+----+
l
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   2|   0|   0|   0|
+----+----+----+----+
|   0|   0|   2|   0|
+----+----+----+----+
|   2|   4|   0|   0|
+----+----+----+----+
d
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   2|   0|   0|
+----+----+----+----+
|   4|   4|   2|   0|
+----+----+----+----+
r
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   2|
+----+----+----+----+
|   0|   0|   0|   2|
+----+----+----+----+
|   0|   0|   8|   2|
+----+----+----+----+
d
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   0|   0|   0|
+----+----+----+----+
|   0|   2|   0|   2|
+----+----+----+----+
|   0|   0|   8|   4|
+----+----+----+----+

```
> 13 votes

# Answer
# Mathematica, 484 chars

Very ugly.

```
m@l=#//.{{x___,0,a_/;a>0,y___}:>{x,a,0,y},{x___,a_/;a>0,a_,y___}:>{x,2 h@a,0,y}}/.h@a_:>a&;{m@u,m@d,m@r}=Composition[#,m@#2,#]&@@@{{Thread,l},{Reverse,u},{Thread,d}};a=ReplacePart[#,RandomChoice@Position[#,0]->2]&;g=a@ConstantArray[0,{4,4}];EventHandler[Dynamic[GraphicsGrid@Map[Graphics@Text@#&,g,{2}]],(#2<>"ArrowKeyDown":>If[g!=m[#]@g,g=a[m[#]@g];Which[And@@(g==m[#]@g&/@{u,l,r,d}),Print@"you lose",!FreeQ[g,2048],Print@"you win"]])&@@@{{l,"Left"},{r,"Right"},{u,"Up"},{d,"Down"}}]

```

Controlled by arrow keys.

---

Ungolfed:

```
move[Left] = # //. {{x___, 1, a_ /; a > 1, y___} :> {x, a, 1, y},
      {x___, a_ /; a > 1, a_, y___} :> {x, 2 Hold@a, 1, y}} /.
    Hold@a_ :> a &;
move[Up] = Composition[Transpose, move[Left], Transpose];
move[Down] = Composition[Reverse, move[Up], Reverse];
move[Right] = Composition[Transpose, move[Down], Transpose];
addTile = ReplacePart[#, RandomChoice@Position[#, 1] -> 2] &;
keyDown = If[grid != move[#][grid], grid = addTile[move[#][grid]];
    Which[And @@ (grid == move[#][grid] & /@ {Left, Right, Up, Down}),
      status = "Can't move...",
     ! FreeQ[grid, 2048], status = "2048!"]] &;
grid = addTile@ConstantArray[1, {4, 4}];
status = "";
EventHandler[Dynamic[ArrayPlot[Log2@grid/11,
   ColorFunction -> "StarryNightColors",
   ColorFunctionScaling -> False,
   Mesh -> All,
   Epilog -> {MapIndexed[
      Text[Style[#1, "Section"] //. 1 -> "", #2 - {0.5, 0.5}] &,
      Transpose@Reverse@grid, {2}],
     Text[Style[status, "Section"], {2, 2}]}]],
 {"LeftArrowKeyDown" :> keyDown[Left],
  "RightArrowKeyDown" :> keyDown[Right],
  "UpArrowKeyDown" :> keyDown[Up],
  "DownArrowKeyDown" :> keyDown[Down]}]

```
> 10 votes

# Answer
# Delphi XE3 (Waaay to many {whispers} 2.979 bytes -\> ungolfed 4.560 bytes)

I like to call this **"2048 code the novel"**
Used more bytes than I like but it works and it was fun to do.

Im still going to try make it shorter later on.

### Game in progress

### Golfed

```
uses System.SysUtils,Windows;type TDir=(dUp,dDown,dLeft,dRight,dInv);const t='_____________________________';er='|      |      |      |      |';nr='| %s | %s | %s | %s |';br='|______|______|______|______|';fn='%d';procedure mycls;var S:String;H:DWORD;CO:_COORD;begin H:=GetStdHandle(STD_OUTPUT_HANDLE);CO.X:=0;CO.Y:=0;SetConsoleCursorPosition(H,CO);S:=StringOfChar(Chr(32),2000);Writeln(S);SetConsoleCursorPosition(H,CO);end;var a:array[1..4,1..4]of integer;c,rx,ry,i,j:int8;m:string;GameOver,gs:boolean;function hz:boolean;var b,q:int8;begin for b:=1to 4do for q:=1to 4do if a[b,q]=0 then exit(true);end;function HM:boolean;var b,q:int8;begin if hz then exit(true);for b:=1to 4do for q:=1to 4do begin c:=a[b,q];if c in [a[b-1,q],a[b+1,q],a[b,q-1],a[b,q+1]] then result:=true;end;end;procedure rn(out n,m:int8);var z:int8;begin z:=0;repeat n:=Random(4)+1;m:=Random(4)+1;z:=z+1;until(a[n,m]=0)and(z>=3);end;function gn(n:integer):string;begin if n=0 then exit('    ');Result:=IntToStr(n).PadLeft(4,' ');end;procedure pm(d:TDir;score:boolean);var b,q,z:int8;begin case d of dUp:for z:=1to 3do for b:=1to 4do for q:=1to 3do begin if score then begin if a[q,b]=a[q+1,b] then begin a[q,b]:=a[q,b]+a[q+1,b];a[q+1,b]:=0;end;end else if a[q,b]=0 then begin a[q,b]:=a[q+1,b];a[q+1,b]:=0;end;end;dDown:for z:=1to 3do for b:=1to 4do for q:=2to 4do begin if score then begin if a[q,b]=a[q-1,b] then begin a[q,b]:=a[q,b]+a[q-1,b];a[q-1,b]:=0;end;end else if a[q,b]=0 then begin a[q-1,b]:=a[q,b];a[q-1,b]:=0;end;end;dLeft:for z:=1to 3do for q:=1to 4do for b:=1to 3do begin if score then begin if a[q,b]=a[q,b+1] then a[q,b]:=a[q,b]+a[q,b+1];a[q,b+1]:=0;end else if a[q,b]=0 then begin a[q,b]:=a[q,b+1];a[q,b+1]:=0;end;end;dRight:for z:=1to 3do for q:=1to 4do for b:=2to 4do begin if score then begin if a[q,b]=a[q,b-1] then begin a[q,b]:=a[q,b]+a[q,b-1];a[q,b-1]:=0;end;end else if a[q,b]=0 then begin a[q,b]:=a[q,b-1];a[q,b-1]:=0;end;end;end;end;function gd(s:string):TDir;begin s:=lowercase(s);if s='u'then exit(dUp);if s='d'then exit(dDown);if s='l'then exit(dLeft);if s='r'then exit(dRight);exit(dInv)end;procedure dg;var z:int8;begin writeln(t);for z:=1to 4do begin writeln(er);Writeln(Format(nr,[gn(a[z,1]),gn(a[z,2]),gn(a[z,3]),gn(a[z,4])]));Writeln(br);end;end;function hw:boolean;var b,q:int8; begin for b:=1to 4do for q:=1to 4do if a[b,q]=2048 then result:=true;end;function dm:boolean;var d:Tdir;begin d:=gd(m);if d=dInv then if not gs then exit(false)else exit(true);pm(d,false);pm(d,true);pm(d,false);exit(true);end;begin gs:=true;m:='';for j:=1to 4do for i:=1to 4do begin a[i,j]:=0;end;rx:=0;ry:=0;rn(rx,ry);a[rx,ry]:=2;repeat if (dm) then begin if hz then begin rn(rx,ry);a[rx,ry]:=2;end;gs:=false;end;mycls;GameOver:=true;if hw then WriteLn('You have won!')else if HM then begin GameOver:=false;dg;writeln('Direction: [U]=up, [D]=Down, [L]=Left, [R]=Right');readln(m);end else WriteLn('Game Over, no more possible moves :('#13#10'Try again next time')until GameOver;readln;end.

```

### Ungolfed

```
uses
  System.SysUtils,Windows;
type
  TDir=(dUp,dDown,dLeft,dRight,dInv);
const
  t='_____________________________';
  er='|      |      |      |      |';
  nr='| %s | %s | %s | %s |';
  br='|______|______|______|______|';
  fn='%d';
procedure mycls;
var
  S:String;
  H:DWORD;
  CO:_COORD;
begin
  H:=GetStdHandle(STD_OUTPUT_HANDLE);
  CO.X:=0;
  CO.Y:=0;
  SetConsoleCursorPosition(H,CO);
  S:=StringOfChar(Chr(32),2000);
  Writeln(S);
  SetConsoleCursorPosition(H,CO);
end;
var
  a:array[1..4,1..4]of integer;
  c,rx,ry,i,j:int8;
  m:string;
  GameOver,gs:boolean;
function hz:boolean;
var b,q:int8;
begin
  for b:=1to 4do
    for q:=1to 4do
      if a[b,q]=0 then exit(true);
end;
function HM:boolean;
var b,q:int8;
begin
  if hz then exit(true);
  for b:=1to 4do
    for q:=1to 4do
    begin
      c:=a[b,q];
      if c in [a[b-1,q],a[b+1,q],a[b,q-1],a[b,q+1]] then
        result:=true;
    end;
end;
procedure rn(out n,m:int8);
var z:int8;
begin
z:=0;
  repeat
    n:=Random(4)+1;
    m:=Random(4)+1;
    z:=z+1;
  until(a[n,m]=0)and(z>=3);
end;
function gn(n:integer):string;
begin
  if n=0 then exit('    ');
  Result:=IntToStr(n).PadLeft(4,' ');
end;
procedure pm(d:TDir;score:boolean);
var
  b,q,z:int8;
begin
  case d of
    dUp:
      for z:=1to 3do
        for b:=1to 4do
          for q:=1to 3do
          begin
            if score then
            begin
              if a[q,b]=a[q+1,b] then
              begin
                a[q,b]:=a[q,b]+a[q+1,b];a[q+1,b]:=0;
              end;
            end
            else
              if a[q,b]=0 then
              begin
                a[q,b]:=a[q+1,b];a[q+1,b]:=0;
              end;
          end;
    dDown:
      for z:=1to 3do
        for b:=1to 4do
          for q:=2to 4do
          begin
            if score then
            begin
              if a[q,b]=a[q-1,b] then
              begin
                a[q,b]:=a[q,b]+a[q-1,b];a[q-1,b]:=0;
              end;
            end
            else
              if a[q,b]=0 then
              begin
                a[q-1,b]:=a[q,b];
                a[q-1,b]:=0;
              end;
          end;
    dLeft:
      for z:=1to 3do
        for q:=1to 4do
          for b:=1to 3do
          begin
            if score then
            begin
              if a[q,b]=a[q,b+1] then
                a[q,b]:=a[q,b]+a[q,b+1];a[q,b+1]:=0;
            end
            else
              if a[q,b]=0 then
              begin
                a[q,b]:=a[q,b+1];a[q,b+1]:=0;
              end;
          end;
    dRight:
      for z:=1to 3do
        for q:=1to 4do
          for b:=2to 4do
          begin
            if score then
            begin
              if a[q,b]=a[q,b-1] then
              begin
                a[q,b]:=a[q,b]+a[q,b-1];a[q,b-1]:=0;
              end;
            end
            else
              if a[q,b]=0 then
              begin
                a[q,b]:=a[q,b-1];a[q,b-1]:=0;
              end;
          end;
  end;
end;

function gd(s:string):TDir;
begin
  s:=lowercase(s);
  if s='u'then exit(dUp);
  if s='d'then exit(dDown);
  if s='l'then exit(dLeft);
  if s='r'then exit(dRight);
  exit(dInv)
end;
procedure dg;
var z:int8;
begin
  writeln(t);
  for z:=1to 4do
  begin
    writeln(er);
    Writeln(Format(nr,[gn(a[z,1]),gn(a[z,2]),gn(a[z,3]),gn(a[z,4])]));
    Writeln(br);
  end;
end;
function hw:boolean;
var b,q:int8;
begin
  for b:=1to 4do
    for q:=1to 4do
      if a[b,q]=2048 then
        result:=true;
end;
function dm:boolean;
var
  d:Tdir;
begin
  d:=gd(m);
  if d=dInv then if not gs then exit(false)else exit(true);
  pm(d,false);
  pm(d,true);
  pm(d,false);
  exit(true);
end;
begin
    gs:=true;m:='';
    for j:=1to 4do
      for i:=1to 4do
      begin
        a[i,j]:=0;
      end;
   rx:=0;ry:=0;
   rn(rx,ry);
   a[rx,ry]:=2;
  repeat
    if (dm) then
    begin
      if hz then
      begin
        rn(rx,ry);
        a[rx,ry]:=2;
      end;
      gs:=false;
    end;
    mycls;
    GameOver:=true;
    if hw then
      WriteLn('You have won!')
    else if HM then
    begin
      GameOver:=false;
      dg;
      writeln('Direction: [U]=up, [D]=Down, [L]=Left, [R]=Right');
      readln(m);
    end
    else
      WriteLn('Game Over, no more possible moves :('#13#10'Try again next time')
  until GameOver;
  readln;
end.

```
> 8 votes

# Answer
## C (C89 standard), 881 bytes

Use wasd keys to move. Compiles in GCC and clang by default, unless set to C99 standard (I guess). Uses termios.h, worked in Linux and MacOS X. Not sure about Windows.

```
#include<termios.h>
#define R return
#define H while
char t[17],*Q,*W="adws",D,x,y,X;m(x,y){R!D?x+y*4:D==1?3-x+y*4:D==2?y+x*4:y+(3-x)*4;}c(){for(y=0;y<3;++y)for(x=0;x<3;++x){D=t[x+y*4];if(t[x+1+y*4]==D||t[x+4+y*4]==D)x=y=9;}R y>4;}d(){if(strlen(t)==16)R 0;H(t[x=(rand()&15)]);R t[x]=1;}r(x){putchar(x);}b(){y=0;r(10);H(y<21)r(y++%5?45:43);r(10);}f(){for(x=0;x<17;++x)if(X=(t[x]==11))x=32;R x<18;}struct termios z;main(){srand(time(tcgetattr(0,&z)));z.c_lflag&=~ICANON;tcsetattr(0,0,&z);H(f()&&(d()||c())){x=0;H(x<16){if(!(x&3)){b();r('|');}if(y=t[x++])printf("%4u|",1<<y);else printf("    |");}b();r(10);H(!(Q=strchr(W,getchar())));D=Q-W;for(y=0;y<4;++y)for(X=0,x=1;x<4;++x)if(t[m(x,y)]){if(t[m(x,y)]==t[m(X,y)]&&t[m(X,y)]++)t[m(x,y)]=0;X=x;}do{for(y=0;y<4;++y)for(x=0;x<3;++x)if(!t[m(x,y)]&&(X=t[m(x+1,y)])){t[m(x,y)]=X;t[m(x+1,y)]=0;x=y=9;}}H(y>4);}puts(X?"you win":"you lose");}

```

Broken in some lines:

```
#include<termios.h>
#define R return
#define H while
char t[17],*Q,*W="adws",D,x,y,X;m(x,y){R!D?x+y*4:D==1?3-x+y*4:D==2?y+x*4:y+(3-x)*4;}
c(){for(y=0;y<3;++y)for(x=0;x<3;++x){D=t[x+y*4];if(t[x+1+y*4]==D||t[x+4+y*4]==D)x=y=9;}R y>4;}
d(){if(strlen(t)==16)R 0;H(t[x=(rand()&15)]);R t[x]=1;}
r(x){putchar(x);}
b(){y=0;r(10);H(y<21)r(y++%5?45:43);r(10);}
f(){for(x=0;x<17;++x)if(X=(t[x]==11))x=32;R x<18;}
struct termios z;
main(){srand(time(tcgetattr(0,&z)));z.c_lflag&=~ICANON;tcsetattr(0,0,&z);
H(f()&&(d()||c())){x=0;H(x<16){if(!(x&3)){b();r('|');}if(y=t[x++])printf("%4u|",1<<y);else printf("    |");}
b();r(10);H(!(Q=strchr(W,getchar())));D=Q-W;for(y=0;y<4;++y)for(X=0,x=1;x<4;++x)
if(t[m(x,y)]){if(t[m(x,y)]==t[m(X,y)]&&t[m(X,y)]++)t[m(x,y)]=0;X=x;}
do{for(y=0;y<4;++y)for(x=0;x<3;++x)if(!t[m(x,y)]&&(X=t[m(x+1,y)]))
{t[m(x,y)]=X;t[m(x+1,y)]=0;x=y=9;}}H(y>4);}puts(X?"you win":"you lose");}

```

The looks:

```
+----+----+----+----+
|   8|   4|   8|   2|
+----+----+----+----+
|    |  16|    |    |
+----+----+----+----+
|    |   2|    |    |
+----+----+----+----+
|    |    |    |   2|
+----+----+----+----+

```

It can be improved for sure.
> 8 votes

# Answer
# Java: 1346 1269

**Edit** So although this contest is done, sometimes I can't let go when improvements can be made. This version boasts a leaner, meaner, in-place folding function, the eviction of most `boolean` types except where it would be more verbose without them, and slightly smaller cells (4x4 instead of 5x5) to cut out a few extra characters there.

So this was a fun one. Thanks for posting! Ungolfed, this was 2856 bytes, golfed I shrunk it to 1346 bytes. Being Java, I'm not going to win, but I wanted to put in a good showing. Figuring out a "general" roll-up function to handle tile joins and moves was fun -- you can of course check out my "progress" by looking through the commits on my github repository for this solution.

**Golfed:**

```
import java.util.*;class T{public static void main(String[]a){(new T()).s();}int[][]b=new int[4][4];int d,p,i,j,x,y,v,q,r;boolean I,V;void s(){p();do{d();do{char a=(new Scanner(System.in)).nextLine().charAt(0);y=a=='u'?f(0,1):a=='d'?f(1,1):a=='l'?f(0,0):a=='r'?f(1,0):0;}while(y<1);p();}while((x=n())>0);d();c("you "+(x<0?"win":"lose"));}int h(){for(int[]y:b)for(int x:y)if(x<2)return 1;return 0;}int n(){for(y=0;y<4;y++){for(x=0;x<4;x++){i=b[y][x];if(x<3&&i==b[y][x+1]||y<3&&i==b[y+1][x])return 1;if(i>2047)return -1;}}return h();}int f(int w,int z){I=w>0;V=z>0;for(i=d=0;i<4;i++){p=I?3:0;for(j=1;j<4;){v=V?i:j;x=I?3-v:v;v=V?j:i;y=I?3-v:v;q=V?x:p;r=V?p:y;if(b[y][x]==0||p==(V?y:x))j++;else if(b[r][q]==0){d+=b[r][q]=b[y][x];b[y][x]=0;j++;}else if(b[r][q]==b[y][x]){d+=b[r][q]*=2;b[y][x]=0;p+=I?-1:1;j++;}else p+=I?-1:1;}}return d;}int v(){return(new Random()).nextInt(4);}void p(){if(h()<1)return;do{x=v();y=v();}while(b[x][y]>0);b[x][y]=2;}void c(String a){System.out.println(a);}String l(char n,char m){String s=""+n;for(i=0;i<4;i++){for(j=0;j<4;j++)s+=m;s+=n;}return s;}void d(){c(l('+','-'));String p[]=new String[5];for(int[]y:b){p[0]=p[1]=p[3]=l('|',' ');p[2]="";for(x=0;x<4;)p[2]+=String.format("|%4d",y[x++]);p[2]+="|";p[4]=l('+','-');for(String q:p)c(q);}}}

```

**Ungolfed:** (Check my github repository for this project for an updated version, including an assertions-based test for new folding functions)

```
import java.util.*;
class Twe {
    public static void main(String[] a){
        (new Twe()).start();
    }
    int[][] board=new int[4][4];
    void start(){
        int x;
        placeTwo();
        do{
            drawBoard();
            resolve();
            placeTwo();
        }while((x=notDone())>0);
        drawBoard();
        wrapup(x);
    }
    int hasFree(){
        for(int[]y:board)
            for(int x:y)
                if(x<2)return 1;
        return 0;
    }
    int notDone(){
        int moves,x,y;
        for(moves=y=0;y<4;y++){
            for(x=0;x<4;x++){
                else if(x<3&&board[y][x]==board[y][x+1]||
                        y<3&&board[y][x]==board[y+1][x])moves++;
                if(board[y][x]>2047)return -1;
            }
        }
        return hasFree()+moves;
    }
    void wrapup(int k){
        if(k<0){
            chalk("you win",true);
        }else{
            chalk("you lose",true);
        }
    }
    void resolve(){
        do{
            switch((new Scanner(System.in)).nextLine().charAt(0)){
                case 'u':
                    if (fold(false,true)>0)return;
                    break;
                case 'd':
                    if (fold(true, true)>0)return;
                    break;
                case 'l':
                    if (fold(false,false)>0)return;
                    break;
                case 'r':
                    if (fold(true,false)>0)return;
                    break;
                case 'z':
                    board[0][0]=2048; // instant win;
                    return;
            }
        } while(true);
    }
    // false,true  = up
    // true, true  = down
    // false,false = left
    // true, false = right
    int fold(boolean inv, boolean vert){
        int didMove=0;
        int nextSpot,x,y,v,q,r;
        int[][] nb = new int[4][4];
        for(int i=0;i<4;i++){
            nextSpot=inv?3:0;
            for(int j=0;j<4;j++){
                v=vert?i:j;
                x=inv?3-v:v;
                v=vert?j:i;
                y=inv?3-v:v;
                q=vert?x:nextSpot;
                r=vert?nextSpot:y;
                if(board[y][x]>0){
                    if(nb[r][q]<1){
                        nb[r][q]=board[y][x];
                        didMove+=(inv?-1:1)*(vert?y-r:x-q);
                    }else if(nb[r][q]==board[y][x]){
                        nb[r][q]*=2;
                        nextSpot+=inv?-1:1;
                        didMove++;
                    }else{
                        nextSpot+=inv?-1:1;//suckage
                        q=vert?x:nextSpot;
                        r=vert?nextSpot:y;
                        nb[r][q]=board[y][x];
                        didMove+=(inv?-1:1)*(vert?y-r:x-q);
                    }
                }
            }
        }
        board=nb;
        return didMove;
    }
    int vec(){
        return (new Random()).nextInt(4);
    }
    void placeTwo(){
        if (hasFree()<1) return;
        int x,y;
        do{
            x=vec();y=vec();
        }while(board[x][y]>0);
        board[x][y]=2;
    }
    void chalk(String a, boolean nl){
        System.out.print(a+(nl?"\n":""));
    }
    String fill(char node, char mid){
        String str = ""+node;
        for(int i=0;i<4;i++){
            for(int j=0;j<5;j++)
                str+=mid;
            str+=node;
        }
        return str;
    }
    void drawBoard(){
        chalk(fill('+','-'),true);
        String p[] = new String[6];
        for(int[]y:board){
            p[0]=p[1]=p[3]=p[4]=fill('|',' ');
            p[2]="";
            for(int x=0;x<4;){
                p[2]+=adjust(y[x++]);
            }
            p[2]+="|";
            p[5]=fill('+','-');
            for (String q:p){
                chalk(q,true);
            }
        }
    }
    String adjust(int a){
        return String.format("|%5d",a);
    }
}

```

Using the program is simple. To build and run:

```
javac T.java
java T

```

Press `u` to fold up, `r` to fold right, `d` to fold down, `l` to fold left. Any other key is ignored, invalid (no result) moves are ignored. Being Java, press `enter` after each key to flush the line buffer. As required by the rules, if you win the program outputs `you win`, if you lose the program outputs `you lose`. New `2`'s are placed randomly in the open tiles. Merges follow the stated rules. Cells are 4x4 characters, with a border surrounding each cell. Of course, leave me a comment if I've messed something up and I'll be certain to fix it.

Example output:

```
$ java T
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
u
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   2|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
l
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
u
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   4|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   2|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
l
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   4|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   4|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   2|
|    |    |    |    |
+----+----+----+----+
u
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   8|   2|   0|   2|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
l
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   8|   4|   2|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
l
u
d
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   2|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   8|   4|   2|   0|
|    |    |    |    |
+----+----+----+----+
d
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   2|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   8|   4|   4|   0|
|    |    |    |    |
+----+----+----+----+
l
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   2|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   8|   8|   0|   0|
|    |    |    |    |
+----+----+----+----+
l
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   2|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   2|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|  16|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
d
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   2|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   4|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|  16|   2|   0|   0|
|    |    |    |    |
+----+----+----+----+
d
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   0|   0|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|   4|   2|   0|   0|
|    |    |    |    |
+----+----+----+----+
|    |    |    |    |
|    |    |    |    |
|  16|   4|   0|   0|
|    |    |    |    |
+----+----+----+----+

```
> 6 votes

# Answer
### Lua, ~~622~~ ~~616~~ ~~615~~ ~~612~~ ~~592~~ ~~590~~ 575 bytes

Queries stdin for 1,2,3,4 correlating with left, down, right, up (made for numpad input); crashes if you give it bad input.

Blank squares are printed as '0's.

```
b={('\0'):rep(16):byte(1,16)}c=1 a=print h=unpack while{}do if c then c=z
e={}for i=1,16 do e[#e+1]=0==b[i]and i or z end _=#e==0 and
a'you lose'b[e[math.random(#e)]]=2 l=('+----'):rep(4)..'+\n'm=l:gsub('-',' ')for
i=1,13,4 do a(l..m..m..m..('+%4d+%4d+%4d+%4d+'):format(h(b,i)))end a(l)end c=z
u,v,w=h({4,1,-4,1,-4,16,4,-1,1,1,4,-4},3*io.read()-2)for i=1,4 do o=-1 for j=2,4
do if 0~=b[u*i+v*j+w]then for k=1-j,o do p=u*i-v*k+w q=p+v r=b[p]if r==0 then
b[p]=b[q]b[q]=r c=1 o=k elseif r==b[q]then _=r==1024 and a'you win'b[p]=r*2
b[q]=0 c=1 o=k-1 break end end end end end end

```

Example output:

```
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   2+   0+   0+   0+
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   0+   0+   0+   0+
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   0+   0+   0+   0+
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   0+   0+   0+   0+
+----+----+----+----+

2
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   0+   2+   0+   0+
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   0+   0+   0+   0+
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   0+   0+   0+   0+
+----+----+----+----+
+    +    +    +    +
+    +    +    +    +
+    +    +    +    +
+   2+   0+   0+   0+
+----+----+----+----+

```
> 3 votes

# Answer
# Clojure: 599

run it in a REPL

**golfed**

```
(defn i[b](let[f(into[](flatten b))z(seq(keep-indexed #(when(zero? %2)%1)f))]
(cond(some #{2048}f)(pr "you win")(empty? z)(pr "game over"):e(partition 4
(assoc f(rand-nth z)2)))))(def r #(remove zero? %))(loop[b(i (partition 4
(repeat 16 0)))](when((fn[v](doseq[l(for[a v](apply str(map #(format "%5d " %)a)))]
(println l "\n"))v)b)(-> b((apply comp(assoc(into[](repeat 5(fn[v]
(map(fn[n](map #(nth % n)v))[3 2 1 0]))))({"h"4 "k"3 "l"2 "j"1}(read-line))
(partial map(comp #(take 4(concat % [0 0 0 0]))(fn[v]
(r(reduce #(let[l(last %1)](if(= %2 l)(conj(pop %1)(+ l %2) 0)
(conj %1 %2)))[]v)))r)))))i recur)))

```

**ungolfed**

```
(defn insert-2 [board]
  (let [flat (into [] (flatten board))
        zero-indices (seq (keep-indexed
                       #(when (zero? %2) %1)
                       flat))]
    (cond
      (some #{2048} flat) (pr "you win")
      (empty? zero-indices) (pr "game over")
      :else (partition 4 (assoc flat (rand-nth zero-indices) 2)))))

(defn rotate [board]
  (map
    (fn [n]
        (map #(nth % n)
             board))
    [3 2 1 0]))

(defn remove-zeros [row]
 (remove zero? row))

(defn fill [row]
 (take 4 (concat row [0 0 0 0])))

(defn sum-up [acc x]
  (let [l (last acc)]
    (if (= x l)
      (conj (pop acc) (+ l x) 0)
      (conj acc x))))

(defn sum-pairs [v]
  (remove-zeros (reduce sum-up [] v)))

(defn render [v]
  (doseq [line (for [row v]
                 (apply str (map #(format "%5d " %) row)))]
    (println line "\n")) v)

(defn slide [board]
 (map (comp
        fill
        sum-pairs
        remove-zeros
        ) board))

(loop [board (insert-2 (partition 4 (repeat 16 0)))]
  (when (render board)
    (let [input ({"h" 4 "k" 3 "l" 2 "j" 1} (read-line))
          command (apply comp
                         (assoc (into [] (repeat 5 rotate))
                                input slide))] ;; (comp rotate rotate slide rotate rotate)
      (-> board command insert-2 recur))))

```
> 1 votes

---
Tags: code-golf, game, sliding-puzzle
---


title: Female and Male Sequences

text:
# Question
Title: Female and Male Sequences
*This question is probably harder than all of those "generate a sequence of numbers" tasks, because this requires TWO sequences working in unison.*

*Really looking forward to the answers!*

In his book "*Gödel, Escher, Bach: An Eternal Golden Braid*", Douglas Hofstadter has a quite few sequences of numbers inside, all of them rely on the previous term in some way. For information on all of the sequences, see this Wikipedia page.

One pair of sequences that's really interesting is the Female and Male sequences, which are defined like so:

for `n > 0`.

Here's the Female sequence and the Male sequence.

Your task is, when given an integer `n` as input, return a list of the Female sequence and the Male sequence, with the amount of terms equal to `n`, in two lines of output, with the Female sequence on the first line and the Male sequence on the second.

Sample inputs and outputs: Input: `5` Output: `[1, 1, 2, 2, 3]` `[0, 0, 1, 2, 2]`

Input: `10` Output: `[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]` `[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]`

NOTE: The separation between lists signifies a line break.

This is code-golf, so shortest code in bytes wins. Also, put an explanation in as well for your code.

## Leaderboard

```
var QUESTION_ID=80608,OVERRIDE_USER=49561;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 4 votes
# Jelly, ~~22~~ 20 bytes

```
ṙṪḢạL}ṭ
çƓḤ¤Ð¡1ṫ-Ṗ€G

```

Try it online!

### How it works

```
çƓḤ¤Ð¡1ṫ-Ṗ€G  Main link. No user arguments. Left argument defaults to 0.
   ¤          Combine the two links to the left into a niladic chain.
 Ɠ              Read an integer from STDIN.
  Ḥ             Unhalve/double it.
ç   Ð¡1       Call the helper link that many times. Return all results.
              In the first call, the left and right argument are 0 and 1 resp.
              After each iteration, the left argument is set to the return value
              and the right argument to the prior value of the left one.
       ṫ-     Tail -1; keep the last two items of the list of results.
         Ṗ€   Discard the last item of each list.
           G  Grid; format the pair of lists.

ṙṪḢạL}ṭ       Helper link. Arguments: x, y (lists)

ṙ             Rotate x k units to the left, for each k in y.
 Ṫ            Tail; extract the last rotation.
  Ḣ           Head; extract the last element.
              This essentially computes x[y[-1]] (Python notation), avoiding
              Jelly's 1-based indexing.
    L}        Yield the length of y.
   ạ          Take the absolute difference of the results to both sides.
      ṭ       Tack; append the difference to y and return the result.

```

# Answer
> 14 votes
# Julia, ~~52~~ 48 bytes

```
x->[n÷φ|(5n^2|4∈(2:3n).^2)for| =(+,-),n=1:x]

```

Try it online!

### Background

In On Hofstadter's married functions, the author shows that

where **φ** denotes the golden ratio,

and **Fn** denotes the **n**th Fibonacci number.

Furthermore, in Advanced Problems and Solutions, H-187: Fibonacci is a square, the proposer shows that

where **Ln** denotes the **n**th Lucas number, and that – conversely – if

then **n** is a Fibonacci number and **m** is a Lucas number.

From this, we deduce that

whenever **n \> 0**.

### How it works

Given input **x**, we construct a **2** by **x** matrix, where **|** is addition in the first column and subtraction in the second, and **n** iterates over the integers between **1** and **x** in the rows.

The first term of both **F(n - 1)** and **M(n - 1)** is simply `n÷φ`.

We compute **δ(n)** and **ε(n)** by calculating **5n² | 4** and testing if the result belongs to the array of squares of the integers between **2** and **3n**. This tests both for squareness and, since **1** is not in the range, for **n \> 1** if **|** is subtraction.

Finally we add or subtract the Boolean resulting from `5n^2|4∈(2:3n).^2` to or from the previously computed integer.

# Answer
> 11 votes
# Python 2, ~~79~~ 70 bytes

```
a=0,;b=1,
exec"a,b=b,a+(len(a)-b[a[-1]],);"*~-input()*2
print b,'\n',a

```

Iterative rather than recursive, because why not. The first line has a trailing space - if that's not okay it can be fixed for an extra byte. -9 bytes thanks to @Dennis.

Here are some combined lambdas which didn't really help:

```
f=lambda n,k:n and n-f(f(n-1,k),k^1)or k
f=lambda n,k:[k][n:]or f(n-1,k)+[n-f(f(n-1,k)[-1],k^1)[-1]]

```

Both take `n` and a parameter `k` either 0 or 1, specifying male/female. The first lambda returns the nth element, and the second lambda returns the first n elements (with exponential runtime).

# Answer
> 9 votes
# MATL, 23 bytes

```
1Oiq:"@XJth"yy0)Q)_J+hw

```

**Try it online!**

### Explanation

This works iteratively. Each sequence is kept in an array. For each index *n* the new term of each sequence is computed and attached to the corresponding array. A `for` loop with *N*−1 terms is used, where *N* is the input number.

The update for sequence M needs to be done first. This is because sequence F is always greater than or equal to sequence M for the same index, so if we tried to update F first we would need a term of M not computed yet.

The two update equations are the same interchanging F and M. Thus the code for the updating is reused by applying a `for` loop with two iterations and swapping the sequences in the stack.

```
1        % Push 1: seed for F sequence
O        % Push 0: seed for M sequence
iq:      % Input N. Generate range [1 2 ... N-1]
"        % For each (i.e. iterate N-1 times)
  @      %   Push current index, n (starting at 1 and ending at N-1)
  XJ     %   Copy to clipboard J
  th     %   Duplicate and concatenate. This generates a length-2 array
  "      %   For each (i.e. iterate twice)
    yy   %   Duplicate top two elements, i.e. F and M sequences
    0)   %     In the *first* iteration: get last entry of M, i.e M(n-1)
    Q)   %     Add 1 and index into F. This is F(M(n-1))
    _J+  %     Negate and add n. This is n-F(M(n-1)), that is, M(n)
    h    %     Concatenate to update M
    w    %     Swap top two elements, to bring F to top.
         %     In the *second* iteration the procedure is repeated to update F,
         %     and then the top two elements are swapped to bring M to top again,
         %     ready for the next iteration of the outer loop
         %   End for implicitly
         % End for implicitly
         % Display implicitly from bottom to top: first line is F, second is M

```

# Answer
> 6 votes
# J, 47 bytes

```
f=:1:`(-m@f@<:)@.*
m=:0:`(-f@m@<:)@.*
(f,:m)@i.

```

Uses the recursive definition. The first two lines define the verbs `f` and `m` which represent the female and male functions, respectively. The last line is a verb that takes a single argument `n` and outputs the first `n` terms of the female and male sequences.

## Usage

```
   (f,:m)@i. 5
1 1 2 2 3
0 0 1 2 2
   (f,:m)@i. 10
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6

```

# Answer
> 6 votes
## JavaScript (ES6), 75 bytes

```
g=n=>--n?([f,m]=g(n),m=[...m,n-f[m[n-1]]],[[...f,n-m[f[n-1]]],m]):[[1],[[0]]

```

I could save 2 bytes if I was allowed to return the Male sequence first:

```
g=n=>--n?([f,m]=g(n),[m=[...m,n-f[m[n-1]]],[...f,n-m[f[n-1]]]]):[[1],[[0]]

```

# Answer
> 6 votes
## Haskell, 57 bytes

```
l#s=scanl(\a b->b-l!!a)s[1..]
v=w#1
w=v#0
(<$>[v,w]).take

```

Usage example: `(<$>[v,w]).take $ 5` -\> `[[1,1,2,2,3],[0,0,1,2,2]]`

The helper function `#` builds an infinite list with starting value `s` and a list `l` for looking up all further elements (at index of the previous value). `v = w#1` is the female and `w = v#0` the male sequence. In the main function we take the first `n` elements of both `v` and `w`.

# Answer
> 4 votes
## Python 2, 107 bytes

```
F=lambda n:n and n-M(F(n-1))or 1
M=lambda n:n and n-F(M(n-1))
n=range(input())
print map(F,n),'\n',map(M,n)

```

Try it online

Larger input values cause a RuntimeError (too much recursion). If this is a problem, I can write a version where the error doesn't happen.

# Answer
> 4 votes
## Clojure, ~~132~~ 131 bytes

```
(fn [n](loop[N 1 M[0]F[1]](if(< N n)(let[M(conj M(- N(F(peek M))))F(conj F(- N(M(peek F))))](recur(inc N)M F))(do(prn F)(prn M)))))

```

Simply builds the sequences iteratively up from zero to n.

Ungolfed version

```
(fn [n]
  (loop [N 1 M [0] F [1]]
    (if (< N n)
      (let [M (conj M (- N (F (peek M))))
            F (conj F (- N (M (peek F))))]
        (recur (inc N) M F))
      (do
        (prn F)
        (prn M)))))

```

# Answer
> 4 votes
# Julia, 54 bytes

```
f(n,x=1,y=0)=n>1?f(n-.5,[y;-x[y[k=end]+1]+k],x):[x y]'

```

Try it online!

# Answer
> 3 votes
# Pyth, 24 bytes

It is probably impossible to use `reduce` to reduce the byte-count.

Straightforward implementation.

```
L&b-b'ytbL?b-by'tb1'MQyM

```

Try it online!

## How it works

```
L&b-b'ytb  defines a function y, which is actually the male sequence.

L          def male(b):
 &b            if not b: return b
   -b          else: return b-
     'ytb            female(male(b-1))

L?b-by'tb1 defines a function ', which is actually the female sequence.

L          def female(b):
 ?b            if b:
   -by'tb          return b-male(female(b-1))
         1     else: return 1

'MQ        print(female(i) for i from 0 to input)
yMQ        print(male(i) for i from 0 to input)

```

# Answer
> 3 votes
# Brachylog, 65 bytes

```
:{:1-:0re.}fL:2aw,@Nw,L:3aw
0,1.|:1-:2&:3&:?--.
0.|:1-:3&:2&:?--.

```

My attempt at combining both predicates for male and female into one actually made the code longer.

You could use the following one liner which has the same number of bytes:

```
:{:1-:0re.}fL:{0,1.|:1-:2&:3&:?--.}aw,@Nw,L:{0.|:1-:3&:2&:?--.}aw

```

**Note**: This works with the Prolog transpiler, not the old Java one.

### Explanation

Main predicate:

```
:{:1-:0re.}fL                Build a list L of integers from 0 to Input - 1
             :2aw            Apply predicate 2 to each element of L, write the resulting list
                 ,@Nw        Write a line break
                     ,L:3aw  Apply predicate 3 to each element of L, write the resulting list

```

Predicate 2 (female):

```
0,1.                         If Input = 0, unify Output with 1
    |                        Else
     :1-                     Subtract 1 from Input
        :2&                  Call predicate 2 with Input - 1 as argument
           :3&               Call predicate 3 with the Output of the previous predicate 2
              :?-            Subtract Input from the Output of the previous predicate 3
                 -.          Unify the Output with the opposite of the subtraction

```

Predicate 3 (male):

```
0.                           If Input = 0, unify Output with 0
  |                          Else
   :1-                       Subtract 1 from Input
      :3&                    Call predicate 3 with Input - 1 as argument
         :2&                 Call predicate 2 with the Output of the previous predicate 3
            :?-              Subtract Input from the Output of the previous predicate 3
               -.            Unify the Output with the opposite of the subtraction

```

# Answer
> 3 votes
# Ruby, ~~104~~ ~~92~~ ~~97~~ 82 bytes

```
f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}

```

**Edit:** `f` and `m` are now one function thanks to HopefullyHelpful. I changed the second function to print `f` then `m`. The whitespace after `p` is significant, as otherwise the function prints `(0...n)` instead of the result of `map`.

The third function prints first an array of the first n terms of `f`, followed by an array of the first n terms of `m`

These functions are called like this:

```
> f=->n,i{n>0?n-f[f[n-1,i],-i]:i>0?1:0}
> s=->n{[1,-1].map{|k|p (0...n).map{|i|f[i,k]}}}
> s[10]
[1, 1, 2, 2, 3, 3, 4, 5, 5, 6]
[0, 0, 1, 2, 2, 3, 4, 4, 5, 6]

```

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~45~~ 25 bytes

Anonymous tacit function. Requires `⎕IO←0`, which is standard on many APL systems.

```
1 0∘.{×⍵:⍵-(~⍺)∇⍺∇⍵-1⋄⍺}⍳

```

Try it online!

This works by combining *F* and *M* into a single dyadic function with a Boolean left argument which selects the function to apply. We use 1 for *F* and 0 for *M* so that we can use this selector as return value for *F* (0) and *M* (0). We then observe that both functions need to call themselves first (on the argument minus one) and then the other function on the result of that, so first we recurse with the given selector and then with the logically negated selector.

**ɩ**ndices; zero through argument minus one

`1 0∘.{``}` outer (Cartesian) "product" (but with the below function instead of multiplication) using `[1,0]` as left arguments () and the indices as right arguments ():

`×⍵` if the right argument is strictly positive (lit. the sign of the right argument):

`⍵-1` subtract one from the right argument

`⍺∇` call self with that as right argument and the left argument as left argument

`(~⍺)∇` call self with that as right arg and the logical negation of the left arg as left arg

`⍵-` subtract that from the right argument and return the result

else:

return the left argument

# Answer
> 3 votes
# Pyth, 23 bytes

```
jCuaG-LHtPs@LGeGr1Q],1Z

```

Try it online: Demonstration

### Explanation:

```
jCuaG-LHtPs@LGeGr1Q],1Z

  u                ],1Z    start with G = [[1, 0]]
                           (this will be the list of F-M pairs)
  u             r1Q        for each H in [1, 2, ..., Q-1]:
              eG              take the last pair of G [F(H-1), M(H-1)]
           @LG                lookup the pairs of these values:
                              [[F(F(H-1)), M(F(H-1))], [F(M(H-1)), M(M(H-1))]]
          s                   join them:
                              [F(F(H-1)), M(F(H-1)), F(M(H-1)), M(M(H-1))]
        tP                    get rid of the first and last element:
                              [M(F(H-1)), F(M(H-1))]
     -LH                      subtract these values from H
                              [H - M(F(H-1)), H - F(M(H-1))]
   aG                         and append this new pair to G
jC                         at the end: zip G and print each list on a line

```

Alternative solution that uses a function instead of reduce (also 23 bytes):

```
L?>b1-LbtPsyMytb,1ZjCyM

```

# Answer
> 2 votes
## Perl 5.10, ~~85~~ 80 bytes

Meh, dunno if I have more ideas to golf this down...

```
@a=1;@b=0;for(1..<>-1){push@a,$_-$b[$a[$_-1]];push@b,$_-$a[$b[$_-1]]}say"@a\n@b"

```

Try it online !

I had to add `use 5.10.0` on Ideone in order for it to accept the `say` function, but it doesn't count towards the byte count.

It's a naive implementation of the algorithm, `@a` being the "female" list and `@b` the "male" list.

Crossed-out 85 is still 85 ?

# Answer
> 2 votes
# ES6, ~~89~~ ~~85~~ 83 bytes

2 bytes saved thanks to @Bálint

```
x=>{F=[n=1],M=[0];while(n<x){M.push(n-F[M[n-1]]);F.push(n-M[F[n++-1]])}return[F,M]}

```

Naïve implementation.

Explanation:

```
x => {
    F = [n = 1], //female and term number
    M = [0]; //male
    while (n < x) {
        M.push(n - F[M[n - 1]]); //naïve
        F.push(n - M[F[n++ - 1]]); //post-decrement means n++ acts as n in the calculation
    }
    return [F, M];
}

```

# Answer
> 2 votes
## Mathematica, ~~69~~ 62 bytes

*Thanks to Sp3000 for suggesting a functional form which saved 14 bytes.*

```
k_~f~0=1-k
k_~f~n_:=n-f[1-k,f[k,n-1]]
Print/@Array[f,{2,#},0]&

```

This defines a named helper function `f` and then evaluates to an unnamed function which solves the actual task of printing both sequences.

# Answer
> 2 votes
# Java, 169 bytes total

```
int f(int n,int i){return n>0?n-f(f(n-1,i),-i):i>0?1:0;}void p(int n,int i){if(n>0)p(n-1,i);System.out.print(i==0?"\n":f(n,i)+" ");}void p(int n){p(n,1);p(0,0);p(n,-1);}

```

# F(), M() 56 bytes

```
int f(int n,int i){
    return n>0?n-f(f(n-1,i),-i):i>0?1:0;
}

```

# recursive-for-loop and printing 77 Bytes

```
void p(int n,int i) {
    if(n>0) {
        p(n-1,i);
    }
    System.out.print(i==0?"\n":f(n,i)+" ");
}

```

# outputting the lists in two different lines 37 Bytes

```
void p(int n) {
    p(n,1);
    p(0,0);
    p(n,-1);
}

```

input : p(`10`)
output :

```
1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9
0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9

```

# Answer
> 1 votes
# C, 166 Bytes

```
#define P printf
#define L for(i=0;i<a;i++)
f(x);m(x);i;c(a){L P("%d ",f(i));P("\n");L P("%d ",m(i));}f(x){return x==0?1:x-m(f(x-1));}m(x){return x==0?0:x-f(m(x-1));}

```

Usage:

```
main()
{
    c(10);
}

```

Output:

```
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6

```

Ungolfed (331 Bytes)

```
#include <stdio.h>

int female(int x);
int male(int x);
int i;
int count(a){
    for(i=0;i<a;i++){
        printf("%d ",female(i));
    }
    printf("\n");
    for(i=0;i<a;i++){
        printf("%d ",male(i));
    }
}
int female (int x){
    return x==0?1:x-male(female(x-1));
}
int male(x){
    return x==0?0:x-female(male(x-1));
}
int main()
{
    count(10);
}

```

# Answer
> 0 votes
# 8th, 195 bytes

**Code**

```
defer: M
: F dup not if 1 nip else dup n:1- recurse M n:- then ;
( dup not if 0 nip else dup n:1- recurse F n:- then ) is M
: FM n:1- dup ( F . space ) 0 rot loop cr ( M . space ) 0 rot loop cr ;

```

**Usage**

```
ok> 5 FM
1 1 2 2 3
0 0 1 2 2

ok> 10 FM
1 1 2 2 3 3 4 5 5 6
0 0 1 2 2 3 4 4 5 6

```

**Explanation**

This code uses **recursion** and **deferred** **word**

`defer: M` \- The word `M` is declared to be defined later. This is a ***deferred word***

`: F dup not if 1 nip else dup n:1- recurse M n:- then ;` \- Define `F` ***recursively*** to generate female numbers according definition. Please note that `M` has not yet been defined

`( dup not if 0 nip else dup n:1- recurse F n:- then ) is M` \- Define `M` ***recursively*** to generate male numbers according definition

`: FM n:1- dup ( F . space ) 0 rot loop cr ( M . space ) 0 rot loop cr ;` \- Word used to print sequences of female and male numbers

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


title: Happy New Year 0409!

text:
# Question
Title: Happy New Year 0409!
The date 0409·01·MO is New Year’s Day in the Ceres Calendar. Wish everyone and everything in the Asteroid Belt, Jupiter, Saturn and beyond a belated Happy New Year by writing a program to convert Julian Dates (JD) to Ceres Dates using these helpful landmarks:

```
                                                JD           CMJD      Ceres Date (& Time*)  ISO 8601 (approx.)
Start of Ceres calendar                     2309103.500         0.000   0000·01·MO 00:00     1610
Start of JD calendar                              0.000  -2309103.500  -6344·17·MO           4713 BCE
Earliest recorded eclipse                    501822.000  -1807281.500  -4966·49·SU           3339 BCE
Battle of Megiddo                           1189360.000  -1119743.500  -3077·41·FR           1456 BCE
Battle of Halys                             1507900.000   -801203.500  -2202·47·WE            584 BCE
Alexander the Great (b)                     1591596.000   -717507.500  -1972·43·SU            355 BCE
Crab Nebula supernova                       2106216.000   -202887.500  -0558·33·MO           1054
Discovery of Galilean moons                 2309107.000         3.500   0000·01·TH           1610
Discovery of Titan by Huygens               2325616.000     16512.500   0045·19·SU           1655
Discovery of Uranus by Herschel             2371629.000     62525.500   0171·41·TU           1781
Discovery of Ceres by Piazzi                2378862.000     69758.500   0191·34·TH           1801
Discovery of Pallas by Olbers               2379313.000     70209.500   0192·46·SU           1802
Discovery of Juno by Harding                2380201.000     71097.500   0195·17·SA           1804
Discovery of Vesta by Olbers                2381140.000     72036.500   0197·47·SU           1807
Discovery of Astraea by Hencke              2395274.000     86170.500   0236·39·MO           1845
Discovery of Neptune by Galle & Le Verrier  2395563.000     86459.500   0237·28·WE           1846
First Nobel Prizes awarded                  2415729.000    106625.500   0292·49·TU           1901-12-10
Archduke Franz Ferdinand (d)                2420312.000    111208.500   0305·27·SU           1914-06-28
Discovery of Pluto by Tombaugh              2426054.000    116950.500   0321·16·TU           1930-03-18
Hiroshima bombing                           2431673.469    122569.969   0336·38·SU 23:15     1945-08-05
Dawn probe started exploration of Ceres     2457088.028    147984.528   0406·29·FR 12:40     2015-03-06
Gravitational waves first detected by LIGO  2457279.910    148176.410   0407·05·MO 09:50     2015-09-14
New Year’s Day 0409                         2457980.000    148876.500   0409·01·MO 12:00     2017-08-14

```

`CMJD` stands for Ceres Modified JD, a convenient offset. `CMJD` is related to `JD` by the formula:

```
CMJD = JD - 2309103.5

```

The Ceres Calendar has 52 weeks (01 - 52) of seven days, with Monday (MO) as the first day of the week, the rest are TU, WE, TH, FR, SA, & SU and the time synchronized to UTC formatted as HH:MM or HH:MM:SS. There are no leap days in the Ceres Calendar.

* The Ceres Dates lacking times are only known to the day, so as a convention the middle of the day `12:00` is chosen as the time. Displaying `12:00` for these cases is perfectly acceptable.

Note that the Calendar starts on the Monday before Galileo discovered his satellites, that’s to have the start of the calendar on a Monday to correspond to the ISO 8601 start of the week. The discovery of the Galilean Satellites is more important to them than the Discovery of Ceres but not so important as to mess up the start of the week or the start of the year! That’s just how they roll!

Your program must convert `JD ≥ 0.000` to `Ceres Date` in the format above, using `-` (U+2212 MINUS SIGN) and `·` (U+00B7 MIDDLE DOT) as required. Especially for those using ASCII-only languages, you can substitute `~` (U+007E TILDE) and `*` (U+002A ASTERISK) for the minus sign and middle dot, respectively. The format for dates beyond `9999·52·SU` is undefined.

Here’s a handy page to convert to Julian Dates and lots of other useful information.

This is , so shortest answer in bytes wins.

# Answer
# Jelly, 92 bytes

*Definitely beatable by languages with built-in time-formatting or even just better string-formatting.*

```
%1×⁽¢Ẓd60
_“#ḟf’_.µd364Ad0¦7Ẏ;ÇḞ‘2¦ị3¦“TUWETHFRSASUMO”s2¤Ṛ€o0ẋ⁽¡Ḳḃ4¤¤U⁽œọ;“ṢṢ :‘¤Ọ¤żFḊ⁸Ṡ>-¤¡

```

A full program accepting a single argument (decimal number representation) and printing the result.

**Try it online!**

### How?

```
%1×⁽¢Ẓd60 - Link 1, get hours and minutes portion of days: number (of days)
%1        - modulo by one - get the fractional part
   ⁽¢Ẓ    - base 250 number = 1440 (that's 60*24)
  ×       - multiply
      d60 - divmod 60 (integer divide by sixty and yield result and remainder)

_“#ḟf’_.µd364Ad0¦7Ẏ;ÇḞ‘2¦ị3¦“TUWETHFRSASUMO”s2¤Ṛ€o0ẋ⁽¡Ḳḃ4¤¤U⁽œọ;“ṢṢ :‘¤Ọ¤żFḊ⁸Ṡ>-¤¡
          - Main link: number, JulianDate -- breaking this down into parts...

_“#ḟf’_.µ - Main link part 1 (get the CMJD): number, JulianDate
 “#ḟf’    - base 250 number = 2309103
_         - subtract from JulianDate
      _.  - subtract a half
        µ - monadic chan separation, call that CMJD

d364Ad0¦7Ẏ;ÇḞ‘2¦ - Main link part 2 (get the numeric parts): number, CMJD
d364             - divmod 364 (integer divide by 364 and yield result and remainder)
    A            - absolute value (removes the sign from the year part)
       ¦         - sparse application:
      0          - ...to index: zero (rightmost - the remainder)
     d  7        - ...action: divmod 7 (integer divide by 7 and yield result and remainder)
         Ẏ       - tighten (to a list of three items)
           Ç     - call the last link (1) as a monad with argument CMJD
          ;      - concatenate (now we have floats [abs(Y.0), W.0, D.0, H.0, M.x])
            Ḟ    - floor (vectorises) (yielding ints [abs(Y), W, D, H, M]
               ¦ - sparse application:
              2  - ...to index: 2 (W)
             ‘   - ...action: increment (CD weeks are 1-indexed, W is 0 indexed)

ị3¦“TUWETHFRSASUMO”s2¤ - Main link part 3 (make the day-string): result of part 2
  ¦                    - sparse application:
 3                     - ...to index: 3 (D)
ị                      - ...action: index into:
                     ¤ -   nilad followed by link(s) as a nilad:
   “TUWETHFRSASUMO”    -     list of characters = "TUWETHFRSASUMO"
                   s2  -     split into chunks of length two
                       -     (note: D=0 yields "MO" due to 1-based & modular indexing)

Ṛ€o0ẋ⁽¡Ḳḃ4¤¤U - Main link part 4 (pad parts with zeros): result of part 3
Ṛ€            - reverse each (implicit decimal-list, so reverse of 289 is [9,8,2])
           ¤  - nilad followed by link(s) as a nilad:
   0          -   zero
          ¤   -   nilad followed by link(s) as a nilad:
     ⁽¡Ḳ      -     base 250 number = 1178
        ḃ4    -     convert to bijective-base 4 = [4,2,1,2,2]
    ẋ         -   repeat = [[0,0,0,0],[0,0],[0],[0,0],[0,0]]
  o           - logical or (vectorises) (yielding the reversed zero padded entries)
            U - upend (reverse each - everything is already a list so not Ṛ€)
              -   now we have something like: [[Ya,Yb,Yc,Yd],[Wa,Wb],['Da','Db'],[ha,hb],[ma,mb]]

⁽œọ;“ṢṢ :‘¤Ọ¤ż - Main link part 5 (include the separators): result of part 4
            ¤  - nilad followed by link(s) as a nilad:
          ¤    -   nilad followed by link(s) as a nilad:
⁽œọ            -     base 250 literal = 8722
    “ṢṢ :‘     -     code-page indices = [183,183,32,58]
   ;           -     concatenate = [8722,183,183,32,58]
           Ọ   -   covert ordinals to characters = "−·· :"
             ż - zip with the result from part 4, i.e. [['−',[Ya,Yb,Yc,Yd]],['·',[Wa,Wb]],['·',['Da','Db']],[' ',[ha,hb]],[':',[ma,mb]]]

FḊ⁸Ṡ>-¤¡ - Main link part 6 (remove the sign if need be): result from part 5
F        - flatten the result from part 5 into a single list: ['−',Ya,Yb,Yc,Yd,'·',Wa,Wb,'·','Da','Db',' ',ha,hb,':',ma,mb]
       ¡ - repeat:
 Ḋ       - ...action: dequeue (remove first element)
      ¤  - ...number of times: nilad followed by link(s) as a nilad:
  ⁸      -   chain's left argument = CMJD
   Ṡ     -  sign (-1 if less than 0, 0 if equal to 0, 1 if greater than 0)
    >-   -  greater than -1?
         - implicit print

```
> 3 votes

# Answer
# Ruby, 120 bytes

Despite being a language with built-in time formatting and string formatting, I still can't beat the Jelly answer...

```
->n{n-=2309103.5;Time.at((n%7+4)*86400).strftime('%04d·%02d·%%^a %%H:%%M'%[n/364,n%364/7+1]).sub(/. /,' ').tr ?-,?−}

```

Try it online!
> 1 votes

---
Tags: code-golf, date
---


title: "Hello, World!" (Robbers' thread)

text:
# Question
Title: "Hello, World!" (Robbers' thread)
*This is the robbers' thread. The cops' thread is here.*

Your challenge is to take an uncracked submission from the cops' thread and find, for what input or inputs, the program will print `Hello, World!` and a newline. Capitalization, spacing, and punctuation must be exact.

Please comment on the cop's submission when you've cracked their code.

# Answer
# Bash by Sisyphus

Original code:

```
[[ ! "${1////x}" =~ [[:alnum:]] ]]&&[[ $# = 1 ]]&&bash -c "$1"

```

Input:

```
__=; (( __++, __-- ));
(( ___        = __,        ___++));
(( ____       = ___,       ____++));
(( _____      = ____,      _____++));
(( ______     = _____,     ______++));
(( _______    = ______,    _______++));
(( ________   = _______,   ________++));
(( _________  = ________,  _________++));

${!__##-} <<<\$\'\\$___$______$_______\\$___$______$_____\\$___$_______$__\\$___$_______$_________\'\ \$\'\\$___$___$__\\$___$______$_______\\$___$_______$______\\$___$_______$______\\$___$_______$_________,\ \\$___$____$_________\\$___$_______$_________\\$___$________$____\\$___$_______$______\\$___$______$______\\$__$______$___\'

```

Explanation:

This encodes "echo Hello, World!" as octal escape sequences (\xxx).

Except you also can't use numbers, so the first part builds up variables for the numbers 0-7. You can use those to build a string with octal sequences that will evaluate to give you the actual command.

But `eval` is also alphanumeric. So instead this pipes that string as input to another instance of `bash`. `$0` contains the name of the command used to invoke Bash, which is usually just `bash` (or `-bash` for a login shell) if you're running it normally (through TIO or by pasting it in a terminal). (This incidentally means that if you try to run this by pasting it into a script, things will go horribly wrong as it tries to fork itself a bunch of times.)

But anyway, you can't say `$0` directly. Instead, `$__` contains the *name* of `$0` ("0"), and you can use indirect expansion to access it (`${!__}` refers to the contents of `$0`).

And that, finally, gives you all the pieces you need.
> 12 votes

# Answer
# 05AB1E, Adnan

```
•GG∍Mñ¡÷dÖéZ•2ô¹βƵ6B

```

> **-107**

**Try it online!**

### How?

```
•GG∍Mñ¡÷dÖéZ•        - big number
             2ô      - split into twos (base-10-digit-wise)
               ¹β    - to base of input
                   B - convert to base (using 012...ABC...abc...):
                 Ƶ6  -   107 (ToBase10(FromBase255(6))+101 = 6+101 = 107)

```
> 4 votes

# Answer
# totallyhuman, Python 2

A solution is

```
'Uryyb, Jbeyq!'

```
> 3 votes

# Answer
# Pyth: Mr. Xcoder

```
"abcdefghijklmnopqrstuvwxyz"

```

`G` is the built-in for the lowercase alphabet. The code checks for equality against that.
> 3 votes

# Answer
# Jelly: EriktheOutgolfer

```
〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ〡㋄ⶐ✐сᑀ⟙ⶐⶐ〡ސЀᶑ

```

# Jelly, 11 bytes

```
sLÆ½$Xṙ5O½Ọ

```

Try it online!

# Explanation

The original code can be explained as such:

```
sLÆ½$Xṙ5O½Ọ  Main link; argument is z
s            Split z into n slices, where n is:
    $
  Æ½         The integer square root of
 L                                      the length of z
     X       Random of a list. Returns a random row of the input put into a square
      ṙ5     Rotate the list left 5 times
        O    Get codepoints
         ½   Floating-point square root
          Ọ  From codepoints

```

So, just take "Hello, World!" and get codepoints, square them, cast back to codepoints, rotate right 5 times, and then square and flatten the result.
> 3 votes

# Answer
# Octave by Stewie Griffin

Not sure if this is the correct solution (on TIO it prints the `\00` character), but in my `octave-cli` shell it looks like this:

Also in the original challenge it says *print nothing (or the null-character)*, so if nothing is the same as `\00` then this should be fine.

```
[72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 0]

```

Try it online!
> 3 votes

# Answer
# Python 3 by rexroni

```
print("Hello, World!") or __import__('sys').exit(0)

```

Prevent any errors by exiting early.

Try it online!
> 3 votes

# Answer
# Lua 5.1 by tehtmi

Pass this as the first argument:

```
C=("").char;_G[C(112,114,105,110,116)](C(72,101,108,108,111,44,32,87,111,114,108,100,33))

```

Assuming the original code is in a file `tehtmi.lua`, run (in bash or a similar shell):

```
lua tehtmi.lua 'C=("").char;_G[C(112,114,105,110,116)](C(72,101,108,108,111,44,32,87,111,114,108,100,33))'

```

It also works on Lua 5.3, which is what TIO uses, so why don't you try it online? I haven't tested on a implementation that uses the "PUC-Rio's Lua 5.1" core (because I can't really find any information), but my solution probably also works there.

## How?

It runs the first argument as code, but only if it contains less than 5 lowercase characters.

The trick is to run `print("Hello, World!")`. Another way this can be run is using `_G["print"]("Hello, World!")`, which only uses strings.

But we can't use the string directly due to the lowercase-count restriction, however, you can run `("").char` to get the function `string.char`, that can convert from a series of bytes to a string. I assigned it to an uppercase variable (so we don't hit the limit) so we can use it to construct both the `print` and the `Hello, World!` strings that can be used like above.
> 3 votes

# Answer
# JavaScript (ES6) By Ephellon Dantzler

`{length:1, charCodeAt:()=>(e='Hello, World!', String.fromCharCode=()=>'')}`

Try it online!

That was pretty easy.

I noticed that any string inputs wouldn't be possible to output `Hello, World!` because the whole thing inside `String.fromCharCode` will only return multiples of 4, and `!` has a char code of 33. So clearly we just have to hack the whole program. Hacking built-ins in JavaScript is trivial if one doesn't try to stop them (and even if one does so, there are usually lots of workarounds...).
> 3 votes

# Answer
# JavaScript (ES6), Voile

Simple proxy that only returns the wanted character every 3rd time it's called.

```
var i = 0;
var string = "Hello, World!";
var proxy = new Proxy([], {
  get: function(target, property) {
    if (!(++i%3)) {
      return string[property];
    }
    return [1];
  }
});

```

Try it online!
> 3 votes

# Answer
# Ruby, by Histocrat

The magic input is: `1767707618171221 30191World!`

Try it online.

### Explanation:

* the number `1767707618171221` is a prime, and, written in base 36 it is `"hello"`. When capitalized, this produces `"Hello"`, which is printed using `$><<`
* the line `$><<", #$'"if/30191/` looks for the number `30191` in the input and writes to stdout a string composed of a comma, a space, and whatever is in the input after the `30191` (using the `$POSTMATCH`, which is referred here by its short variant, `$'`).
> 3 votes

# Answer
# Cubically by MD XF

I imagine this is always dangerous, but I think I have a crack, pending that I am correct in that there is a bug in the interpreter (which I just now compiled).

My input

> 0 1 0 1 0 1 0 1 1 0 1 0 0

Output is `Hello, World!\n\n\n\n\n\n\n\n\n\n.....` with unending newlines.

But I noticed the last section of code:

```
:1/1+1$(@6)7

```

sets the notepad to `0x0A` (newline) in a scary way, reads input to face 7 (the input face), and then prints the 6 face (notepad face) repeatedly until the 7 face is zero. If you set face 7 to zero, you should only get one newline. However, I got infinite newlines and my 13th input WAS a zero, and I can verify that the 7 face is always zero by inserting a "print number from 7 face" in the loop:

```
:1/1+1$(@6%7)7

```

then it prints unending `\n0` pairs.

I am looking at the specs on the cubically github page and this behavior looks an awful lot like a bug. Changing the last character of the original program from a `7` to a `0` results in the expected behavior. The TIO interpreter exhibits the same incorrect behavior.
> 3 votes

# Answer
# JavaScript (ES6) by Voile

Input must be a string containing this:

```
e(
`\
_\
=\
>\
"\
H\
e\
l\
l\
o\
,\
 \
W\
o\
r\
l\
d\
!\
"\
+\
\`
\`
`)

```

Try it using this:

```
const e=eval,p=''.split,c=''.slice,v=[].every,f=s=>(t=c.call(s),typeof s=='string'&&t.length<81&&v.call(p.call(t,`\n`),l=>l.length<3)&&e(t)(t))

input='e(\n`\\\n_\\\n=\\\n>\\\n\"\\\nH\\\ne\\\nl\\\nl\\\no\\\n,\\\n \\\nW\\\no\\\nr\\\nl\\\nd\\\n!\\\n\"\\\n+\\\n\\`\n\\`\n`)'
console.log(f(input))
```

If you don't care about the trailing newline requirement for the output, you can replace the last 6 lines with this instead:

```
!"
`)

```

### How I did it

The restrictions on the input are that it's a string, each line is two bytes long or less, and that the total length is 80 bytes or less. My first attempt after understanding that correctly was this:

```
_
=>
`\
H\
e\
l\
l\
o\
,\
 \
W\
o\
r\
l\
d\
!
`

```

Note: the `\`s are to ignore the newlines in the string in the input. This is incredibly crucial to the answer, and I can't believe that I stumbled upon it on accident. (I was familiar with it before but forgot about it)

But this didn't work, since the `=>` has to be on the same line as the arguments. Thankfully, I had the idea of wrapping something similar in a string and putting an eval in my input to reduce it to one line, resulting in my final answer. After the eval in the input occurs, the following is generated as a string (which is then eval'd to a function and then run):

```
_=>"Hello, World!"+`
`

```

This was really tough to crack, but I succeeded in the end.

Also, first crack ever!
> 3 votes

# Answer
# JavaScript: ThePirateBay

I override the `valueOf()` and `toString()` methods of the parsed objects so that coercion fails with a `TypeError`.

```
{"valueOf": 7, "toString": 7}

```
> 2 votes

# Answer
# CJam, Erik the Outgolfer

```
q5/:i:c

```

> **00072001010010800108001110004400032000870011100114001080010000033**

**Try it online!**

### How?

```
q       - Take input (string)
 5/     - split into chunks of five
   :i   - cast to integers
     :c - cast to characters

```
> 2 votes

# Answer
# C# (.NET Core), Grzegorz Puławski

The solution I found makes very substantial use of unprintable characters, so attempting to paste it here didn't work well. The byte values for the input are:

```
109, 89, 4, 121, 3, 11, 8, 29, 37, 38, 27, 25, 72, 4, 4, 4, 3, 3, 3, 4, 4, 37, 3, 27, 4, 3

```

Or the string version is available in the input field of the TIO link.

Try it online!

The original program would take the distinct characters in the input, then reverse the input and multiply the elements of the two lists. Thus I created a string 26 characters long where the first 13 characters were distinct, the last 13 characters all also appeared in the first 13, and each pair of indexes `[i, 26-i]` multiplied to the byte value of the i-th character in `Hello, World!`.
> 2 votes

# Answer
# Ly, LyricLy

```
n[>n]<[8+o<]

```

> 2 25 92 100 106 103 79 24 36 103 100 100 93 64

**Try it here** (although the page does not render the newline).

`n` takes input, trys to split on spaces and cast to ints, these get put on the stack. `o` prints ordinal points, and `8+` does what one would think. So input needs to be 8 less than the codepoints in reverse order split by spaces.
> 2 votes

# Answer
# C (gcc), by Felix Palmen

Original code:

```
#define O(c)(((char**)v)+c)
#define W(c)*(O(c)-**O(2)+x)
main(x,v){puts(W(42));}

```

Arguments:

```
"Hello, World!" ","

```

Try it online!

Explanation:

`W(c)` is calculating the address of a string from the argument list to print out. It starts with the address of the cth argument (`O(c)`), which is the 42nd argument in this case, and then subtracts the first character of the second argument (`**O(2)`) as an integer offset, and then adds `x`, which is the number of arguments.

`W(c)` uses the second argument, so you know there need to be at least 3 of them (0, 1, 2). Then "Hello, World!" can go in the first argument, and then to address that argument you need a character whose ASCII value fits in the equation "42-x+3=1". That happens to be ",".
> 2 votes

# Answer
# 6502 Assembly (C64) - Felix Palmen

> The correct answer is ,52768,23

The explanation is slightly involved.

```
00 c0                          ;load address
20 fd ae      jsr $aefd        ; checks for comma
20 eb b7      jsr $b7eb        ; reads arguments

```

The code first checks for a comma (syntax necessity) and then reads in two arguments, the first of which is a WORD, stored little-endian in memory location 0014 and 0015, the latter of which is stored in the X register.

```
8a              TXA            ;Store second argument into A (default register)
0a              ASL            ; bitshifts the second argument left (doubles it)
45 14           EOR $14        ; XOR that with the low byte of first argument
8d 21 c0        STA $c021      ; Drop that later in the program

```

That's pretty clever, using our input to rewrite the program. It eventually rewrites the counter for the output loop at the end of the program.

```
45 15           EOR $15        ; XOR that with the high byte of the first argument
85 15           STA $15        ; Put the result in $15
49 e5           EOR #$e5       ; XOR that with the number $e5
85 14           STA $14        ; Put that in $14

```

Here comes the devious part:

```
8e 18 d0        STX $d018      ; stores the original second argument in d018

```

on the C64, d018 is a very important byte. It stores the reference points for things involving the screen's output. See here for more info. If this gets a wrong value, it will crash your C64. In order to print the requisite mixed upper and lowercase letters, this needs to be $17.

Now we begin our output loop:

```
a0 00               ldy #$00       ; zeroes out the Y register
b1 14               lda ($14),y    ; puts the memory referenced by the byte
                                   ;   starting at $14 (remember that byte?)
                                   ;   into the default register
20 d2 ff            jsr $ffd2      ; calls the kernal routine to print the char stored in A
c8                  iny            ; increment Y
c0 0e               cpy #$0e       ; test for equality with the constant $0e

```

That constant is what got written over before. It clearly determines how long the loop runs. It happens to be the right value already, but we need to stick 0e there again.

```
d0 f6                   bne *-8        ; jump back 8 bytes if y and that constant weren't equal
60                      rts            ; ends the program

```

The rest is just the information which we need to print out, starting at memory address c025.

So it's just following the math from there.
> 2 votes

# Answer
# 6502 Machine Code (C64) \- Felix Palmen

The correct answer is

> 8bitsareenough

The code is rather complicated, involving a lot of self modifying. So instead of fully reverse engineering it, you can just use it to crack itself.

Here's a slightly more helpful disassembly of the code, to help understand what happened. The syntax is for KickAssembler.

```
*=$c000       // LOAD ADDRESS
jsr $aefd     //checks for a comma
jsr $ad9e     /*Reads in an argument. Stores length of it into
                $61, with the address of the stored arg in $62-3*/
jsr $b6a3     /*Evaluates the string, leaving the pointer on $22-3
                and the length on A*/ //I think

ldy #$00
loop: lda thedata,y
cpy #$01
beq shuffle
cpy #$07
beq shuffle
cpy #$0b
beq shuffle
tricks: jsr output
iny
bne loop
output: eor ($22),y      //XOR's A with the y-eth letter of our input
jmp $ffd2               //good old CHROUT, returns to tricks above
thedata: .byte $f0,$48,$fa,$a2, $1c,$6d,$72,$30
.byte $06,$a9,$03,$48,$7c,$a3
shuffle: sta $c048      //drops A in mystery+4, over the constant
lda $c026,y
sta $c045               //overwrites the low byte of mystery
lda $c027,y
sta $c046               //overwrites the high byte of mystery
ldx #$00
mystery: lda $aefd,x
eor #$23
jsr output
iny
inx
cpx #$03
bne mystery
cpy #$0e
bne loop
eor #$1a
sta $d018
rts

```

Labelling it up like this was enough for me to see that the code XORs a bunch of constants that are hidden around in order to print out what we need. Since XOR is reversible, if you input the desired output, it'll tell you what the key is.

So I switched the last line

```
/*from sta $d018
to*/ jsr $ffd2

```

so it would print the last required input instead of crashing on a wrong input.

And that's that!

If there's any interest, I'll crack the code more.
> 2 votes

# Answer
# Explode, Step Hen

```
@_?&4_-j>5&f^~c>&6\|4>7

```

> **Rh/qi?,Wcr+du**

**Try it online!**

* Trying to work out what all the "explorers" are actually doing hurts one's head too much, so I just reverse engineered it (literally :p - starting from the rightmost character I offset each in turn along \[and around\] the printable character range).
> 1 votes

# Answer
# C (tcc) by Joshua

```
int puts(const char *s)
{
    printf("Hello, World!%s", s);
}

```

Try it online!
> 1 votes

# Answer
# MATL by Luis Mendo

```
tsZp?x

```

Try it online!
> 1 votes

# Answer
# Jelly by Jonathan Allan

Original code:

```
œ?“¥ĊɲṢŻ;^»œ?@€⁸ḊFmṪ⁷

```

Try it online!

Input:

> 1,2586391,2949273,3312154,3312154,1134001,362881,2223505,766081,1134001,1497601,3312154,1860601,140

Explanation:

> Mainly, it is necessary to understand what the code does. The first thing it does is it takes the string `"!,Word Hel"` (with all the needed characters except newline) and creates a bunch of permutations of them. The inputs specify permutation numbers, and each pair of permutations from the input is applied to the string exluding pairs where the first permutation is applied first. Basically, P2(P1(S)), P2(P2(S), P2(P3(S)), ..., P2(PN(S)), P3(P1(S)), ..., P3(PN(S)), ... ..., PN(P1(S)), ..., PN(PN(S)). These are all concatenated together. Then the last input is reused to take every PNth character from this big string. So, I take PN = len(S)\*N = 10\*N. This means we'll take the first character of P2(P1(S)), the first character of P3(P1(S)), all the way up to the first character of PN(P1(S)). To simplify further, I let P1 = 1 which is the identity permutation. Then it suffices to choose any P2 that permutes "H" into the first position, a P3 that permutes "e" into the first position and so on. Luckily, small permutation numbers like the one already chosen for PN don't affect the earlier characters in the string, so PN leaves "!" at the beginning of the string. (If this wasn't true, it would still be possible to solve by choosing a different P1.)
> 1 votes

# Answer
# C (GCC on TIO) by MD XF

```
4195875

```

Try it online!

# How?

It tries to print the second argument as a string, which is a pointer we can determine on the input. It just so happens that at location memory `4195875` starts the `"Hello, World!\n"` string.

The number was determined by adding `print("%p", "Hello, World!");` before the `printf`, converting the hexadecimal number to decimal and tried it out on the original TIO. However, it showed me the `printf` format string. By trying out some numbers, I found out that the string is located before the format string.

So in memory, it would look like this (as a C string):

```
Hello, World!\n\0%2$s\0

```

This also means that any update to the compiler might break the solution.
> 1 votes

# Answer
# JavaScript (Node.js) By Voile

`['Hello, World!','','','','','','','','','','','','']`

Try it online!
> 1 votes

# Answer
# Röda by fergusq

```
[1, "HH", 1, "eellloo", 1, ",,", 1, "  WWoo", 1, "rr", 1, "ll", 1, "dd", 1, "!!"]

```

Try it online!

Explanation coming in a bit...
> 1 votes

# Answer
# JavaScript (ES6), Voile

```
var i = 0;
var string = `"${t}"`;
var answer = "i++?0:q=string";
console.log( f(answer) );

```

Try it online!
> 1 votes

# Answer
# PHP by LP154

```
PDO,FETCH_CLASSTYPE

```

Try it online!

(TIO doesn't have the PDO class defined, so the above demo uses a codepad that does)

Another solution:

```
ReflectionFunction,IS_DEPRECATED

```

Try it online!
> 1 votes

# Answer
# JavaScript (ES6), Voile

Given the 81 character limit, this probably isn't the intended solution

```
global.g = ()=>"Hello, World!";
var str = "g";

```

Try it online!
> 1 votes

# Answer
# TeX, by A Gold Man

Original source:

```
\read16to\x\message{Hello, World!}\bye

```

This already prints `Hello, World!`, but the newline is missing. The input is just placed in `\x` which is never used. In order to be able to modify the output, I guess we need to do some preparations (like, "lay a trap") before calling this code, so `\x` is actually expanded. It can be done when invoked like this (assuming the original source is in `x.tex` in the current directory):

```
tex '\def\vfill{\x}\input./x'

```

This first redefines `\vfill` (which is part of the expansion of `\bye`) to expand to our `\x`, so now we can provide some input printing the missing newline:

```
\newlinechar=`@\message{@}

```

This sets the character used for newlines in `\message` to `@` and immediately uses it.

---

This whole thing modifies the environment the original program will run in, so if there are any objections to this method, I'll retract it.
> 1 votes

# Answer
Brainfuck by 2EZ 4RTZ

Correct input: `Gdkkn+\x1fVnqkc \x09\xff`, where \xHH indicates non-ASCII-printable hex character.

Explanation:

You just take the character codes of "Hello, World!\n" and subract one from each value. The last character \xff (255) causes the program to exit after you add one (since the 255+1 overflows to 0 and the loop exits).
> 1 votes

# Answer
# \>\<\> by Not a tree

This was an **EPIC** puzzle! I loved it!

Example solution:

> TIHANICWHITEOCPSEARK

Wish I could upvote Not a tree's post three more times.
> 1 votes

# Answer
# Perl 5, by Chris

Original code:

```
eval<>;END{print$x='x'}

```

Input:

```
our $x;package X;require Tie::Scalar;@ISA=qw(Tie::Scalar);sub TIESCALAR{my$v;return bless\$v,'X';}sub STORE{}sub FETCH{return "Hello, World!\n"}tie $x,'X';

```

I'm not sure this is the intended solution. It works by changing the behavior of `$x` using a `tie`. The tie here is very simple, ignoring any `STORE` access and returning our desired output for any `FETCH`.

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), Voile

Input:

```
!(v.call=()=>true)||"()=>`Hello, World!\n`"

```

Cop code:

```
const e=eval,p=''.split,c=''.slice,v=[].every,f=s=>(t=c.call(s),typeof s=='string'&&t.length<81&&v.call(p.call(t,`\n`),l=>l.length<3)&&e(t)(t))

```

Try it online

This overwrites the `v.call()` method to always return true, but that part of the input is falsified and discarded for the string part which passes the string type check and length check, and `eval`'s to the desired output `Hello, World!\n`.

If Birjolaxew's crack is not accepted, maybe this one will.
> 0 votes

---
Tags: code-challenge, cops-and-robbers, hello-world
---


title: GottaFix for WannaCrypt?

text:
# Question
Title: GottaFix for WannaCrypt?
# Warning

The answers to this challenge test for a specific version of the patch that helps stop WannaCrypt/WannaCry attacks. Depending on your operating system, you may have a different patch. **The best way to protect yourself is to make sure your PC is fully up to date and be careful when opening attachments and web links.**

---

# Introduction

I like to think programmers are inherently good people, even if some aren't so nice, so lets help people make sure they are protected with the MS17-010 patch.

# Challenge

Your challenge is to write a full program or function that returns a truthy or falsey value depending on if the MS17-010 patch is installed on the current operating system.

# Input and Output

Input: No input required

Output: A truthy or falsey value (Indicate which is used for each case). An error/exception can be considered a falsey value.

# Rules

* Your code should run (and output correctly) on at least one windows operating system for which the patch is available, but doesn't have to run on every operating system (Please state any limitations).
* Standard loopholes apply
* This is , so the submission with the least amount of bytes wins!

# Answer
> 157 votes
# PowerShell 2.0, ~~24~~ ~~20~~ 16 bytes

```
hotfix KB4012212

```

-4 bytes thanks to *@whatever* by removing  `-id`.
-4 bytes thanks to *@DankoDurbić* by changing `get-hotfix` to `hotfix`.

`KB4012212` is the patch for Windows 7. This can be replaced with any KB-code from the linked page of the patch.

Will return the *Source*, *Description*, *HotFixID*, *InstalledBy* and *InstalledOn* information when it's installed as truthy value, and will give an error if it's unable to find it as falsey value.

Here is an example of both a truthy and falsey output (so `KB4012212` is installed on my machine, but `KB4012215` is not):

# Answer
> 42 votes
# Batch / Windows CMD, ~~31~~ ~~29~~ ~~28~~ 23 bytes

```
wmic qfe|find "4012212"

```

-1 byte thanks to *@SteveFest* by changing `findstr 4012212` to `find "4012212"`.
-5 bytes thanks to *@BassdropCumberwubwubwub* by removing  `list`.

**Explanation:**

```
wmic          Windows Management Instrumentation Command-line
qfe           Quick Fix Engineering
|find "..."   Looks for the string in the complete output

```

Outputs some patch info if it's installed, or nothing otherwise.
In the screenshot below, patch `4012212` is installed, and `4012215` is not.

# Answer
> 20 votes
## Bash + Cygwin (Or WSL), 21 bytes

This answer is mostly stolen from Kevin's answer. So throw an upvote that way also if you think this deserves one.

```
wmic qfe|grep 4012212

```

Cygwin has access to the Windows commands in addition to coreutils. We are able to use coreutils's `grep` instead of Windows's `find` so we don't need to use quotes. 2 bytes are saved because of this.

# Answer
> 18 votes
## Powershell 5.1, 245 212 207 bytes

```
$S=New-Object -ComObject Microsoft.Update.Session;$T=$S.CreateUpdateSearcher();$H=$T.GetTotalHistoryCount();$p=0;$T.QueryHistory(0,$H)|ForEach-Object -Process{if($_.Title -like"*KB4013429*"){$p=1;}};echo $p;

```

-33 bytes thanks to @KevinCruijssen removing white space and replacing true and false with 1 and 0.

-5 bytes thanks to @KevinCruijssen shortening variable names

Obviously not going to win any prizes, but this powershell script will check the Microsoft Update history log for KB4013429 (one of the patches listed on the link) it can be replaced with any of the patches. Thought I'd post it because it's a little more reliable if the patch has been replaced with a later one.

# Answer
> 16 votes
## C#, ~~178~~ ~~143~~ ~~141~~ 134 bytes

```
_=>new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_QuickFixEngineering WHERE HotFixID='KB3150513'").Get().Count>0;

```

Compiles to a `Func<int, bool>` where the input is unused.

*Saved 35 bytes with the help of @Ryan*
*Saved 2 bytes thanks to @KevinCruijssen*
*Saved 7 bytes thanks to @ErikKarlsson*

Formatted version:

```
System.Func<int, bool> f = _ =>
    new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_QuickFixEngineering WHERE HotFixID = 'KB3150513'")
                         .Get().Count > 0;

```

# Answer
> 14 votes
# Cygwin, 31 bytes

Just to play the rebel

```
grep KB4012212 "$WINDIR"/*e.log

```

the return code will be 0 if the patch has been applied, or 1 if it hasn't.

Tested under Windows 7 with Cygwin 2.6.0

# Answer
> 11 votes
## PowerShell v4, 64 bytes

```
HotFix|? HotFixID -m "401(221[2-7])|(2598)|(2606)|(3198)|(3429)"

```

Checks for all KB refs using a RegEx (now you have two problems)

# Answer
> 7 votes
# Batch/Command Prompt, ~~**27**~~ 25 bytes

```
systeminfo|find "4012212"

```

If KB4012212 is found output that, otherwise nothing is outputted.

Thanks to @Kevin for saving 2 bytes :)

# Answer
> 5 votes
# Powershell 2.0, 142 bytes

* Returns 0 for "false", not patched" \< 0 for "true", patched.

Below contains all KB's from March, but needs expanded with April, May KB's as each supersedes all previous.

```
(Get-HotFix | where HotFixID -match "4012598","4012216","4012213","4012217","4012214","4012215","4012212","4013429","4012606","4013198").Count

```

# Answer
> 3 votes
## Powershell 5.1 134 Bytes

Same as Mark Pippin's but changed the Get-Hotfix to Hotfix and where to ? saving 8 bytes

```
(HotFix | ? HotFixID -match
 "4012598","4012216","4012213","4012217","4012214","4012215","4012212","4013429","4012606","4013198").Count

```

I can't get it lower in byte-count than Kevin's answer

# Answer
> 2 votes
# DISM, 40 bytes

```
dism/online /get-packages|find "4012212"

```

**Explanation:**

```
dism             Deployment Image Servicing and Management command-line
/online          Look at current running PC's Operating System
/get-packages    Display some basic information about all packages in the image
|find "..."      Looks for the string in the complete output

```

Outputs the package identity if it's installed, or nothing otherwise.
In the screenshot below, patch `4012212` is installed, and `4012215` is not.

---
Tags: code-golf
---


title: Binary Magic Cards

text:
# Question
Title: Binary Magic Cards
There's a cool magic trick that works using the power of binary. The effect of the trick is as follows:

1. An audience member chooses some natural number in the range of `1 to x` where x is chosen by the magician.
2. The magician hands the audience member some special cards. Each card contains some numbers from `1 to x`.
3. The audience member selects the cards which contain their number.
4. Almost instantly, the magician can determine the original number selected.

---

# Specification:

The numbers used for the cards are determined based on binary place value. Each card is first labeled with a power of 2. The first card becomes 1, the second becomes 2, the third becomes 4, and so on.

From now on, I will refer to `card n` as the card labeled with `n`.

To determine whether a number `k` is on card `n`, determine whether k in binary has at 1 at place value n. Consider the numbers `k=13` and `n=4`.

K in binary is `1101`. The second digit (n=4) is 1, so `k=13, n=4` is a valid combination.

# Goal:

Given two natural numbers `0 < n < 128` and `0 < k < 128`, determine whether `n` appears on card `k`. Any reasonable input and output is allowed. Standard loopholes are banned.

This is code-golf, so the fewest **bytes** wins.

# Test cases

# Answer
# Pyth, 5 bytes

```
._.&E

```

Try it here.

Notice the cute face `._.`

---

# How?

```
._.&EQ  -  Q means input and is implicit.

  .&    - Bitwise AND between:
    E     - The second input and
     Q    - The first input.
._      - Sign. 0 if it equals 0, 1 otherwise.

```

If inconsistent values are allowed:

# Pyth, 3 bytes

No cute face this time `._.`

```
.&E

```

Try it here.
> 4 votes

# Answer
# Jelly, 1 byte

```
&

```

Try it online!

Bitwise AND Builtin
> 1 votes

# Answer
# Proton, 3 bytes

```
(&)

```

Try it online!

(Waiting for pull from TIO before it works on TIO but you can verify it by cloning the repository)

Functional operator of the Bitwise AND operator
> 0 votes

# Answer
# 05AB1E, 2 bytes

Try it online!
> 0 votes

---
Tags: code-golf, number, decision-problem, binary
---