title: Make a simplified Tamagotchi/Giga Pet!

text:
# Question
Title: Make a simplified Tamagotchi/Giga Pet!
Tamagotchi and Giga Pets were small electronic devices which simulated a little virtual pet. This pet had several stats, like health, hunger, etc.
I recently wrote this example:

```
import msvcrt,os,sys;d=m=100;h=s=t=p=0;f=10
while 1:
 os.system('cls'if os.name=='nt'else'clear');print("health:",d,"\nhunger:",h,"\nsleep:",s,"\nfood:",f,"\npotions:",p,"\nmoney:",m);t+=1
 if msvcrt.kbhit():
  k=ord(msvcrt.getch())
  if k==102 and h>8 and f:f-=1;h-=9
  if k==115:s=0
  if k==112 and p:p-=1;d+=9
  if k==98 and m>8:m-=9;p+=1
  if k==116 and m>8:m-=9;f+=1
 if t>99:
  t=0;h+=1;s+=1
  if s>80:s=0;h+=9
  if h>80:d-=1
  if d<1:sys.exit(0)
  if d>79:m+=1

```

This is a bare-bones virtual pet in 467 bytes! I then wondered how well the **code golf pros** could do, so now, the challenge.

# The Challenge

Make a program that tracks 6 stats of a virtual pet, and updates them over time and in response to user input. The stats are: health and money (starting at 100), food (starting at 10), and hunger, sleep, and potions (starting at 0).

The program should update the values in response to the following events:

* While the program is receiving no input, it should perform updates at regular intervals (the interval between updates should not be shorter than half a second nor longer than one second). Each update does the following:

+ Hunger and Sleep each increase by 1.
    + If Hunger is 80 or above, Health decreases by 1.
    + If Sleep is 80 or above, it is reset to 0, and Hunger increases by an additional 9.
    + If Health is 80 or above, Money increases by 1.
    + If Health is 0, the program exits.
* The program must also respond immediately upon the following keypresses by the user (this means that you will need to use a language feature or library that can detect a key being pressed and respond to it immediately, rather than just reading from standard input), performing the following actions:

+ `f`: If Hunger is greater than 8 and Food is nonzero, then Food is decreased by 1 and Hunger is decreased by 9.
    + `s`: Sleep is reset to 0.
    + `p`: If Potions is greater than zero, Potions is decreased by 1 and Health is increased by 9.
    + `b`: If Money is greater than 8, then Money is decreased by 9 and Potions are increased by 1.
    + `t`: If Money is greater than 8, then Money is decreased by 9, and Food is increased by by 1.

Whenever the values of the stats change, they must be displayed on screen in the form `Stat: *value*`. All six stats must be displayed whenever any of them changes; and the stats within a display must be separated either by commas or by newlines.

This challenge follows normal rules: the shortest program complying with the specification above wins. (Note that as usual, if the language is newer than the competition, the submission must be marked as non-competing.)

# Answer
> 6 votes
# C, 424 406 386 357 bytes

```
#define x(a,b,c)if(*#a==C){if(b>8){c-=9;}Z=0;}
L,M=100,H,S=-1,F=10,P,Z,C;t(){H++;S++;L-=H>79;if(S>79)S=0,H+=9;Z=1/L/2;alarm(1);}main(){nodelay(initscr(),L=M);signal(14,t);for(t(H=S);C=getch();Z=Z||printf("\rhealth: %d,hunger: %d,sleep: %d,food: %d,potions: %d,money: %d\n",L,H,S,F,P,M)){x(s,9,S=9;S)x(p,P+8,P--;L+=18;L)x(f,H,F--;H)x(b,M,P++;M)x(t,M,F++;M)}}

```

I appreciate the need for raw input and asynchronous updates in the problem spec. Even though that required some overhead from the ncurses setup and signal handlers, it's nice to have the occasional challenge that (hopefully) won't be automatically won by one of the dedicated golfing languages.

You didn't specify exactly how game over is indicated, so this one perishes with the traditional Tamagotchi death cry of "Floating point exception (core dumped)".

**Ungolfed**

```
/* Playing a bit fast and loose with the prototyping rules by omitting these;
 * none of the functions I'm using from them *exactly* match the default
 * prototype of `int f();`
 */
//#include <curses.h>
//#include <stdio.h>
//#include <signal.h>
//#include <unistd.h>

#define x(a,b,c)if(*#a==C){if(b>8){c-=9;}Z=0;}
L,M=100,H,S=-1,F=10,P,Z,C;

t() {
    H++;
    S++;
    L-=H>79;
    if(S>79)S=0,H+=9;
    Z=1/L/2;//0 if L>0. otherwise the pet dies of a floating point error
    alarm(1);
}

main(){
    nodelay(initscr(),L=M);
    signal(14,t);
    for(t(H=S); C=getch(); Z=Z||printf("\rhealth: %d,hunger: %d,sleep: %d,food: %d,potions: %d,money: %d\n",L,H,S,F,P,M)){
        x(s,9,S=9;S)
        x(p,P+8,P--;L+=18;L)
        x(f,H,F--;H)
        x(b,M,P++;M)
        x(t,M,F++;M)
    }
}

```

# Answer
> 2 votes
# PHP, ~~396~~ 413 bytes

*(Dang, my first code golf entry that I had to edit up in byte count. Edited to remove sleep() call, as it wasn't really complying with rules-as-intended.)*

Requires a unix-ish OS for the non-blocking STDIN. Oddly, using switch/case versus cascading if/else produced shorter source code, but the subsequent compressed version was longer.

```
<?eval(gzinflate(base64_decode('bY5BT8MwDIXv/Ao0WWujtVJ7YmtITwiNAwhp3KutOE20pImWVGxa999J1IEAcbH87O892wlUqsEjtmnivD/d5rLd9qZPCHX+gFvdOPTNTpl2L/su3bw9PL1kBaEwMHAMLCsocFaGKhjo0BT0Q0iFaUnO4JmXGlPyPZI8TWHPeIe+nbIIGccJqsGTXbi4p4EKEEt4Qs6xH+rlfA6c5DnwEYacregFlcMvziUk/FLQnzN79drosiOIxV/X7kroeklAh9BxsQD7m/H/MXxi4iKoob5bxRuCTtpFHd8Jn8ab0S7iLOz0pO5LgkfpQ0wrzGyNW+VFBSJ7Nj2eKtDZozHvFfBsPfQdHioYso1CtBW47NV4aXpXgb2Z0csn')));

```

Ungolfed:

```
<?
shell_exec('stty -icanon');
stream_set_blocking(STDIN, 0);
$u = $s = $p =0;
$f = 10;
$h = $m = 100;
while(1) {
    $t=time();
    while(1)
        if (($k = fgetc(STDIN)) || time() > $t)
            break;
    if ($k == 'f'){
        if ($u > 8 && $f) --$f | $u -= 9;
    } elseif ($k == 's')
        $s = 0;
    elseif ($k == 'p') {
        if ($p) --$p | $h += 9;
    } elseif ($k == 'b') {
        if ($m > 8) $m -= 9 | ++$p;
    } elseif ($k == 't') {
        if ($m > 8) $m -= 9 | ++$f;
    } else {
        if (++$u > 79) --$h;
        if (++$s > 79) $s = 0 | $u += 9;
        if ($h > 79) ++$m;
        if ($h < 1) exit;
    }
    echo"Health:$h,Money:$m,Food:$f,Hunger:$u,Sleep:$s,Potions:$p\n";
}

```

# Answer
> 2 votes
# C#6, ~~567~~ 563 bytes

```
using System;using System.Threading;class T{int L,M,F=10,H,S,P;static void Main(){T t=new T();}T(){M=L=100;var W=new Thread(new ThreadStart(Q));W.Start();while(1>0){var r=Console.Read();bool B=0>1,K=1>0;if(r=='f'&H>8&F>0){F--;H-=9;B=K;}if(r=='s'){S=0;B=K;}if(r=='p'&P>0){P--;L+=9;B=K;}if(r=='b'&M>8){M-=9;P++;B=K;}if(r=='t'&M>8){M-=9;F++;B=K;}if(B)p();}}void Q(){while(1>0){H++;S++;if(H>79)L--;if(S>79){S=0;H+=9;}if(L>79)M++;L*=L/L;p();Thread.Sleep(500);}}void p(){Console.Write($"\nhealth: {L}\nhunger: {H}\nsleep: {S}\nfood: {F}\nmoney: {M}\npotions: {P}\n");}}

```

Ungolfed:

```
using System;
using System.Threading;
class T
{
    int L,M,F=10,H,S,P;
    static void Main()
    {
        T t=new T();
    }
    T()
    {
        M=L=100;
        var W=new Thread(new ThreadStart(Q));
        W.Start();
        while(1>0)
        {
            var r=Console.Read();
            var B=0>1;
            if(r=='f'&H>8&F>0){F--;H-=9;B=1>0;}
            if(r=='s'){S=0;B=1>0;}
            if(r=='p'&P>0){P--;L+=9;B=1>0;}
            if(r=='b'&M>8){M-=9;P++;B=1>0;}
            if(r=='t'&M>8){M-=9;F++;B=1>0;}
            if(B)p();
        }
    }
    void Q()
    {
        while(1>0)
        {
            H++;S++;
            if(H>79)L--;
            if(S>79){S=0;H+=9;}
            if(L>79)M++;
            L*=L/L;
            p();
            Thread.Sleep(500);
        }
    }
    void p()
    {
        Console.Write($"\nhealth: {L}\nhunger: {H}\nsleep: {S}\nfood: {F}\nmoney: {M}\npotions: {P}\n");
    }
}

```

# Answer
> 2 votes
**Mathematica, 374 bytes**

```
h=m=100;f=10;g=s=p=0;RunScheduledTask[g++;s++;If[g>79,h--];If[s>79,s=0;g+=9];If[h>79,m++];If[h<1,Quit[]]];Dynamic@Row[{EventHandler[InputField[],"KeyDown":>Switch[CurrentValue@"EventKey","f",If[g>8&&f>0,f--;g-=9],"s",s=0,"p",If[p>0,p--;h+=9],"b",If[m>8,m-=9;p++],"t",If[m>8,m-=9;f++]]],"
Health: ",h,"
Money: ",m,"
Food: ",f,"
Hunger: ",g,"
Sleep: ",s,"
Potions: ",p}]

```

The line breaks are important because they are newline characters in the string so I could use `Row` instead of `Column`. If you evaluate this in a Mathematica notebook you should see something like this:

You have to click in the input field and quickly (less than a second) type your character before `Dynamic` causes the input field to update. This headache could be avoided entirely if the `EventHandler` was in its own cell rather than being an element of `Row`, but that would require saving the program as a .nb file which would greatly increase the byte count.

# Answer
> 1 votes
## Clojure, ~~1224~~ 702 bytes

## V2

Made all the atoms loose variables instead of being inside a state object. That alone got rid of a lot of code. I also created the shortcut functions `a!` and `s!` to add and subtract from the `atoms` easier (basically acting as `+=` and `-=`, since Clojure doesn't have those operators).

I realized that I could probably do away with `atom`s if I manage to integrate key input into a `loop`. I'll have to see.

```
(ns bits.golf.pet.v2.petms)(def h(atom 100))(def j(atom 0))(def s(atom 0))(def f(atom 10))(def p(atom 0))(def m(atom 100))(defn a[sa n](swap! sa #(+ % n)))(defn v[sa n](swap! sa #(- % n)))(defn c[](a j 1)(a s 1)(if(>=@j 80)(v h 1))(if (>=@s 80)(do(reset! s 0)(a j 9)))(if(>= @h 80)(a m 1)))(defn l[k](case k\f(if(> @j 8)(do(v f 1)(v j 9)))\s(reset! s 0) \p(if(>@p 0)(do(v p 1)(a h 9)))\b(if(> @m 8)(do(v m 9)(a p 1)))\t(if(>@m 8)(do(v m 9)(a f 1)))nil))(defn b[](.start(Thread.^Runnable(fn[](while(>@h 0)(l(first (read-line))))))))(defn -main[](b)(while(>@h 0)(Thread/sleep 500)(c)(println(str"Health: "@h"\nHunger: " @j"\nSleep: "@s"\nFood: "@f"\nPotions: "@p"\nMoney:"@m"\n")))(println"You died!\n"))

```

Ungolfed:

```
(ns bits.golf.pet.v2.pet)

; 100 0 0 10 0 100
(def he (atom 100))
(def hu (atom 0))
(def sl (atom 0))
(def fo (atom 10))
(def po (atom 0))
(def mo (atom 100))

(defn a! [sa n]
  (swap! sa #(+ % n)))

(defn s! [sa n]
  (swap! sa #(- % n)))

(defn apply-rules []
    (a! hu 1)
    (a! sl 1)
    (if (>= @hu 80)
      (s! he 1))
    (if (>= @sl 80)
      (do
        (reset! sl 0)
        (a! hu 9)))
    (if (>= @he 80)
      (a! mo 1)))

(defn handle-keypress [k]
    (case k
      \f (if (> @hu 8)
           (do
             (s! fo 1)
             (s! hu 9)))
      \s (reset! sl 0)
      \p (if (> @po 0)
           (do
             (s! po 1)
             (a! he 9)))
      \b (if (> @mo 8)
           (do
             (s! mo 9)
             (a! po 1)))
      \t (if (> @mo 8)
           (do
             (s! mo  9)
             (a! fo 1)))
      nil))

(defn start-listener []
  (.start
    (Thread. ^Runnable
      (fn []
        (while (> @he 0)
            (handle-keypress (first (read-line))))))))

(defn -main []
  (start-listener)
  (while (> @he 0)
    (Thread/sleep 500)

    (apply-rules)

    (println (str
               "Health: " @he "\n"
               "Hunger: " @hu "\n"
               "Sleep: " @sl "\n"
               "Food: " @fo "\n"
               "Potions: " @po "\n"
               "Money:" @mo "\n")))

  (println "You died!\n"))

```

---

## V1

Ohdeargod. Definitely room for improvement here. This kind of problem is easiest to do with side effects, and Clojure is functional, so I'm trying to abuse `atom`s to lessen the amount of code needed. Unfortunately, I didn't go in with a plan, so it's kind of haphazard right now. I've already gotten a few ideas to shrink I though.

It's a full program. It can be run by running `-main`.

```
(ns bits.golf.pet)(defrecord S[he hu sl fo po mo])(def new-state(->S 100 0 0 10 0 100))(def state(atom new-state))(defn update![sa k f](swap! sa #(update % k f)))(defn apply-rules[s](let [s' (atom s)u! #(update! s' %1 %2)g #(get @s' %)](u! :hu inc)(u! :sl inc)(if(>=(g :hu)80)(u! :he dec))(if(>= (g :sl)80)(do(u! :sl (fn[_]0))(u! :hu #(+ % 9))))(if(>=(g :he)80)(u! :mo inc))@s'))(defn get-input [](let [raw (read-line)](first raw)))(defn handle-keypress[s k](let [s'(atom s)u! #(update! s' %1 %2)g #(get @s' %)](case k\f(if (> (g :hu)8)(do(u! :fo dec)(u! :hu #(- % 9))))\s(u! :sl (fn [_] 0))\p(if(> (g :po)0)(do(u! :po dec)(u! :he #(+ % 9))))\b(if(>(g :mo))(do(u! :mo #(- % 9))(u! :po inc)))\t(if(>(g :mo)8)(do(u! :mo #(- % 9))(u! :fo inc)))nil@s')))(defn start-listener[](.start(Thread.^Runnable(fn[](while true(let[k(get-input)](swap! state #(handle-keypress % k))))))))(defn -main[](start-listener)(let[g #(get @%1 %2)](while true(Thread/sleep 500)(swap! state #(apply-rules %))(println(str"Health: "(g state :he)"\nHunger: "(g state :hu)"\n""Sleep: " (g state :sl)"\nFood: "(g state :fo)"\nPotions: "(g state :po)"\n""Money:"(g state :mo)"\n"))(if(<=(g state :he)0)(do(println"You died!\n")(reset! state new-state))))))

```

Ungolfed:

```
(ns bits.golf.pet)

(defrecord State [he hu sl fo po mo])

(def new-state (->State 100 0 0 10 0 100))

(def state (atom new-state))

(defn update! [sa k f]
  (swap! sa #(update % k f)))

(defn apply-rules [s]
  (let [s' (atom s)
        u! #(update! s' %1 %2)
        g #(get @s' %)]
    (u! :hu inc)
    (u! :sl inc)
    (if (>= (g :hu) 80)
      (u! :he dec))
    (if (>= (g :sl) 80)
      (do
        (u! :sl (fn [_] 0))
        (u! :hu #(+ % 9))))
    (if (>= (g :he) 80)
      (u! :mo inc))
    @s'))

(defn get-input []
  (let [raw (read-line)]
    (first raw)))

(defn handle-keypress [s k]
  (let [s' (atom s)
        u! #(update! s' %1 %2)
        g #(get @s' %)]
    (case k
      \f (if (> (g :hu) 8)
           (do
             (u! :fo dec)
             (u! :hu #(- % 9))))
      \s (u! :sl (fn [_] 0))
      \p (if (> (g :po) 0)
           (do
             (u! :po dec)
             (u! :he #(+ % 9))))
      \b (if (> (g :mo))
           (do
             (u! :mo #(- % 9))
             (u! :po inc)))
      \t (if (> (g :mo) 8)
           (do
             (u! :mo #(- % 9))
             (u! :fo inc)))
      nil
      @s')))

(defn start-listener []
  (.start
    (Thread. ^Runnable
      (fn []
        (while true
          (let [k (get-input)]
            (swap! state #(handle-keypress % k))))))))

(defn -main []
  (start-listener)
  (let [g #(get @%1 %2)]
    (while true
      (Thread/sleep 500)

      (swap! state #(apply-rules %))

      (println (str
                 "Health: " (g state :he) "\n"
                 "Hunger: " (g state :hu) "\n"
                 "Sleep: " (g state :sl) "\n"
                 "Food: " (g state :fo) "\n"
                 "Potions: " (g state :po) "\n"
                 "Money:" (g state :mo) "\n"))

      (if (<= (g state :he) 0)
        (do
          (println "You died!\n\n\n\n\n")
          (reset! state new-state))))))

```

---
Tags: code-golf
---


title: Witness My Challenge (Tetris Puzzle)

text:
# Question
Title: Witness My Challenge (Tetris Puzzle)
# Introduction

In the game *The Witness* (*possible spoilers ahead*) there is a group of puzzles that involve drawing a Tetris piece with your line while making sure that the symbol for the Tetris piece your currently drawing stays contained within the shape you've drawn.

For the image above the drawing works because the L-shaped and upside down L-shaped Tetris pieces, occupying the positions `(1,2)(2,2)(3,2)(3,3)` and `(1,1)(1,0)(2,0)(3,0)` respectively, and the icons, located at `(3,0)` and `(3,3)`, are contained within the white line.

# Challenge

Your goal is to draw the solution line such that it contains all Tetris pieces as well as their respective symbols. The solution line may not contain anymore squares than that which is required (i.e. you must contain the sum of the number of squares making up each Tetris piece). Each solution will begin in the bottom left and end in the top right. Lastly, this is code-golf, so the shortest solution (in bytes) wins.

## Representation

Each of these puzzles use a `HxW` grid of squares to construct your Tetris pieces and have some space for you to draw lines in between them. The representation is best understood by example. For the above image the representation would be

```
===========
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
===========

```

and the solution would be

```
===========
|*********|
|*X X X X |
|*******  |
| X X X*X |
|  *** *  |
| X*X*X*X |
|  * * ***|
| X*X*X X*|
|*** *****|
===========

```

where each square is represented by an `X` and the solution is drawn using a line of `*`s. The number of lines for each puzzle is `2*H+3` and the number of characters for each line is `2*W+3`.

## Input

The first `n` lines will give you the Tetris piece followed by the location of the corresponding symbol for that Tetris piece. The format is as follows:

`(i1,j1)(i2,j2)...(ik,jk)->(p,q)`

where `(ik,jk)` is the `kth` coordinate pair of the Tetris piece (the left coordinate increases as you move down, the right coordinate increases as you move right) and `(p,q)` is the location of the corresponding symbol. The origin of each Tetris piece is the top left square (i.e. the top left square is `(0,0)`).

Example 1:

```
X
X
XX

```

would be

```
(0,0)(1,0)(2,0)(2,1)

```

Example 2:

```
XX
X
X

```

would be

```
(0,0)(1,0)(2,0)(0,1)

```

Example 3:

```
X  X
X  X

```

would be

```
(0,0)(1,0)(0,3)(1,3)

```

The next `2*H+3` lines will consist of the puzzle's grid.

## Output

Output the puzzle grid with the solution line drawn in.

## Examples

### Example Input 1

```
(0,0)(0,1)->(2,1)
(0,0)(0,1)->(0,1)
(0,0)->(0,2)
=========
|       |
| X X X |
|       |
| X X X |
|       |
| X X X |
|       |
=========

```

### Example Output 1

```
=========
|*******|
|*X X X |
|*******|
| X X X*|
|***** *|
|*X X*X*|
|*   ***|
=========

```

### Example Input 2

```
(0,0)(0,1)(0,2)(1,2)(2,2)->(0,0)
(0,0)(1,0)(0,3)(1,3)->(2,1)
(0,0)(1,0)(2,0)->(1,3)
===========
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
===========

```

### Example Output 2

```
===========
|      ***|
| X X X*X |
|      ***|
| X X X X*|
|        *|
| X X X X*|
|*** *****|
|*X*X*X X |
|* ***    |
===========

```

### Example Input 3

```
(0,0)(1,0)(2,0)->(1,0)
(0,0)(1,0)(2,0)->(1,6)
(0,0)(0,1)(0,2)->(1,3)
=================
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
=================

```

### Example Output 3

```
=================
|***         ***|
|*X*X X X X X*X |
|* *******   *  |
|*X X X X*X X*X |
|* *******   *  |
|*X*X X X X X*X |
|* ***********  |
=================

```

# Clarifications

* It is assumed that for any given input there is a solution.
* If there are multiple solutions just print one.

# Answer
> 2 votes
# Python, 992

Takes input from stdin and prints the solution. Note that SE has turned my tab characters into four spaces - anything indented beyond one space should be a tab.

It shouldn't be too hard to beat this, but I thought I'd post it since no one else had posted a solution.

```
L=len
R=range
j=[(-1,0),(1,0),(0,-1),(0,1)]
P=lambda y,x,q:(y,x)==(0,w)and[q+[(y,x)]]or sum([P(y+e,x+d,q+[(y,x)])for e,d in j if not(y+e,x+d)in q and 0<=x+d<=w and 0<=y+e<=h],[])
def C(q,y,x,v):
 if(y,x)in v:return
 v.add((y,x))
 for e,d in j:
    Y,X=y+e,x+d;a,b=[(y+(e+s*d+1)/2,x+(d+s*e+1)/2)for s in[-1,1]]
    if 0<=X<w and 0<=Y<h and not(a in q and b in q and abs(q.index(a)-q.index(b))==1):C(q,Y,X,v)
def G(s,c):
 if not s:return not c
 for y,x in r:
    p=set((Y+y,X+x)for Y,X in s[0])
    if c&p==p and G(s[1:],c-p):return 1
def B(q):
 for y,x in r:
    c=set();C(q,y,x,c);s=[h for(w,h)in p if w in c]
    if s and not G(s,c):return 1
h,p,g=0,[],[]
try:
 while 1:
    s=raw_input()
    if'('in s:l,o=s.split('->');p.append(map(eval,[o,'('+l.replace(')','),')+')']))
    else:g.append(list(s))
except:h=L(g)/2-1;w=L(g[0])/2-1
r=[(x/w,x%w)for x in R(w*h)]
for s in P(h,0,[]):
 if not B(s):break
for(a,b),(c,d)in zip(s,s[1:]):g[1+2*a][1+2*b]=g[1+a+c][1+b+d]=g[1+2*c][1+2*d]='*'
print'\n'.join(''.join(r)for r in g)

```

Quick rundown of how it works:

`P` finds all possible paths.

`C` finds all the squares that are connected to a given square.

`G` determines whether or not a set of shapes fit exactly in a set of squares.

`B` determines whether or not a path is bad by checking each connected set of squares and checking if their shapes fit.

## Examples

input:

```
(0,0)(0,1)->(2,1)
(0,0)(0,1)->(0,1)
(0,0)->(0,2)
=========
|       |
| X X X |
|       |
| X X X |
|       |
| X X X |
|       |
=========

```

output (all tetris pieces are grouped into the top-right):

```
=========
|***   *|
|*X*X X*|
|* *   *|
|*X*X X*|
|* * ***|
|*X*X*X |
|* ***  |
=========

```

input:

```
(0,0)(0,1)(0,2)(1,2)(2,2)->(0,0)
(0,0)(1,0)(0,3)(1,3)->(2,1)
(0,0)(1,0)(2,0)->(1,3)
===========
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
| X X X X |
|         |
===========

```

output (this is the only one that's the same as the example solution):

```
===========
|      ***|
| X X X*X |
|      ***|
| X X X X*|
|        *|
| X X X X*|
|*** *****|
|*X*X*X X |
|* ***    |
===========

```

input:

```
(0,0)(1,0)(2,0)->(1,0)
(0,0)(1,0)(2,0)->(1,6)
(0,0)(0,1)(0,2)->(1,3)
=================
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
| X X X X X X X |
|               |
=================

```

output (rightmost 2 pieces are grouped together):

```
=================
|*** *** *******|
|*X*X*X*X*X X X |
|* * * * *******|
|*X*X*X*X X X X*|
|* * * * *******|
|*X*X*X*X*X X X |
|* *** ***      |
=================

```

---
Tags: code-golf, ascii-art, game, puzzle-solver, tetris
---


title: When does (x == x+2)?

text:
# Question
Title: When does (x == x+2)?
The challenge: Define `x` in such a way that the expression `(x == x+2)` would evaluate to true.

I tagged the question with C, but answers in other languages are welcome, as long as they're creative or highlight an interesting aspect of the language.

I intend to accept a C solution, but other languages can get my vote.

1. Correct - works on standard-compliant implementations. Exception - assuming an implementation of the basic types, if it's a common implementation (e.g. assuming `int` is 32bit 2's complement) is OK.
2. Simple - should be small, use basic language features.
3. Interesting - it's subjective, I admit. I have some examples for what I consider interesting, but I don't want to give hints. **Update**: Avoiding the preprocessor is interesting.
4. Quick - The first good answer will be accepted.

After getting 60 answers (I never expected such prticipation), It may be good to summarize them.

The 60 answers divide into 7 groups, 3 of which can be implemented in C, the rest in other languages:

1. The C preprocessor. `#define x 2|0` was suggested, but there are many other possibilities.
2. Floating point. Large numbers, infinity or NaN all work.
3. Pointer arithmetic. A pointer to a huge struct causes adding 2 to wrap around.

The rest don't work with C:
4. Operator overloading - A `+` that doesn't add or a `==` that always returns true.
5. Making `x` a function call (some languages allow it without the `x()` syntax). Then it can return something else each time.
6. A one-bit data type. Then `x == x+2 (mod 2)`.
7. Changing `2` \- some language let you assign `0` to it.

# Answer
> 71 votes
```
main()
{
double x=1.0/0.0;
printf("%d",x==x+2);
}

```

Outputs 1.

Link: http://ideone.com/dL6A5

# Answer
> 125 votes
Fortran IV:

```
2=0

```

After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)

# Answer
> 100 votes
This seems to work:

```
#define x 2|0

```

Basically, the expression is expanded to `(2|0 == 2|(0+2))`. It is a good example of why one should use parentheses when defining macros.

# Answer
> 79 votes
## Brainfuck

```
x

```

This does of course stretch "evaluate to true" a bit, because in Brainfuck nothing actually *evaluates* to anything – you only manipulate a tape. But if you now append your expression

```
x
(x == x+2)

```

the program is equivalent to

```
+

```

(because everything but `<>+-[],.` is a comment). Which does nothing but increment the value where we are now. The tape is initialised with all zeros, so we end up with a 1 on the cursor position, which means "true": if we now started a conditional section with `[]`, it would enter/loop.

# Answer
> 56 votes
# F#

```
let (==) _ _ = true
let x = 0
x == (x + 2) //true

```

# Answer
> 50 votes
## C

```
int main() { float x = 1e10; printf("%d\n", x == x + 2); }

```

Note: may not work if `FLT_EVAL_METHOD != 0` (see comments below).

# Answer
> 36 votes
**C#**

```
class T {
  static int _x;
  static int X { get { return _x -= 2; } }

  static void Main() { Console.WriteLine(X == X + 2); }
}

```

Not a shortie, but somewhat elegant.

http://ideone.com/x56Ul

# Answer
> 32 votes
**Scala:** `{ val x = Set(2); (x == x + 2) }`

---

**Haskell:** Define ℤ/2ℤ on `Bool`eans:

```
instance Num Bool where
    (+) = (/=)
    (-) = (+)
    (*) = (&&)
    negate = id
    abs    = id
    signum = id
    fromInteger = odd

```

then for any `x :: Bool` we'll have `x == x + 2`.

*Update:* Thanks for the ideas in comment, I updated the instance accordingly.

# Answer
> 31 votes
## Python

```
class X(int):__add__=lambda*y:0
x=X()

# Then (x == x+2) == True

```

# Answer
> 31 votes
**GNU C** supports structures with no members and size 0:

```
struct {} *x = 0;

```

# Answer
> 26 votes
PHP:

```
$x = true;
var_dump($x == $x+2);

```

Or:

```
var_dump(!($x==$x+2));

```

Output:

> bool(true)

# Answer
> 25 votes
It's a common misconception that in C, whitespace doesn't matter. I can't imagine somebody hasn't come up with this in GNU C:

```
#include <stdio.h>
#define CAT_IMPL(c, d) (c ## d)
#define CAT(c, d) CAT_IMPL(c, d)
#define x CAT(a, __LINE__)

int main()
{
    int a9 = 2, a10 = 0;
    printf("%d\n", x ==
        x + 2);
    return 0;
}

```

Prints `1`.

# Answer
> 20 votes
**C**

It's more interesting without using macros and without abusing infinity.

```
/////////////////////////////////////
// At the beginning                 /
// We assume truth!                 /

int truth = 1;
int x = 42;

/////////////////////////////////////
// Can the truth really be changed??/
truth = (x == x + 2);

/////////////////////////////////////
// The truth cannot be changed!     /
printf("%d",truth);

```

Try it if you don't believe it!

# Answer
> 18 votes
## Mathematica:

```
x /: x + 2 := x
x == x + 2

```

I think this solution is novel because it uses *Mathematica's* concept of Up Values.

EDIT:

I am expanding my answer to explain what Up Values mean in *Mathematica*.

The first line essentially redefines addition for the symbol `x`. I could directly store such a definition in the global function that is associated with the `+` symbol, but such a redefinition would be hazardous because the redefinition may propagate unpredictably through *Mathematica's* built-in algorithms.

Instead, using the tag `x/:`, I associated the definition with the symbol `x`. Now whenever *Mathematica* sees the symbol `x`, it checks to see whether it is being operated on by the addition operator `+` in a pattern of the form `x + 2 + ___` where the symbol `___` means a possible null sequence of other symbols.

This redefinition is very specific and utilizes *Mathematica's* extensive pattern matching capabilities. For example, the expression `x+y+2` returns `x+y`, but the expression `x+3` returns `x+3`; because in the former case, the pattern could be matched, but in the latter case, the pattern could not be matched without additional simplification.

# Answer
> 17 votes
Javascript:

```
var x = 99999999999999999;
alert(x == x+2);

```

Test Fiddle

# Answer
> 17 votes
## **scheme**

```
(define == =)
(define (x a b c d) #t)
(x == x + 2)
;=> #t

```

# Answer
> 16 votes
Here is a solution for JavaScript that does not exploit the `Infinity` and `-Infinity` edge cases of floating-point addition. This works neither in Internet Explorer 8 and below nor in the opt-in ES5 strict mode. I would not call the `with` statement and getters particularly "advanced" features.

```
with ({ $: 0, get x() {return 2 * this.$--;} }) {
    console.log(x == x+2);
}

```

**Edited to add:** The above trick is also possible without using `with` and `get`, as noted by Andy E in Tips for golfing in JavaScript and also by jncraton on this page:

```
var x = { $: 0, valueOf: function(){return 2 * x.$++;} };
console.log(x == x+2);

```

# Answer
> 16 votes
Obvious answer:

# When this terminates:

```
while (x != x+2) { }
printf("Now");

```

# Answer
> 14 votes
The following is not standards compliant **C**, but should work on just about any 64-bit platform:

```
int (*x)[0x2000000000000000];

```

# Answer
> 10 votes
Sage:

```
x=Mod(0,2)
x==x+2

```

returns True

In general for GF(2\**n) it's always true that x=x+2 for any x

This is not a bug or an issue with overflow or infinity, it's actually correct

# Answer
> 10 votes
## Common Lisp

```
* (defmacro x (&rest r) t)
X
* (x == x+2)
T

```

It's pretty easy when `x` doesn't have to be an actual value.

# Answer
> 8 votes
## APL (Dyalog)

```
X←1e15
X=X+2

```

APL does not even have infinity, it's just that the floats aren't precise enough to tell the difference between `1.000.000.000.000.000` and `1.000.000.000.000.002`. This is, as far as I know, the only way to do this in APL.

# Answer
> 8 votes
# Perl 6

I'm surprised to not see this solution before. Anyway, the solution is - what if `x` is `0` and `2` at once? `my \x` in this example declares sigilless variable - this question asks about `x`, not Perl-style `$x`. The `?? !!` is ternary operator.

```
$ perl6 -e 'my \x = 0|2; say x == x + 2 ?? "YES" !! "NO"'
YES

```

But...

```
$ perl6 -e 'my \x = 0|2; say x == x + 3 ?? "YES" !! "NO"'
NO

```

`x` is multiple values at once. `x` is equal to `0` and `2` at once. `x + 2` is equal to `2` and `4` at once. So, logically they're equal.

# Answer
> 8 votes
# Python 2.X (Using redefinition of (cached) integers)

I've noticed all of the python answers have defined classes that redefine the `+` operator. I'll answer with an even more low-level demonstration of python's flexibility. (This is a python2-specific snippet)

In python, integers are stored more or less this way in C:

```
typedef struct {            // NOTE: Macros have been expanded
    Py_ssize_t ob_refcnt;
    PyTypeObject *ob_type;
    long ob_ival;
} PyIntObject;

```

That is, a struct with a `size_t`, `void *`, and `long` object, in that order.
Once we use, and therefore cache an integer, we can use python's `ctypes` module to redefine that integer, so that not only does `x == x+2`, but `2 == 0`

```
import ctypes
two = 2 # This will help us access the address of "2" so that we may change the value

# Recall that the object value is the third variable in the struct. Therefore,
# to change the value, we must offset the address we use by the "sizeof" a
# size_t and a void pointer
offset = ctypes.sizeof(ctypes.c_size_t) + ctypes.sizeof(ctypes.c_voidp)

# Now we access the ob_ival by creating a C-int from the address of
# our "two" variable, offset by our offset value.
# Note that id(variable) returns the address of the variable.
ob_ival = ctypes.c_int.from_address(id(two)+offset)

#Now we change the value at that address by changing the value of our int.
ob_ival.value = 0

# Now for the output
x = 1
print x == x+2
print 2 == 0

```

Prints

```
True
True

```

# Answer
> 7 votes
## Perl

using a subroutine with side-effects on a package variable:

```
sub x () { $v -= 2 }
print "true!\n" if x == x + 2;

```

Output: `true!`

# Answer
> 7 votes
***Python***

exploiting floating point precision makes this very simple.

```
>>> x = 100000000000000000.0
>>> (x == x+2)
True

```

To make it less system specific requires an extra import

```
>>> import sys
>>> x = float(sys.maxint + 1)
>>> (x == x+2)
True

```

This should work in other languages too. This works because the reprensentation of 100000000000000000.0 and 100000000000000002.0 are exactly the same for the machine, because of the way floating points are represented inside the machine. see http://en.wikipedia.org/wiki/IEEE\_floating\_point for more information.

So this will basically work in any language that allows you to add integers to floats and have the result of this be a float.

# Answer
> 6 votes
Here is a solution for C++ based on operator overloading. It relies on implicit conversion from an `enum` to an `int`.

```
#include <iostream>

enum X {};
bool operator==(X x, int y)
{
    return true;
}

int main()
{
    X x;
    std::cout << std::boolalpha << (x == x+2) << std::endl;
    return 0;
}

```

# Answer
> 5 votes
I know it's a code challenge... but I golfed it. Sorry.

**Ruby - 13 characters - Infinity solution**

```
x=1e17;x==x+2

```

returns true

**Ruby - 41 characters - Op Overloading solutions**

```
class Fixnum;def + y;0 end end;x=0;x==x+2

```

or

```
class A;def self.+ y;A end end;x=A;x==x+2

```

# Answer
> 5 votes
If it is ok to exploit the question a little bit, then I will add some new Java. The trick is for sure not new, but perhaps interesting that this is possible in Java.

```
static void pleaseDoNotDoThis() throws Exception {
    Field field = Boolean.class.getField("FALSE");
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, true);
}

public static void main(String args[]) throws Exception {
    pleaseDoNotDoThis();
    doit(1);
    doit("NO");
    doit(null);
    doit(Math.PI);
}

static void doit(long x) {
    System.out.format("(x == x + 2) = (%d == %d) = %s\n", x, x+2, (x == x + 2));
}

static void doit(String x) {
    System.out.format("(x == x + 2) = (%s == %s) = %s\n", x, x+2, (x == x + 2));
}

static void doit(double x) {
    System.out.format("(x == x + 2) = (%f == %f) = %s\n", x, x+2, (x == x + 2));
}

```

And the results:

```
(x == x + 2) = (1 == 3) = true
(x == x + 2) = (NO == NO2) = true
(x == x + 2) = (null == null2) = true
(x == x + 2) = (3,141593 == 5,141593) = true
(x == x + 2) = (Infinity == Infinity) = true

```

# Answer
> 4 votes
This VBScript solution works similarly to my JavaScript solution. I did not use a preprocessor yet the solution seems trivial.

```
y = 0
Function x
x = y
y = -2
End Function

If x = x + 2 Then
    WScript.Echo "True"
Else
    WScript.Echo "False"
End If

```

# Answer
> 4 votes
## Java

```
double x = Double.POSITIVE_INFINITY; // Double.NEGATIVE_INFINITY also works
System.out.println(x == x + 2);      // prints true

```

# Answer
> 4 votes
## Common Lisp

```
(let ((x   42)
      (x+2 42))
  (= x x+2))
;=> true

```

# Answer
> 3 votes
**Ada**

```
procedure test() is
  type x_type is mod 2;
  var x: x_type := 0; -- 0 or 1
begin
  if x /= x + 2 then
    put('Error');
  else
    put('Equal!');
  end if;
end test;

```

This is similar to Sage. We use a 1 bit integer which is allowed to wrap. We could also use a floating point, obviously.

# Answer
> 3 votes
## C#

I didn't see any rule stating x had to be a number:

```
class Program {
    public static Program operator +(Program x, int y) {
        return x;
    }

    static void Main(string[] args) {
        var x = new Program();
        Console.WriteLine(x == x + 2);
    }
}

```

I defined `x` in such a way, but I also defined the `+` operator for the object stored in `x`.

http://ideone.com/ylNyM

# Answer
> 3 votes
**JavaScript**

Here's a way do it without exploiting Infinity:

```
x = {
    value: 0,
    valueOf: function () {
        this.value += 2;
        return this.value;
    }
};

alert(x == x+2);

```

# Answer
> 3 votes
# C

If you evaluate `x == x+2` directly you will get a false, but I think it is interesting because it makes usage of a different language feature.

```
#include <stdio.h>

typedef struct {
  int bit:1;
} bitpack;

#define x a.bit
#define y b.bit

main()
{
  bitpack a, b;
  y = x + 2;
  if (x==y)
    printf("true\n");
  else
    printf("false\n");
}

```

# Answer
> 3 votes
## C

let the computer find a value for `x`

```
int main()
{
  float x=0;
  while(x!=x+2)x+=2;
  printf("%f\n",x);
}

```

# Answer
> 3 votes
# Haskell

```
Prelude> instance Num Bool where (+) _ _ = True
Prelude> let x = True
Prelude> (x==x+2)
True

```

You could call that cheating but I assume that's what this is about :D

To make it work with more than just bool:

```
import Prelude hiding ((==),(+))
infixl 9 ==
(==) _ _ = True
(+) _ _ = True

```

# Answer
> 3 votes
**GAP**

```
gap> x:=[];
[  ]
gap> x=x+2;
true

```

Here x is an empty array.

```
gap> x:=Z(2);
Z(2)^0
gap> x=x+2;
true

```

Here x is a generator of GF(2).

```
gap> x:=Integers;
Integers
gap> x=x+2;
true

```

Here x is the set of integers.

# Answer
> 3 votes
# Bash (0 character)

According to the rule, it looks like I can suggest my 0 character definition of `x` in bash, since without any definition, I have:

```
if (x==x+2); then echo "true"; fi

```

Output

```
true

```

Is it fair?

# Answer
> 2 votes
## PHP

```
<?php
  $x = 1e17;
  echo $x==$x+2;

```

Works in many other languages as well.

# Answer
> 2 votes
**Ruby**

```
def x;1.0/0;end
puts (x == x+2) #=> true

```

# Answer
> 2 votes
# Scala

```
case object x {
  def +(n:Int) = this
}
//defined module x

x == x + 2
//res0: Boolean = true

```

# Answer
> 2 votes
Java:

```
Float x = Float.MAX_VALUE;
System.out.println(x == (x + 2));

```

It prints "true"

```
System.out.println(x);

```

prints 3.4028235E38

```
System.out.println(x+2);

```

prints 3.4028235E38

I think this is caused by the loss of precision.

# Answer
> 2 votes
In my opinion, x must have a data type of just ONE BIT.

Since C99, there is the data type **\_Bool** ; So this should probably work:

```
_Bool x;
x = 0;
if (x == x + 2) ...

```

# Answer
> 2 votes
# Tcl, 22 chars.

```
proc (x args return\ 1

```

# Answer
> 2 votes
## J

```
x =: 1

```

There is no `==` operator in J, so`x==x+2` would actually mean `x=(=(x+2))`. Unary `=` is an operator, that will return `1` acting on any number, and as binary it is just an equality. So `1=(=(1+2))` =\> `1=(=3)` =\> `1=1` =\> `1`.

# Answer
> 2 votes
## JavaScript

```
x=Math.log(0)
x==x+2

```

Prints

`True`

# Answer
> 1 votes
## C#

Using infinity

```
Double x = Double.PositiveInfinity;
Console.WriteLine(String.Format("Result: {0}", x == x + 2));

```

Also works with

```
Double x = Double.NegativeInfinity

```

(this is actually the same as `1.0 / 0.0` approach)

# Answer
> 1 votes
# PHP

```
$isi = 1.0E+17;
var_dump($isi == $isi + 2);

```

---

```
$isi = 1e18;
var_dump($isi == $isi + 2);

```

---

```
$isi = 4.2E+20;
var_dump($isi == $isi + 2);

```

---

```
$isi = 9.2233720368548E+18;
var_dump($isi == $isi + 2);

```

---

```
$isi = 5.0E+19;
var_dump($isi == $isi + 2);

```

---

```
$isi = 6.0822444802213E+18;
var_dump($isi == $isi + 2);

```

---

```
$isi = 0x5468792130ABCDEF;
var_dump($isi == $isi + 2);

```

---

```
$isi = 6082244480221302255;
var_dump($isi == $isi + 2);

```

# Answer
> 1 votes
**Python:**

```
>>> x=float('inf')
>>> x==x+2
True

```

# Answer
> 1 votes
## Haskell

```
f x = x == (x+2) where (==)=(<)

```

Always returns `True`, except when x is `1/0`.

# Answer
> 1 votes
# Pascal

Here's a solution that takes a different approach (not the usual infinity trick).

```
Program xplus2;

Var value: integer;

Function x: integer;
Begin
   value := value-2;
   x := value;
End;

Begin
   If x=x+2 then
      Writeln('They are the same')
   else
      WriteLn('They are different');
End.

```

Works with 2+x too.

# Answer
> 1 votes
Python

```
>>> x=1e999
>>> x==x+2
True

```

# Answer
> 1 votes
### Haskell

```
f x = (x == x + 2)
    where x + 2 = x

```

Calling `f` with any argument (whose type is in the `Eq` typeclass) will evaluate to `True`.

# Answer
> 1 votes
Missing **GolfScript**?

`0:2;`
Then e.g. `15 2+` -\> 15

# Answer
> 1 votes
JavaScript

```
var x = Infinity;

```

So if you add anything to infinity it will remain infinity.

# Answer
> 1 votes
Trying to come up with something that doesn't fall under one of the existing seven groups is tough:

```
def x
  rand(1..3)
end

puts x==x+2

```

33% of the time, it's right all the time...

# Answer
> 1 votes
`$x == $х+2` for infinite pairs of numbers. Let's try it out.

# PHP

```
$х = 1;
$x = 3;

if ($x == $х+2)
    echo "LOL it works. Sort of black magic?";

```

Nah, it's not black magic. Truth is that one x is Kha, that as Wikipedia states, `it looks the same as the Latin letter X, in both uppercase and lowercase, both roman and italic forms.`

There's actually no difference between them, so even if there are two different variables, rules are not broken, since I assumed that a x is a Kha.

# Answer
> 1 votes
# SWI-Prolog

In query mode:

```
?- X = X+2, X == X+2.
X = X+2.

```

You just need to "assign" `X = X + 2`, then `X == X + 2` will be true. Why make things so complicated?

---

### Real explanation

In Prolog, `x` is an *atom*, so it is not possible to make `x == x + 2` returns true. Variables in Prolog must start with an uppercase letter or underscore.

Therefore, my solution will define (uppercase) `X` so that `X == X+2`.

In Prolog, `==` compares 2 terms according to standard order of terms. Therefore, we only need to *unify* (`=` operator) `X` and `X+2` before doing the comparison.

Note that the unification `X = X+2` unifies `X` with the infinite term `X = (((...)+2)+2)+2`, much like how the unification `X = f(X)` unifies `X` with the infinite term `X = f(f(f(...)))`.

In Prolog, when a query succeeds, it will return `true` if there is no variable, or it will return the variable binding which satisfies the query. This explains the output `X = X+2`.

# Answer
> 1 votes
# C

Defining x as `1==-2`

```
#include<stdio.h>
#define x 1==-2

main()
{
  printf("%d", (x==x+2) ) ;
}

```

# Answer
> 1 votes
**Scheme / Unicode**

```
(let
  ((２ 0) (x 9))
  (= x (+ x ２)))

```

I knew there had to be a Unicode character that looks like a 2 - and that there would be a language or interpreter lenient enough to accept it as a variable name.

# Answer
> 1 votes
# ECMAScript (also known as JavaScript):

```
x=1e17

```

# Answer
> 1 votes
# Haskell, denotational semantics

`x = undefined`

As most of you probably know, `undefined :: a` can be cast to any type - or in other words, every type contains a special value `undefined`, also called  (pronounced "bottom"). We say that  is *less defined* than any other inhabitant of that type, and while its a little too in-depth for this post,  can also be seen as a computation that never finishes.

Let's `import Data.Function`.

In there, there is a function called `fix`, which according to the Haskell docs finds the **least-defined** fixpoint of f, by repeatedly applying the function to itself. Let's recap:

We need to find a value `x`, for which `x = x + 2`, or, equivalently `x = (+2) x`. Lets factor `(+2)` into a function called `f`. We get `x = f x`, which is precisely the definition of a fixed point for the function `f`. Since we don't know `x` yet, we need a function that knows how to calculate a fixpoint, like `fix`; `x` is our placeholder for said fixpoint (`x = fix f`), so our whole equation becomes `fix f = f (fix f)`.

This is just the definition of `fix`, so `fix` indeed finds a fixed point for a given function!

What I'm trying to say is: To solve OP's problem, all we need to do is pipe `fix (+2)` through ghci. When we do that however, we see nothing, as ghci gets caught in an infinite loop. But since I said that infinite loops can be seen as ⊥, we arrive at the fact that `x = ⊥`, which by the way turns out to be the only solution to OP's question (who would have guessed).

# Answer
> 0 votes
the answer is infinity or - infinity because infinity+2=infinity you can't find any other number that it's bigger than itself+ a number

# Answer
> 0 votes
**Ruby**

```
1.9.3p125 :006 > x = Float::INFINITY  # or x = -Float::INFINITY
 => Infinity
1.9.3p125 :007 > x == x +2
 => true

1.9.3p125 :015 > x =Float::MAX
 => 1.7976931348623157e+308
1.9.3p125 :016 > x == x +2
 => true

```

# Answer
> 0 votes
In Scala, just override the "+" operator (really a function):

```
scala> class X { def +(a:Int)=this }
defined class X

scala> val x = new X
x: X = X@26e7127

scala> x == x+2
res3: Boolean = true

scala>

```

# Answer
> 0 votes
# Processing

```
float x=1e30;
print(x==x+2);

```

The output will be `true`

Not very creative, but yeah.

# Answer
> 0 votes
**Ruby**

That's surely cheating, but hey ...

```
#/usr/bin/env

class Fixnum
  def +(y)
    if self == 42
       self
    else
       self + y
    end
  end
end

```

Then for x being exactly 42 ... /me =\> \[ \]

# Answer
> 0 votes
# Python

```
>>> x=99999999999999999999999999999999999.
>>> x==x+2
True

```

Note the `.` at the end, which makes `x` a floating point number.

# Answer
> 0 votes
**Javascript**

Most compact, correct that I could figure.

```
x=1/0;x==x+2

```

I also tried futzin around with toString() and clever output variance with casting, but while the results were correct sequentially, the == would never be true.

# Answer
> 0 votes
## C++

I'm aware there have been a couple of similarly themed solutions, but here's mine nonetheless:

```
#include <iostream>

struct Plus {
  int x;
  Plus(int _x):x(_x){}
  Plus operator+(int _x) {
    return Plus(this->x + _x);
  }
  bool operator==(Plus _x) {
    return true;
  }
};

int main() {
  Plus x(0);
  std::cout << bool(x == x + 2);
}

```

# Answer
> 0 votes
## Python

I'm always looking for an excuse to use a class for golfing Python... alas, this isn't golf.

```
class foo:__add__=lambda a,b:a
x=foo()

```

Here, `x+2` is `x`, though `2+x` blows up with an error (I'd have to implement `__radd__`). I could have hacked equality testing instead, but I'd still need to implement `__add__`.

# Answer
> 0 votes
## Python

Any language with floats - no need to go all the way to infinity

```
x=9e9**9
x==x+2

```

# Answer
> 0 votes
# q/k

Pretty trivial using infinity (or null):

```
q)x:0w

x=x+2
1b

```

# Answer
> 0 votes
# Python

```
class X():
 def __eq__(a,b):
  return True
 def __add__(a,b):
  return True
x = X()
print x==x+2

```

```
$ python x.py
True

```

# Answer
> 0 votes
## Sage

```
sage: print oo
+Infinity
sage: oo+2==oo
True

```

# Answer
> 0 votes
## Groovy

```
Integer.metaClass.plus = { Integer y -> delegate }
def x = 0
assert x == x+2

```

The `plus` method is overridden to return the first number :-D

# Answer
> 0 votes
# C (GCC at least)

Using pointer arithmetic on an struct of size 0

```
#include <stdio.h>
typedef struct {} empty;

main(){
    empty *x;
    printf("%d\n", x==x+2);
}

```

# Answer
> 0 votes
## Coffeescript, 18 chars

```
x=1/0;alert x==x+2

```

# Answer
> 0 votes
Lua, used in various products including World of Warcraft, Wireshark, Nmap, Adobe Photoshop Lightroom, and the Nspire line of Texas Instruments graphing calculators, supports operator overloading (using "metamethods") for tables (associative arrays). This code works in both Lua 5.1 and 5.2:

```
local x = setmetatable({}, {
  __add = function(a, b)
    return a
  end
})

print(x == x + 2) -- true

```

# Answer
> 0 votes
## GolfScript

In Golfscript, you can redefine `+`, `2`, or `=` in order to make the statement true for any value of `x`! Any of the following lines would suffice:

```
{;}:+; #Redefine + to ignore the second summand
0:2;; #Redefine 2 to be 0
{;;1}:=; #Redine = to always return true

```

Then:

```
10:x; #Any x would work
x x 2+ = #x==x+2
-> 1

```

If you want the answer in the exactly format of the question, we can do some other nonsense:

```
{0}:(:x:=:+:2; #redefine all the characters in the expression to 0
{];1}:); #redefine ) to pop everything off the stack and then return 1

```

So then:

```
(x == x+2)  #That doesn't look like GolfScript!
-> 1

```

# Answer
> 0 votes
Little know fact about Haskell is it doesn't always do divide by 0 errors.

```
let x=1/0 in x==x+2

```

This is because when you add 2 to infinity, it doesn't get bigger. It is weird that such a mathematical language would just deal with infinity so nonchalantly.

# Answer
> 0 votes
# Rebol

Version of the Perl answer by *memowe*:

```
v: 0
x: does [v: v - 2]

```

With above defined you can now test in Rebol console...

```
>> x == (x + 2)
== true

>> equal? x x + 2
== true

```

And a Rebol version of *Joshua Taylor* Common Lisp answer:

```
x: 42
x+2: 42

```

In console...

```
>> x == x+2
== true

```

# Answer
> 0 votes
## Groovy

```
x = Float.MAX_VALUE
assert x==x+2

```

Float.MAX\_VALUE = 3.4028235E38
Float.MAX\_VALUE + 2 = 3.4028234663852886E38
Which the == determines is close enough.

# Answer
> 0 votes
# C++

Had some fun with operator overloading

```
#include <iostream>

class Tautology
{
  public:
    const Tautology& operator+(int n)
    {
        // Anything to make x + 2 compile
        return *this;
    }

    bool operator==(const Tautology& t)
    {
        // Any tautology equals any other
        return true;
    }
};

int main()
{
   Tautology x;
   std::cout << (x == x + 2 ? "true" : "false");

   return 0;
}

```

# Answer
> 0 votes
# C++ / C-sharp

Here's another one depending on the definition of an infinite double according to the IEEE standard (http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlf101a.doc%2Fxlfopg%2Ffpieee.htm).

```
int main()
{
   double x = 0x7FF0000000000000; // Positive infinity
   cout << (x == x + 2 ? "true" : "false");

   return 0;
}

```

In C# this could be written more readably as

```
 double x = double.PositiveInfinity;

```

# Answer
> 0 votes
## JavaScript

Exploiting the big number / infinity approach as shortly as possible.

12 chars:

```
9e99==9e99+2 // true

```

10 chars

```
1/0==1/0+2 // true

```

# Answer
> 0 votes
# JavaScript

```
var x = {y: 0, toString: function() {return (this.y+=2)}};
console.log(x == x+2); // true

```

When you add number to an object you indirectly call `toString` method of this object. toString method returns number... Right side becomes number, then `==` operator converts `x` to primitive by using it's `toString` method.

Interesting article about related idea: Fake operator overloading in JavaScript.

# Answer
> 0 votes
## Python (18)

```
>>> x=True;[x][x==2+x]
True

```

Gives True in interactive mode.

# Answer
> 0 votes
# J

```
   x=:!123
   x=x+2
1

```

This is also reliant on the floating point trick: `!123x=2+!123x` returns 0(`=` actually is the comparison operator, so no trickery there)

Or, maybe even better:

```
   x=:_
   x=x+2
1

```

simply sets x to infinity.

# Answer
> 0 votes
**Python 2.7, 46 chars**

I see a lot of Python answers abusing real number limitations, I'm surprised no one's submitted this disgusting Python hack yet.

```
x=True;True=False;
if True is (x==x+2): print x

```

Returns:

```
True

```

# Answer
> 0 votes
# Javascript

```
x=1/0;x==x+2

```

This doesn't work in strict mode, nor without a global variable (i.e `window`). Tested in `Firefox 38`.

# Answer
> 0 votes
# Ruby

With some monkey patching, everything is possible.

```
class Fixnum
    def ==(obj)
        # Check if difference between self and obj is 0, -2 or +2
        "#{self-obj}"=~/0|\-?2/ ? true : false
    end
end

```

As I can't use `self==obj || self==obj+2 || self==obj-2`, as that would cause a StackError, I first transform them into Strings, then check if the difference matches `"0"`, `"-2"` or `"2"`

### Test cases

```
# Make sure `x` is from type Fixnum
x=0

p (x==x+2) # => true
p (x+2==x) # => true
p (x==x)   # => true
p (x==x+1) # => false
p (x==x+3) # => false

```

# Answer
> 0 votes
# Mathematica

```
x=∞

```

Mathematica is perfectly happy to reason (within reason) with infinity, and knows that  and `∞+2` are the same!

# Answer
> 0 votes
# ForceLang

```
def x set y -2+y
io.write x=x+2

```

# Answer
> -4 votes
```
 cout << bool(x == x+2);

```

! is not needed at all

# Answer
> -4 votes
JavaScript

```
!!("x==x+2") // true

```

---
Tags: math, arithmetic, c
---


title: The codegolf object

text:
# Question
Title: The codegolf object
Imagine this, we have an environment with a global scope containing just a single object, called `codegolf`. This object has a single child called `stackexchange`, which has a property called `com`.
Accessing this property would look like `codegolf.stackexchange.com`.

### The challenge

The input of your program/function will be a string trying to access a property on the global scope. Whenever this property is found, you shall print/return a truthy value. If the property isn't found, a falsy value shall be printed/returned. The catch: when you try to access a property on a non-existant object, your program should throw any kind of error¹.

To make things a bit easier, you may assume that input will always be `[a-z.]`, it will never be empty, it will never have repeating `.`'s and it will never start or end with a `.`. So `codegolf.` is an invalid input.

### Test cases

```
codegolf.stackexchange.com => 1 // or any other truthy value
codegolf.stackexchange.net => 0 // or any other falsy value
codegolf.stackexchange => 1
codegolf.foo => 0
codegolf => 1
foo => 0
codegolf.com => 0
codegolf.constructor => 0

codegolf.foo.bar => Error (since foo is undefined)
codegolf.stackexchange.com.foo => Error (since com is a value, not an object)
codegolf.stackexchange.com.foo.bar => Error
foo.stackexchange.com => Error
foo.bar => Error
foo.bar.baz => Error

```

This is , shortest code in bytes wins

¹ if (and only if) your language of choice doesn't support errors **at all**, you must output something which makes it clear that this is an error. For example, if you use 1 for truthy and 0 for falsy, you may use "e" for an error. Be consistent in your return values and explain the behaviour in your post.

# Answer
> 8 votes
# JavaScript, 135 bytes

```
v=>(c=(p,i)=>new Proxy({}, {get:(o,q)=>(r=q==p[i]?c(p,i+1):o.$,i==3?r||z:r)}),x=c(["codegolf","stackexchange","com"],0),!!eval("x."+v))

```

Reworked the first attempt to prevent builtin keys being accessible, at this point its going to be better to use a different approach, but hey!

Returns true for valid, false for missing and errors on error.

# Answer
> 4 votes
## JavaScript (ES6), 87 bytes

Returns `false`/ `true` or throws `ReferenceError`.

```
s=>s.split`.`.map((w,i)=>e|['codegolf','stackexchange','com'][i]!=w&&e++,e=0)&&e>1?X:!e

```

```
let f =

s=>s.split`.`.map((w,i)=>e|['codegolf','stackexchange','com'][i]!=w&&e++,e=0)&&e>1?X:!e

console.log(f('codegolf.stackexchange.com')); // => true
console.log(f('codegolf.stackexchange.net')); // => false
console.log(f('codegolf.stackexchange'));     // => true
console.log(f('codegolf.foo'));               // => false
console.log(f('codegolf'));                   // => true
console.log(f('foo'));                        // => false
console.log(f('codegolf.com'));               // => false

console.log(f('codegolf.foo.bar'));           // => Error
```

### Probabilistic version, 78 bytes (non-competing)

Because all properties are guaranteed to match `[a-z]`, we can give this a try:

```
s=>s.split`.`.map((w,i)=>e|[162,6,2][i]-parseInt(w,36)%587&&e++,e=0)&&e>1?X:!e

```

Apart from the fact that `587` is a prime and leads to rather short values for the words we are interested in, this is a rather random modulo choice.

Although it does pass all test cases, it is of course likely to return false-positives.

```
let f =

s=>s.split`.`.map((w,i)=>e|[162,6,2][i]-parseInt(w,36)%587&&e++,e=0)&&e>1?X:!e

console.log(f('codegolf.stackexchange.com')); // => true
console.log(f('codegolf.stackexchange.net')); // => false
console.log(f('codegolf.stackexchange'));     // => true
console.log(f('codegolf.foo'));               // => false
console.log(f('codegolf'));                   // => true
console.log(f('foo'));                        // => false
console.log(f('codegolf.com'));               // => false

console.log(f('codegolf.foo.bar'));           // => Error
```

# Answer
> 3 votes
## Batch, ~~269~~ 231 bytes

```
@echo off
set/ps=
set w=1codegolf
for %%a in (%s:.= %)do call:l %%w
echo %w:~0,1%
exit/b
:g
if
:l
if %w:~-1%==. goto g
if not %1==%w% set w=0.&exit/b
set w=1com
if %1==com set w=1.
if %1==codegolf set w=1stackexchange

```

Takes input on STDIN; throws a syntax error for an invalid property. Works by using `w` as a state machine. If `w` ends with a `.` this means that the next property access is invalid. Edit: Saved 17 bytes by using the syntax error to abort the batch script. Saved 21 bytes by realising that one of my assignments could be unconditional.

# Answer
> 2 votes
# Javascript, ~~84~~ 82 bytes

Not short enough to win, but since I am a beginner I thought it would be fun to share it. Maybe someone has a suggestion for improvement.

```
s=>s.split`.`.length>3&&e||!!eval('codegolf={stackexchange:{com:true}};window.'+s)

```

It passes all the tests in the question, returns `true` for existing value, `false` for non-existent and it throws an error if you try to get a property of a non-existent or non-object variable. However I now realize that this solution has some issues as well. As pointed out by @Florent in the comments it returns true when string prototype properties such as `.toString` are called.

**Edit**: 2 bytes shorter thanks to @MamaFunRoll

Test snippet:

```
var f =
s=>s.split`.`.length>3&&e||!!eval('codegolf={stackexchange:{com:true}};window.'+s)

console.log(f('codegolf.stackexchange.com')) //true
console.log(f('codegolf.stackexchange.net')) //false
console.log(f('codegolf.stackexchange')) //true
console.log(f('codegolf.foo')) //false
console.log(f('codegolf')) //true
console.log(f('foo')) //false
console.log(f('codegolf.com')) //false

console.log(f('codegolf.foo.bar')) // TypeError
console.log(f('codegolf.stackexchange.com.foo')) //ReferenceError
console.log(f('codegolf.stackexchange.com.foo.bar')) //ReferenceError
console.log(f('foo.stackexchange.com')) // TypeError
console.log(f('foo.bar')) // TypeError
console.log(f('foo.bar.baz')) // TypeError
```

# Answer
> 1 votes
# C, 98 ~~112~~ 113 bytes

```
f(char*a){char*c="codegolf.stackexchage.com";while(*c&&*c==*a)++a,++c;return strchr(a,46)?*(a=0):!(*a|*c&*c-46);}

```

ungolfed

```
f(char*a){char*c="codegolf.stackexchage.com";
          while(*c&&*c==*a)++a,++c;
          return strchr(a,46)?*(a=0):!(*a|*c&*c-46);
         }

f(codegolf.stackexchage.com)=1
f(codegolf.stackexchage.net)=0
f(codegolf.stackexchage)=1
f(codegolf.foo)=0
f(codegolf)=1
f(foo)=0

```

for the below it has to seg fault

```
f(codegolf.stackexchage.com.foo)
f(foo.bar)
f(foo.bar.baz)
f(codegolf.foo.bar)
f(foo.v)

```

# Answer
> 1 votes
# JavaScript, 173 bytes

```
function d(a){var b="codegolf",u="stackexchange",c=a.split("."),e="e";return c.length==1?c[0]==b:c.length==2?c[0]==b?c[1]==u:e:c.length==3?c[0]==b?c[1]==u?c[2]=="com":e:e:e}

```

Works with IE 10, so should work on major modern browsers.

**Try it here (+ ungolfed)**

# Answer
> 1 votes
# C#, 155 bytes

Wasn't going to be the shortest but thought it would be fun give it a go in C#...

```
bool f(string s){var a=s.Split('.');int e=0,l=a.Length-1,i=l;for(;0<=i;i--){e+=a[i]!=new[]{"codegolf","stackexchange","com"}[i]?i<l?s[-1]:1:0;}return e<1;}

```
* Splits the string and reverse iterates through the result.
* A non matching element more than 1 iteration deep, errors (throwing an `IndexOutOfRangeException` by accessing a char at -1 position in the string).
* Otherwise, returns false if any elements didn't match.

.NET Fiddle

# Answer
> 1 votes
# Ruby, ~~84~~ 80 bytes

Anonymous function which returns `true` or `false`, or divides by zero to raise error:

```
->s{k=1;s.split(?.).zip(%w[codegolf stackexchange com]){|i,o|1/0if !k;k=i==o};k}

```

Try it online

# Answer
> 0 votes
# Java, ~~187~~ 138 bytes

Version 2.0(**138** bytes): Idea shamelessly stolen from @Jamie.

```
l->{for(String []a=l.split,int l=i=a.length-1,e=0;i>=0;e+=a[i]!=new String[]{"codegolf","stackexchange","com"}[i]?i<l?s[-1]:1:0)return e;}

```

Version 1.0(**187** bytes):

```
l->{String[]a=l.split(".");return a[0].equals("codegolf")?(a.length<2?1:(a[1].equals("stackexchange")?(a.length<3?1:(a[2].equals("com")?1:0)):(a.length<3?0:a[-1]))):(a.length<2?0:a[-1]);}

```

Explanation of the return part:

```
return a[0].equals("codegolf")?(a.length<2?1:(a[1].equals("stackexchange")?(a.length<3?1:(a[2].equals("com")?1:0)):(a.length<3?0:a[-1]))):(a.length<2?0:a[-1]);
return                                                                                ;
       a[0].equals("codegolf")?                                                                                :
                               (a.length<2? :                                                                                ) (a.length<2? :     )
                                           1 (a[1].equals("stackexchange")?                                       :                    )              0 a[-1]
                                                                           (a.length<3? :                        ) (a.length<3? :     )
                                                                                1 (a[2].equals("com")? : )              0 a[-1]
                                                                                1 0

```

---
Tags: code-golf, regular-expression
---


title: Collapse ascii-art

text:
# Question
Title: Collapse ascii-art
# Challenge

Given a rectangular grid of printable ascii characters as a string or through standard input, write a function or program that collapses the non-space characters into a pile on the bottom.

## The rules:

* The output has the same dimensions and characters as the input.
* A non-space character at `(row a,column b)` can't have a space character `' '` at `(a-1, b)`, `(a-1,b-1)` or `(a-1,b+1)`, where rows are numbered up from the bottom-most. This has the consequence that all vertical piles should collapse sideways.
* A non-space character can travel at most `(initial height - final height)` places to the left or right (see Fig. 1).
* You can assume the picture has enough space to collapse without characters falling out of the screen.

Figure 1: possible final locations for characters `@#$` shown as `x,y,z`, respectively.

```
..............
...@..........
..xxx.........
.xxxxx...#....
xxxxxxx.yyy.$.

```

The order in which characters collapse can be chosen freely. Trailing spaces are not okay but trailing newlines are.

This is , so the shortest answer in bytes wins!

## Example

```
                 (__)
                 (oo)
           /------\/
          / |    ||
         *  /\---/\
            ~~   ~~
..."Have you mooed today?"...

```

One possible output:

```

                --(_
           /----|/|(o_)
          /|/~\---~\\/o)
..."Have*you~mooed~today?"...

```

# Answer
> 4 votes
## JavaScript (ES6), ~~100~~ ~~90~~ 88 bytes

```
f=s=>s==(l=s.search`
`,s=s.replace(eval(`/(\\S)([^]{${l-1},${l+1}}) /`),` $2$1`))?s:f(s)
s=`                 (__)
                 (oo)
           /------\\/
          / |    ||
         *  /\\---/\\
            ~~   ~~
..."Have you mooed today?"...`
console.log(s)
console.log(f(s))
```

Requires the the string to have at least two lines and all lines padded to equal length. Output for the example image:

```
              ( --
            /|---/|-(o__
          */~~\---~\|\/o))
..."Have you/mooed~today?"...

```

Note that as it tries to move elements to the right if possible, the `*` did not fall between the `Have` and the `you`.

Edit: Saved 10% thanks to @ETHproductions. Saved another 2 bytes thanks to @DanielIndie.

# Retina 0.8.2, 50 bytes

```
+`(?<=(.)*)(\S)(.*¶(?<-1>)?(?>(?<-1>.)*).?)
 $3$2

```

Try it online! A slightly different approach to my JavaScript answer, this uses a balancing group to match a space below the non-space character; the `(?<-1>)?` allows the space to be one column to the left while the `.?` allows the space to be one column to the right.

# Retina, 40 bytes

```
~0L$`.(.*)¶
+s`(\S)(.{$.1,$.&}) ¶ $$2$$1

```

Try it online! Port of my JavaScript answer. The `0L$` atomic stage takes the input and substitutes the two lengths into the second line resulting in the command that actually performs the replacement, which is then evaluated on the original input by the `~` compound stage.

# Answer
> 3 votes
## Python 2, 298 bytes

```
a=input()
L=len(a);s=' '
a=[list(s*L+l.ljust(L+max(map(len,a))))for l in a]
t=1
while t:
 t=0
 for y in range(L-1):
  for x in range(len(a[y])):
   c=a[y][x];C=a[y+1][x-1:x+2]
   if s!=c and s in C:t=1;a[y][x]=s;a[y+1][[[x+1,x][C[1]==s],x-1][C[0]==s]]=c
for l in map(''.join,a):print l[L:].rstrip()

```

Takes input as a list of strings (one per line)

Example: Input:

```
['                 (__)',
'                 (oo)',
'           /------\/',
'          / |    ||',
'         *  /\---/\ ',
'            ~~   ~~',
'..."Have you mooed today?"...']

```

Output:

```
              (
            -----/|-(o__
         //|~~\---~\|\/o))
..."Have*you/mooed~today?"...

```

# Answer
> 3 votes
**C, 252 bytes**

```
e=1,l,c,i,j,p,r,w,a[999];f(){while((i=getchar())>0)a[w++]=i,i<16?l++:0,l?0:c++;while(e)for(i=e=0;i<c;i++)for(j=l;j>=0;j--)e=(r=a[p=j*(c+1)+i]-32?a[r=p+c+1]-32?a[r=p+c]-32?a[r=p+c+2]-32?0:r:r:r:0)?l=a[p],a[p]=a[r],a[r]=l:e;for(i=0;i<w;)putchar(a[i++]);}

```

Ungolfed test code:

```
#include <stdio.h>

e=1,l,c,i,j,p,r,w,a[999];
f()
{
    // counting lines and columns
    while ((i = getchar())>0)a[w++] = i, i<16 ? l++ : 0, l ? 0 : c++;
    // main shaking loop
    while (e) // repeat while collapsing
        for (i = e = 0; i < c; i++) // columns loop
            for (j = l; j >= 0; j--) // lines loop
                e = ( // remember that collapsing was
                     r = // find place to collapse
                         a[p = j*(c + 1) + i] - 32 ? // if not space
                             a[r = p + c + 1] - 32 ? // if char under the current is not a space
                                 a[r = p + c] - 32 ? // see one position left
                                    a[r = p + c + 2] - 32 ? 0 // then one position right
                                                          : r
                                    : r
                                 : r
                             : 0
                         ) ? // and if place was found
                           l=a[p],a[p]=a[r],a[r]=l // replace values in positions p and r
                           : e;
    //print resulting picture
    for(i=0;i<w;)putchar(a[i++]);
}

int main(void)
{
    int cnt;
    FILE * testf = fopen("caw.txt","w");
    char testd[][31] = {
        "                 (__)        \n",
        "                 (oo)        \n",
        "           /------\\/         \n",
        "          / |    ||          \n",
        "         *  /\\---/\\          \n",
        "            ~~   ~~          \n",
        "...\"Have you mooed today ? \"...",
        "" };
    // prepare data for test
    printf("Initial data:\n");
    for(cnt = 0; cnt < 7; cnt++)
    {
        printf("%s", testd[cnt]);
        fprintf(testf, testd[cnt]);
    }
    fclose(testf);
    // redirect standard input
    freopen("caw.txt", "r", stdin);
    printf("\n\nResult:\n");
    // start test
    f();
}

```

Result of test:

# Answer
> 1 votes
# JavaScript, 286 bytes

```
b=>eval('f=b=>b==null||" "==b;b=b.split`\n`.map(b=>[...b]);a:for(;;){for(c=0;c<b.length-1;c++)for(g=b[c],d=0;d<g.length;d++){h=g[d];if(!f(h)){e=0;f(b[c+1][d])?e=2:f(b[c+1][d-1])?e=1:f(b[c+1][d+1])&&(e=3);if(e){b[c+1][d+e-2]=h;b[c][d]=" ";continue a}}}break}b.map(b=>b.join``).join`\n`')

```

## Examples

```
// Here I assume that you've assigned the above function to `fall`
console.log(fall(`
                 (__)
                 (oo)
           /------\/
          / |    ||
         *  /\---/\\
            ~~   ~~
..."Have you mooed today?"...`))

```

Output:

```
                -
            /--(-\--(__
          /|~~---/~||/oo))
..."Have*you/mooed~today?"...

```

Another example:

```
console.log(fall(`
 (\__/)  .~    ~. ))
 /O O  ./      .'
{O__,   \    {
  / .  . )    \\
  |-| '-' \    }
 .(   _(   )_.'
'---.~_ _ _&`))

```

Output:

```
    _ , /
  OO/__'_.. .
 {.(|-|.(O'))/.~{
/('---.~___-_&)_.'}\~.'))

```

## Ungolfed function

```
function fall(input) {
  let move = true
  let lines = input.split("\n").map(line => line.split(""))
  let isSpace = c => c == null || c == " "
  loop: for (;;) {
    for (let y = 0; y < lines.length - 1; y++) {
      let line = lines[y]
      for (let x = 0; x < line.length; x++) {
        let ch = line[x]
        if (!isSpace(ch)) {
          let dx = 0
          if (isSpace(lines[y+1][x])) { dx = 2 }
          else if (isSpace(lines[y+1][x-1])) { dx = 1 }
          else if (isSpace(lines[y+1][x+1])) { dx = 3 }
          if (dx) {
            lines[y + 1][x + dx - 2] = ch
            lines[y][x] = " "
            continue loop
          }
        }
      }
    }
    break
  }
  return lines.map(line => line.join("")).join("\n")
}

```

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


title: Peel the potato

text:
# Question
Title: Peel the potato
This is a potato:

```
  @@
 @@@@
@@@@@@
@@@@@@
 @@@@
  @@

```

More generally, a size N potato is defined as the following shape:

If N is even, it is 2 centered `@` symbols, followed by 4 centered `@` symbols, followed by 6 centered `@` symbols, all the way up to N centered `@` symbols; then, N centered `@` symbols, followed by N-2 centered `@` symbols, all the way down to 2.
If N is odd, a size N potato is generated in the same way as described above, but we begin with 1 `@` symbol, rather than 2.

A potato is peeled by starting in the top right corner, and removing one `@` sign each step, going in a counterclockwise fashion. For instance, peeling a size-3 potato looks like this:

```
 @
@@@
@@@
 @

```

---

```

@@@
@@@
 @

```

---

```

 @@
@@@
 @

```

---

```

 @@
 @@
 @

```

---

```

 @@
 @@

```

---

```

 @@
 @

```

---

```

 @
 @

```

---

```

 @

```

# Challenge

Write a program, that, given an integer input, displays all of the steps of peeling a potato of that size.
Trailing whitespace/newlines are allowed.

# Scoring

This is ; the shortest code in bytes wins.

## Sample Test Cases

***N=2***

```
@@
@@

@
@@

@@

 @

```

***N=7***

```
   @
  @@@
 @@@@@
@@@@@@@
@@@@@@@
 @@@@@
  @@@
   @

  @@@
 @@@@@
@@@@@@@
@@@@@@@
 @@@@@
  @@@
   @

   @@
 @@@@@
@@@@@@@
@@@@@@@
 @@@@@
  @@@
   @

   @@
  @@@@
@@@@@@@
@@@@@@@
 @@@@@
  @@@
   @

   @@
  @@@@
 @@@@@@
@@@@@@@
 @@@@@
  @@@
   @

   @@
  @@@@
 @@@@@@
 @@@@@@
 @@@@@
  @@@
   @

   @@
  @@@@
 @@@@@@
 @@@@@@
  @@@@
  @@@
   @

   @@
  @@@@
 @@@@@@
 @@@@@@
  @@@@
   @@
   @

   @@
  @@@@
 @@@@@@
 @@@@@@
  @@@@
   @@

   @@
  @@@@
 @@@@@@
 @@@@@@
  @@@@
   @

   @@
  @@@@
 @@@@@@
 @@@@@@
  @@@
   @

   @@
  @@@@
 @@@@@@
 @@@@@
  @@@
   @

   @@
  @@@@
 @@@@@
 @@@@@
  @@@
   @

   @@
  @@@
 @@@@@
 @@@@@
  @@@
   @

   @
  @@@
 @@@@@
 @@@@@
  @@@
   @

  @@@
 @@@@@
 @@@@@
  @@@
   @

   @@
 @@@@@
 @@@@@
  @@@
   @

   @@
  @@@@
 @@@@@
  @@@
   @

   @@
  @@@@
  @@@@
  @@@
   @

   @@
  @@@@
  @@@@
   @@
   @

   @@
  @@@@
  @@@@
   @@

   @@
  @@@@
  @@@@
   @

   @@
  @@@@
  @@@
   @

   @@
  @@@
  @@@
   @

   @
  @@@
  @@@
   @

  @@@
  @@@
   @

   @@
  @@@
   @

   @@
   @@
   @

   @@
   @@

   @@
   @

   @
   @

   @

```

## Catalog

Based on Is this number a prime?

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><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="language-list"> <h2>Shortest Solution 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> <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> <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><script>var QUESTION_ID = 101224; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 12012; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 7 votes
## Perl, 129 bytes

128 bytes of code + `-n` flag.

```
$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;say$_=$p;say y/A/ /r while s/(^| )A(.*
? *)@/$1 $2A/m||s/@( *
?.*)A/A$1 /||s/@/A/

```

You'll need `-nE` flags to run it :

```
perl -nE '$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;say$_=$p;say y/A/ /r while s/(^| )A(.*
? *)@/$1 $2A/m||s/@( *
?.*)A/A$1 /||s/@/A/' <<< 7

```

**Explanations:** (I'll detail them more when I have a moment)
The first part, `$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;`, generates the initial potato: it starts from the middle line of the potato, and adds two lines at each iteration: one before the previous string, one after. Note that `$"` is a space, and since `$n` isn't initialized, it starts at 0, and `$/` is a newline.

Note much to say about the `say$_=$p;` that prints the initial potato while storing it in `$_` (which will later be easier to manipulate).

Finally, `say y/A/ /r while s/(^| )A(.*\n? *)@/$1 $2A/m||s/@( *\n?.*)A/A$1 /||s/@/A/` peels the potato. The last position where a `@` was removed contains a `A` (it's arbitrary, it could have be any symbol). So each iteration consist in finding the `A`, replacing it with a space, and in the meantime replacing the next `@` with a `A`. That's done thanks to two regex: `s/(^| )A(.*\n? *)@/$1 $2A/m` when the `A` is on the left side of the potato (`A(.*\n? *)@` allows to go on the right or down), and `s/@( *\n?.*)A/A$1 /` when the `A` is on the right side (`@( *\n?.*)A` allows to go up or on the left). `s/@/A/` replaces the first `@` with a `A` (that's the initialization). Since we always have a `A` in the string, we need to replace it with a space when printing it, that's what `y/A/ /r` does.

---

**Just for the eyes**, the animated version looks fairly nice: (to run in a terminal, it's roughly the same code but with `clear` and `sleep`)
```
perl -nE 'system(clear);$p=($r=$"x$n++."@"x$_.$/).$p.$r,$_-=2while$_>0;say$_=$p;select($,,$,,$,,0.1),system(clear),say y/A/ /r while(s/(^| )A(.*\n? *)@/$1 $2A/m||s/@( *\n?.*)A/A$1 /||s/@/A/)&&/@/' <<< 10

```

# Answer
> 5 votes
## Befunge, ~~319~~ 254 bytes

```
&:00p1+:40p2/10p>:40g%20p:40g/30p\:10g30g`:!00g:2%!-30g-*\30g*+:20g1+v
+10g-::40g\-*2*30g+\-1+00g2%!+\00g2/1++20g-:::40g\-*2*+30g-\4*00g2*-v>
v+1\,-**2+92!-g02g00**84+1`\+*`g02g01\*!`g02g01+**!-g02\`g03:/2g00-4<
>:40g00g:2%+*`!#v_$1+:55+,00g::*1-2/+`#@_0

```

The motivation for this algorithm was to try and avoid branching as much as possible, since a single path of execution is generally easier to golf. The code is thus comprised of just two loops: the outer loop iterating over the frames of the peeling process, and the inner loop rendering the potato for each frame.

The rendering loop is essentially just outputting a sequence of characters, the character for each iteration being determined by a rather complicated formula that takes the frame number of the peeling process and the index of the output sequence and returns either an `@`, a space, or a newline, as required.

Try it online!

# Answer
> 3 votes
# Python 3.5.1, 520 bytes

```
n=int(input())L=lenR=rangeP=printdefg(a,b):f=list(a)ifb:foriinR(L(f)):iff[i]=="@":f[i]=""breakelse:foriinR(L(f)-1,-1,-1):iff[i]=="@":f[i]=""breakreturn"".join(f)l=[]s=(2-n%2n)*(((n-2n%2)/2)1)i=2-n%2whilei<=n:l.append("@"*i)i=2j=L(l)-1whilej>=0:l.append(l[j])j-=1y=[rforrinR(int((L(l)/2)-1),-1,-1)]forhinR(L(y)-1,-1,-1):y.append(y[h])defH(q):foreinR(L(l)):P((""*y[e])q[e])P("")H(l)k=0m=0whilek<s:fortinR(L(l)):if'@'inl[t]andm%2==0:l[t]=g(l[t],True)k=1H(l)if'@'inl[t]andm%2==1:l[t]=g(l[t],False)k=1p=l[:]p.reverse()H(p)m=1

```

# Explanation

Basic idea: Alternate between iterating down each line and removing leftmost character and iterating up each line removing rightmost character while there are still `@`s left.

```
n=int(input())
L=len
R=range
P=print
# g() returns a line in the potato with leftmost or rightmoxt '@' removed
def g(a,b):
    f=list(a)
    if b:
        for i in R(L(f)):
            if f[i]=="@":
                f[i]=" "
                break
    else:
        for i in R(L(f)-1,-1,-1):
            if f[i]=="@":
                f[i]=" "
                break
    return "".join(f)

l=[]
# s is the total number of '@'s for size n
s=(2-n%2+n)*(((n-2+n%2)/2)+1)
i=2-n%2

# store each line of potato in l
while i<=n:
    l.append("@"*i)
    i+=2
j=L(l)-1
while j>=0:
    l.append(l[j])
    j-=1

# this is used for spacing
y=[r for r in R(int((L(l)/2)-1),-1,-1)]
for h in R(L(y)-1,-1,-1):
    y.append(y[h])

# print the potato
def H(q):
    for e in R(L(l)):
        P((" "*y[e])+q[e])
    P("\n")

H(l)
k=0
m=0

# while there are still '@'s either
# go down the potato removing leftmost '@'
# go up the potato removing rightmost '@'
while k<s:
    for t in R(L(l)):
        if '@' in l[t] and m%2==0:
            l[t]=g(l[t],True)
            k+=1
            H(l)
        if '@' in l[t] and m%2==1:
            l[t]=g(l[t],False)
            k+=1
            p=l[:]
            p.reverse()
            H(p)
    m+=1

```

Overall a sad attempt at a straightforward procedure.

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


title: Railroad switch network

text:
# Question
Title: Railroad switch network
## Introduction

Suppose we have a network of railroads. Each junction in the network is controlled by a *switch*, which determines whether an incoming train turns left or right. The switches are configured so that each time a train passes, the switch changes direction: if it was pointing left, it now points right, and vice versa. Given the structure of the network and the initial positions of the switches, your task is to determine whether a train can eventually pass through it.

This challenge was inspired by this article.

## Input

Your input is a non-empty list **S** of pairs **S\[i\] = (L, R)**, where each of **L** and **R** is an index of **S** (either 0-based or 1-based), in any reasonable format. This includes a **2 × N** matrix, an **N × 2** matrix, two lists of length **N**, or a list of length **2N**.

Each pair represents a junction of the network, and **L** and **R** point to the junctions that are reached by turning left and right from the junction. They may be equal and/or point back to the junction **i**. All junctions initially point left.

## Output

A train is placed on the first junction **S\[0\]**. On each "tick", it travels to the junction that its current switch points to, and that switch is then flipped to point to the other direction. Your output shall be a truthy value if the train eventually reaches the last junction **S\[length(S)-1\]**, and a falsy value if is doesn't.

## Example

Consider this network:

This corresponds to the input `[(1,2),(0,3),(2,0),(2,0)]` The train travels the following route:

```
[0] -L-> [1] -L-> [0] -R-> [2] -L-> [2] -R-> [0] -L-> [1] -R-> [3]

```

Since the train reached its destination, the last junction, the correct output is truthy.

For the input `[(1,2),(0,3),(2,2),(2,0)]` we have the following route:

```
[0] -L-> [1] -L-> [0] -R-> [2] -L-> [2] -R-> [2] -L-> [2] -R-> ...

```

This time, the train got stuck in the junction `2`, and will never reach the destination. The correct output is thus falsy.

## Rules and scoring

You can write a full program or a function, and the lowest byte count wins. Consider skimming the article, as it may contain useful info for writing a solution.

## Test cases

These have 0-based indexing.

```
[(0,0)] -> True
[(0,1),(0,0)] -> True
[(0,0),(1,0)] -> False
[(1,2),(0,3),(2,0),(1,2)] -> True
[(1,2),(0,3),(2,2),(1,2)] -> False
[(1,2),(3,0),(2,2),(1,2)] -> True
[(1,2),(2,0),(0,2),(1,2)] -> False
[(0,2),(4,3),(0,4),(1,2),(4,1)] -> True
[(4,0),(3,0),(4,0),(2,0),(0,4)] -> True
[(1,4),(3,2),(1,4),(5,3),(1,0),(5,2)] -> True
[(3,1),(3,2),(1,5),(5,4),(1,5),(3,2)] -> True
[(1,2),(5,0),(3,2),(2,4),(2,3),(1,6),(1,2)] -> False
[(4,9),(7,3),(5,2),(6,4),(6,5),(5,4),(3,2),(6,8),(8,9),(9,1)] -> False
[(2,7),(1,5),(0,8),(9,7),(5,2),(0,4),(7,6),(8,3),(7,0),(4,2)] -> True
[(4,9),(7,3),(3,2),(8,3),(1,2),(1,1),(7,7),(1,1),(7,3),(1,9)] -> False
[(0,13),(3,6),(9,11),(6,12),(14,11),(11,13),(3,8),(8,9),(12,1),(5,7),(2,12),(9,0),(2,1),(5,2),(6,4)] -> False
[(6,0),(1,2),(14,1),(13,14),(8,7),(6,4),(6,10),(9,10),(10,5),(10,9),(8,12),(14,9),(4,6),(11,10),(2,6)] -> False
[(1,3),(9,17),(5,1),(13,6),(2,11),(17,16),(6,12),(0,8),(13,8),(10,2),(0,3),(12,0),(3,5),(4,19),(0,15),(9,2),(9,14),(13,3),(16,11),(16,19)] -> True

```

# Answer
> 4 votes
## CJam, ~~30~~ 29 bytes

```
0l~_,m!{_2$=(@@2$+3$\t}*,(])&

```

Uses 0-based inputs and prints the index of the terminal node if the terminal node is ever reached.

This is super inefficient. You wouldn't want to test this on inputs with more than 10 nodes. The test link below uses `2\#` instead of `m!` which isn't *quite* enough for all possible inputs, but it passes all test cases in a few seconds (and one would have try fairly hard to find a test case that doesn't pass).

Try it online!

### Explanation

This doesn't have any loop or terminal detection. Instead we simply iterate the system often enough that we *know* we've hit a loop, recording the history, and then we check whether we've reached the terminal node at any point.

If we don't visit the terminal node, we only modify the states of `N-1` nodes (if `N` is the total number of nodes). Each of the nodes has two different states, and the train can be on any one of those nodes (thanks to ais523 for pointing this out), so there are `2<sup>(N-1)</sup>*(N-1)` different states we can visit before entering a loop or reaching the terminal node. Since we start from one of these states we know that after `2<sup>(N-1)</sup>*(N-1)` transitions, we've either entered a loop or reached the terminal node.

That's a fairly lengthy expression. However, `N!` is almost never less than `2<sup>(N-1)</sup>*(N-1)`. In fact, the only `N` for which that's the case is `3`, where the number of possible states is `8` and `N!` gives only `6`. That said, it's not necessarily the case that it's possible to reach all theoretical states in any of the possible inputs. It's fairly easy to check this exhaustively: the neighbours of the last node are always irrelevant, so we can simply consider all inputs of the form `[[a b] [c d] [0 0]]` where at least one of `abcd` contains `2` (otherwise, the terminal state is guaranteed to be unreachable). There are only 65 of these states, and I ran them through a slightly modified program, which finds the first transition after which the terminal state is reached (or `-1` if it's unreachable). As it turns out, it's impossible to construct an input which requires more than 6 transitions to reach the terminal state, just what we need. Hence, I'm using `N!` as the upper bound of iterations.

```
0      e# Push a zero. This is the initial node index of the train.
l~     e# Read and evaluate the input.
_,m!   e# Compute the factorial of N.
{      e# Run this block N! times.
  _    e#   Copy the list of LR pairs.
  2$=  e#   Copy the current node index and extract the corresponding pair.
  (    e#   Pull off the first neighbour - this is where the train moves next.
  @@   e#   Pull list of pairs and the list with the other neighbour on top.
  2$+  e#   Copy the first neighbour and append it. This effectively, reverses
       e#   the pair so that next time the other destination from the current
       e#   node is picked.
  3$   e#   Copy the current node again.
  \    e#   Swap it with the reversed pair.
  t    e#   Write the reversed pair back into the full list of pairs.
       e#   In summary, one iteration extracts the first neighbour of the
       e#   current node and leaves it on the stack, and swaps the neighbours
       e#   of that node for future visits.
}*     e# At the end, we've got all the reachable nodes on the stack, and
       e# the list of all pairs still on top.
,(     e# Compute N-1 from the list of pairs.
])     e# Wrap everything in a list and remove N-1 from it.
&      e# Compute the set intersection all reachable nodes with N-1.

```

# Answer
> 2 votes
# Perl, 52 + 2 = 54 bytes

```
$F[$1/($@++<@F<<@F)]=~s/(.+),(.+)/$2,$1/ while$1<$#F

```

Run with `-ap` (2 byte penalty). Input is a single line in the format `1,2 0,3 2,2 2,0`.

Prints a copy of the input (which is truthy in Perl, as it's a string more than one byte long) to standard output on success, or crashes via dividing by zero (producing nothing on standard output; the null string is falsey) on failure.

The algorithm is very simple; we simply simulate the movement of the train, remembering its current location in `$1` (whose initial value is zero when seen as an integer, and which automatically updates to hold the first capture group every time a regex is run), and the current states of the track by overriding `@F` (which holds the input array, and is input via the `-a` option on the command line). In order to detect that we've got stuck in a loop, we use `$@` to count the number of steps taken; if this exceeds the number of switches times 2 to the power of the number of switches (a formula that can be conveniently written in Perl as `@F<<@F` and which is only slightly higher than the actual upper bound), we're necessarily stuck in a loop, because seeing the same (track, train) state twice will cause an infinite loop in this problem, and we've already been through more states than there are *distinct* states (so by the pigeonhole principle, we must have seen at least one twice).

# Answer
> 1 votes
# Haskell, ~~114~~ ~~95~~ ~~88~~ 84 bytes

```
(o%h)g|elem(o,g)h=1<0|(a,(l,r):b)<-splitAt o g=null b||(l%((o,g):h)$a++(r,l):b)
0%[]

```

Keeps a history of visited (location, network) pairs to be able to decide a failure. Junctions tuples are swapped when visited.

Usage:

```
0%[]<$>[[(0,0)] ,[(0,1),(0,0)] ,[(0,0),(1,0)] ,[(1,2),(0,3),(2,0),(1,2)] ,[(1,2),(0,3),(2,2),(1,2)] ,[(1,2),(3,0),(2,2),(1,2)] ,[(1,2),(2,0),(0,2),(1,2)] ,[(0,2),(4,3),(0,4),(1,2),(4,1)] ,[(4,0),(3,0),(4,0),  (2,0),(0,4)] ,[(1,4),(3,2),(1,4),(5,3),(1,0),(5,2)] ,[(3,1),(3,2),(1,5),(5,4),(1,5),(3,2)] ,[(1,2),(5,0),(3,2),(2,4),(2,3),(1,6),(1,2)] ,[(4,9),(7,3),(5,2),(6,4),(6,5),(5,4),(3,2),(6,8),(8,9),(9,1)] ,[(2,7),(1,  5),(0,8),(9,7),(5,2),(0,4),(7,6),(8,3),(7,0),(4,2)] ,[(4,9),(7,3),(3,2),(8,3),(1,2),(1,1),(7,7),(1,1),(7,3),(1,9)] ,[(0,13),(3,6),(9,11),(6,12),(14,11),(11,13),(3,8),(8,9),(12,1),(5,7),(2,12),(9,0),(2,1),(5,2),  (6,4)] ,[(6,0),(1,2),(14,1),(13,14),(8,7),(6,4),(6,10),(9,10),(10,5),(10,9),(8,12),(14,9),(4,6),(11,10),(2,6)] ,[(1,3),(9,17),(5,1),(13,6),(2,11),(17,16),(6,12),(0,8),(13,8),(10,2),(0,3),(12,0),(3,5),(4,19),(0,  15),(9,2),(9,14),(13,3),(16,11),(16,19)]]
[True,True,False,True,False,True,False,True,True,True,True,False,False,True,False,False,False,True]

```

Ungolfed:

```
rails location history network
  | elem state history = False                         --We are stuck in a loop
  | otherwise = null b || (rails l newHistory swapped) --b is empty when location is last element in list
  where
  (a, (left, right):b) = splitAt location network
  swapped            = a ++ (right, left):b
  state              = (location, network)
  newHistory         = state:history

```

Thanks @Zgarb for saving 4 bytes

# Answer
> 0 votes
# Python ~~135~~ 133 bytes

-1 byte thanks to Angs (`l>len(c)-2` rather than `l==len(c)-1`)

```
def f(c,p=0,l=0,h=[]):j=len(c);p=p or[0]*j;s=p[:],l;r=2*(l>j-2)or(s in h);n=c[l][p[l]];p[l]=1-p[l];return r-1if r else f(c,p,n,h+[s])

```

**repl.it**

Returns `1` (truthy) if the goal is reached; or `0` (falsey) if a state is reached that has been reached before. Otherwise recurses updating the state.

`c` is the network. `p` is the current state of each switch (initialised to all left as `[0]*len(c)` on the first run). `l` is the current location. `h` is the state history, to which `s`, a tuple of a copy of `p` and `l`, is added.

---
Tags: code-golf, graph-theory, decision-problem
---