title: Programming Dichotomies (Literally)

text:
# Question
Title: Programming Dichotomies (Literally)
Consider a question written in plain English whose answer involves two reasonably accurate (but potentially clever) words or phrases that can be separated by the word 'and':

> **Q:** What are the two sides of a coin? **A:** heads and tails
>
> **Q:** What are the best ways to travel? **A:** airplane and jetpack
>
> **Q:** Why is a raven like a writing desk? **A:** because there is a 'b' in both and an 'n' in neither

# Goal

Write a program which, when run normally, outputs such a question.

When every other character is removed from the program starting with the *second* character and the result is re-run, the output should be whatever is to the *left* of the 'and' in the answer.

When every other character is removed from the program starting with the *first* character and the result is re-run, the output should be whatever is to the *right* of the 'and' in the answer.

(The 'and' itself is not output.)

# Example

If the program is

```
A1B2C3D4E5F6G7H8I9

```

and its output is

```
What are the two sides of a coin?

```

Then the output of `ABCDEFGHI`should be `heads`, and the output of `123456789` should be `tails`.

# Rules about questions and answers

* You may use my example questions but I encourage you to make up your own.
* The question and the two answer parts:
    + must all be distinct
    + should be common grammatical meaningful English
    + may only contain printable ASCII (hex 20 to 7E)
* Ideally the question will be capitalized and punctuated (but the answers do not need to be).
* The question must be at least 30 character long and have entropy above or equal to 3.5. (Type in string, hit *calculate*, look for last *H(X)*.)
* The two answer parts (not including the `[space]and[space]` between them) must each have at least 5 characters with entropy above or equal to 2.
* The word 'and' may appear in either answer part.

# Rules about code

* None of the 3 code snippets may:
    + contain comments or anything else traditionally ignored by the compiler/interpreter (don't worry about putting an extra semicolon or two in, but if you think it's a comment it probably is)
    + exit the program in mid-execution
* The code may contain any characters, including Unicode and non-printable ASCII.
* It may have an odd or even number of characters.
* Output goes to stdout or a file or whatever seems reasonable. There is no input.

# Scoring

Since I wan't to encourage golfed answers but I want to encourage clever answers even more, the scoring will be something in between code-golf and popularity contest:

Score = `(upvotes - downvotes) - floor((bytes in code that outputs question) / 3)`

The highest score wins.

(Use http://mothereff.in/byte-counter as a byte counter.)

# Answer
> 55 votes
# Javascript (148 bytes)

Creates some nonsense literals, with the side effect of creating an alert\* for the question. (the splits doing similar, but creating alerts\* for each of the answers).

```
"';"+alert( 'What is the ideal breakfast???')+/ " ;apl=e"rbta(k"esnc"r.armebplleadc ee g g s(" ) + " \/)k;e"/+ ",t'hceo 'c)a;kye= ailse rat (lpi)e "

```

Splits:

```
";+lr('hti h da rafs??)/";p="baken".replace   (    /ke/ ,'co');y=alert(p)

```

and

```
'"aet Wa steielbekat?'+  alert("scrambled eggs")+"\);"+"the cake is a lie"

```

Question: `What is the ideal breakfast???`

Answers: `bacon` and `scrambled eggs`

# Answer
> 29 votes
## Brainfuck (437 characters)

I have to confess that this is my first brainfuck program that actually does something meaningful. The program is highly optimized for low memory systems since it uses only 4 memory locations.

Question: `What are the two main groups of trees?`

Answers: `conifers` and `broadleafs`

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

```

**Main loop**

The program consists of main loop (which isn't really a loop since all \[ \] -blocks are executed only once) and two sections.

```
-+[[        // let answers enter
            * SNIP interleaved answer sections *
]]
++-+[[      // let odd answer and question enter
    +-+-[[  // let question enter
            * SNIP question section *
    ]]
]]

```

If you want to test sections independently, you must take the main loop into account. Location 0 contains -1 in even answer, 1 in odd answer and 2 in question section.

**Answer section**

Even answer (odd instructions removed):

```
// location 0 contains minus 1 from main
// set location 1 = 10 * 10 minus 1 = 99 (c)
+++++++++++[>++++++++++<-]>-. // c
++++++++++++.-.     // on
-----.---.          // if
-.+++++++++++++.+.  // ers
<                   // goto 0 (which contains 0)
+-+-+-+-+-          // padding to match length of odd answer

```

Odd answer (even instructions removed):

```
// location 0 contains 1 from main
// set location 1 = 16 * 6 plus 2 = 98 (b)  location used for characters below 'l'
// set location 2 = 16 * 7 plus 2 = 114 (r) location used for 'l' and above
+++++++++++++++[>++++++>+++++++<<-]>++.>++. // br
---.<               // o
-.+++.              // ad
>---.<              // l
+.----.+++++.       // eaf
>+++++++.           // s
>                   // goto 3 (which contains 0)

```

**Question section**

I decided to store space to separate location because its value differs drastically from other characters. This allows space to be printed simply with `<.>`.

```
// location 0 contains 2 from main
// set location 1 = 17 * 2 minus 2 = 32 (space)
// set location 2 = 17 * 5 plus 2 = 87 (W)   location used for characters below 'r'
// set location 3 = 17 * 7 minus 3 = 116 (t) location used for 'r' and above
+++++++++++++++[>++>+++++>+++++++<<<-]>-->>---<++. // W
+++++++++++++++++.  // h
-------.>.<         // at
<.>                 // (space)
.>--.<++++.         // are
<.>                 // (space)
>++.<+++.---.       // the
<.>                 // (space)
>.+++.<++++++++++.  // two
<.>                 // (space)
--.------------.    // ma
++++++++.+++++.     // in
<.>                 // (space)
-------.>-----.     // gr
<++++++++.>+++.     // ou
<+.>--.<            // ps
<.>                 // (space)
-.---------.        // of
<.>                 // (space)
>+.--.<-..>+.       // trees
<<[<++>-]<-.<       // ? (value_of_space * 2 minus 1)

```

**Final update**

In my final update I optimized multiplications so that minimum instructions are used. Also including 'l' to second character group in odd answer section proved to be huge improvement. Single character savings in odd answer basicly meant two characters from whole program, since it also reduces padding from the even answer. I also removed couple of unnecessary instructions from here and there and I don't think I can optimize the code any further.

# Answer
> 23 votes
# Batch - 84

Quite proud of this one

Full program: What are two sides of a coin? (console)

```
echo What are two sides of a coin?  2>>xx  2>>cc&&eecchhoo  hteaaidlss  2>>xx  2>>cc

```

Evens only: heads ('c' file)

```
eh htaetosdso  on 2>x >c&echo heads 2>x >c

```

Odds only: tails ('x' file)

```
coWa r w ie faci? >x 2>c&echo tails >x 2>c

```

Works by redirecting the error output to a file in both cases.

# Answer
> 20 votes
# Python - ~~104~~ 96 (golfed: 76)

My solution is rather simple (and somehow readable):

```
"";print 'What is the color of a zebra?' ;""
paraianat= "' b l a c k '"
aparaianat="'w h i t e'"

```

Output:

```
What is the color of a zebra?
black
white

```

Honestly, I found the idea for the first line in bitpwner's answer.

---

**Even more readable alternative: - ~~113~~ ~~105~~ 97**

```
"";print 'What is the color of a zebra?' ;""
"p r i n t ' b l a c k '" ;"p r i n t ' w h i t e '"

```

---

**Even shorter alternative: - ~~86~~ 76**

```
"";print'What is the color of a zebra?';""
"""";;pprriinntt''bwlhaictke''"""

```

# Answer
> 15 votes
# Perl 186 139 135

```
"";print'What are the best things in life?';""&&pprriinntt("'hceraurs ht hyeo ulra meennetmaiteiso'n s   o f   t h e i r   w o m e n ")

```

What are the best things in life?

```
"pitWa r h ettig nlf?;"&print('crush your enemies'                 )

```

crush your enemies

```
";rn'htaetebs hnsi ie'"&print"hear the lamentations of their women"

```

hear the lamentations of their women

Using less lengthy answers:

# Perl 79 72

```
"";print'What are my preferred weapons?';""&&pprriinntt("'smwaocredss'")

```

`What are my preferred weapons?` (30Byte, H(X)=3.76) `swords` (H(X)=2,25) and `maces` (H(X)=2,32)

# Answer
> 15 votes
## Rebmu: 79 chars OR (37 + length(p1) + 2 * max(length(p2), length(p3)))

First I'll give a 79 character solution that asks **Which languages must you learn?** (entropy 4.0, 30 letters not including `?`) and offers you the suggestions of **Rebol and \[Red\]**:

```
DD  11  DD :do dd {dd  {p{Which languages must you learn?}qt}} pp{{[RReebdo]l}}

```

A unique tactic available here that isn't in other languages comes from taking advantage of the fact that curly braces are an asymmetric string delimiter, that can nest legally:

```
my-string: {"It's cool," said {Dr. Rebmu}, "for MANY reasons--like less escaping."}

```

That let me produce a generalized solution, that can work effortlessly on any program that doesn't use escape sequences. The 79 character version was simple enough to shortcut, but to properly contain arbitrary program source for programs p2 and p3 you'd need the full template. Had we used that, it would have been 87 characters:

```
DD  11  DD :do dd {dd  {p{Which languages must you learn?}qt}} ddoo{{pp{{[RReebdo]l}}}}

```

The pattern for using this general form is that if you have three source texts of sequential characters of variable lengths (let's use an example like `AAA`, `BBBBB`, `CCCCCCC`) you can encode them as something along the lines of:

```
DD  11  DD :do dd {dd  {AAAqt}} ddoo{{BCBCBCBCBC C C}}

```

*(Note: Although this pattern won't work without tweaking on programs that use escape characters, this is not a fatal flaw. Getting an unmatched left brace in a string delimited by braces requires something like `{Foo ^{ Bar}`...but you could easily rewrite that using the alternative string notation `"Foo { Bar"`, and combined cases can be managed with gluing together a mixture of unescaped strings.)*

So...how about an example? Once the general form was available, this 573 character program was assembled in only a couple of minutes from 3 prior code golf solutions:

> DD 11 DD :do dd {dd {rJ N 0% rN Wa1m2j S{ \x/ }D00 Hc&\[u\[Ze?Wa Qs~rpKw\[isEL00c\[skQd2k\]\[eEV?kQ\[tlQ\]\]pcSeg--b00\[eZ 1 5\]3\]prRJ\[si~dSPscSqFHs\]eZ 1\[s+dCa+wM2cNO\]\]\]Va|\[mpAp2j\]prSI~w{*}Ls2w Wl h01tiVsb01n -1 chRVs{*}hLceVn01qt}} ddoo{{BrdSz \[fcebC\[sn\[{N sbeo\[tIt0l1eV}0e5gXN1 01L{5s0}C{1}0{0 Do5f0 0bMe1e0r0}0\]\]\]tMw9C9 Numz Jl\[paN+\[KperlCJBn\[\[ba sWS{B noJn Nt0h0e\] jw\]aJlnl\]}aCd{K,j } b P { . } l f E Z - - n \[ N m { G o t o t h e s t o r e a n d b u y s o m e m o r e } \] { T a k e o n e d o w n a n d p a s s i t a r o u n d } c B w P l f \] \] }}

If anyone wants to try writing that program in their language of choice, and thinks they can beat 573, let me know. I will bounty you a heavy amount of reputation if you do--assuming your language of choice is not Rebmu, because I know those programs aren't minimal. :-)

That "wasteful" spacing you get at the end is what happens when p2 and p3 are of imbalanced lengths. But all 3 programs are different sizes in this case so there isn't a particular good pairing to pick for p2/p3. (I picked these because there was no external data as input, such as a maze or whatever, not that they were of similar lengths. While I could have written new programs that were more optimal, I've spent enough time and the point was you *don't* have to write new programs...)

### How it works

*(Note: I started with a more "creative" approach that was not as streamlined but more interesting-looking. I moved it to an entry on my blog as describing this approach is already long.)*

A key here is the "eval code as a string" trickery like some other entries, it just has the trump card of the asymmetric string delimiter. I'll start by explaining the workings of the 80 character case.

Here's the "whole" program, adjusting the whitespace for this case's readability:

```
DD 11                    ; assign 11 to dd (about to overwrite again)
DD :do                   ; make dd a synonym for DO (a.k.a. "eval")

; eval a string as source code that ends with QUIT (QT)
dd {dd  {p{Which languages must you learn?}qt}}

; we'll never get here, but whatever's here must be legally parseable
pp{{[RReebdo]l}}

```

Here we wind up setting DD to a synonym for DO (a.k.a. "eval"). But the trick is that when the halved programs run, they wind up running code whose only effect is to define D to the harmless literal 1.

Here's what the odd-chars code makes, whitespace again adjusted:

```
D 1                      ; assign 1 to d
D d                      ; assign d to itself, so it's still 1
d                        ; evaluates to integer, no side effect
{d pWihlnugsms o er?q}   ; string literal, no side effect
p {Rebol}                ; print "Rebol"

```

And here's the even-chars code:

```
D 1                      ; assign 1 to d
D:od                     ; URL-literal (foo:...), no side effect
d                        ; evaluates to integer, no side effect
{{hc agae utyulan}t}     ; string literal (well-formed!), no side effect
p {[Red]}                ; print "[Red]"

```

It's actually the case that for the non-halved program, the `dd {dd {(arbitrary code)qt}}` will execute whatever code you want. However, there are two calls to evaluate instead of just one. That's because while the nested braces work great in the interleaved code, they mess up the eval behavior of DO. Because:

```
do {{print "Hello"}}

```

Will load the string as a program, but that program winds up being just the string constant `{print "Hello"}`. Thus the trick I use here is to take my DD (holding the same function value as DO) and run it twice. The halvers chew at the different parts of the string but they don't chew both if the even/oddness is correct for the content, and because what's left outside the string after halving is just the integral constant `d` they're harmless.

With this pattern there's no challenge in writing the program behavior when it's not cut in half--you can put in anything as long as the character length of the code is even (odd if you're counting the QT, which is QUIT). If you need to get the even number from an odd one, throw in a space *(so there's actually a +1 in my formula above on p1 for odd program lengths of p1)*. The trick would seem to write that interleaved code afterwards, which must pass the parser if it *isn't* halved. (It won't be run because of the QT, but it has to be LOADable before it will be executed.)

This case is trivial; `pp` loads fine as a symbol even though it's undefined, and is split into `p` for print in each half program. But we can do another trick just by using a string literal again. The halved programs still have DO defined normally, so we could also have just said:

```
ddoo{{pp{{[RReebdo]l}}}}

```

By having the only part picked up by the parser in the whole case be the symbolic word `ddoo` and a string literal, we can then interleave any two programs we wish inside that string literal and not anger the parser. The halved versions will just say:

```
do{p{Rebol}}

```

..and...

```
do{p{[Red]}}

```

As I say, this part looks familiar to other solutions that treat programs as strings and eval them. But in the competition's case, when the programs you're packing contain nested strings, that throws in wrenches for them. Here the only things that will get you in trouble are use of escaping via carets (`^`)...which can be easily worked around.

---

*(Small 'cheating' note: I added QT for "QUIT" in response to this problem. Actually, I had purposefully removed the abbreviation for quit before...because somehow I thought it was only good for console use and just taking up the two-letter space if it wasn't in a REPL. I'm adding it because I see I was wrong, not adding it for this case in particular. Nevertheless, prior to that change it would have been 2 characters longer. Also, when I first posted the solution there was a bug in Rebmu that kept it from actually working even though it should have...now it works.)*

# Answer
> 9 votes
# Python - ~~139~~ 103

```
"";print'What are the ingredients for success?';""; ";" ;id=='"RUaniincboorwnss'";;pprriinntt  id++"'"'

```

`What are the ingredients for success?` -\> `Unicorns` and `Rainbows`

**Test:**

```
c="\"\";print\'What are the ingredients for success?\';\"\"; \";\" ;id==\'\"RUaniincboorwnss\'\";;pprriinntt  id++\"\'\"\'"
exec c        # What are the ingredients for success?
exec c[::2]   # Unicorns
exec c[1::2]  # Rainbows
print
print c[::2]  # ";rn'htaeteigeinsfrsces'";"";d="Unicorns";print d+''
print c[1::2] # "pitWa r h nrdet o ucs?;" ; i='Rainbows';print i+""

```

**Old version:**

```
# What are the ingredients for success?
"";print(('What are the ingredients for success?'));""; ";" ;"pHrEiRnEt (C'OUMnEiSc oZrAnLsG'O)"; ";" ; "p,r iTnOtN(Y' RTaHiEn bPoOwNsY'.)"
# Unicorns
";rn('htaeteigeinsfrsces')";"";print('Unicorns');"";", TONY THE PONY."
# Rainbows
"pit(Wa r h nrdet o ucs?);" ; "HERE COMES ZALGO" ;  print('Rainbows')

```

# Answer
> 6 votes
# Haskell, 117

Having to work with Haskell's functional paradigm means that everything has to be assigned to a variable or commented out with line `--` or block `{- -}` comments; having nonsense functions run without assignment is out. So, to keep myself sane, I kept the question and answers as short as the rules allow.

Question: What can I not have enough of?

```
main=putStrLn{---}"What can I not have enough of?"{- }
=u"Scrank=e"sS"h
omeasi"n
=mpauitnS=tpru taSntprt tmLi

-----}

```

"Shoes" and "cakes":

```
mi=uSrn--"htcnInthv nuho?{
uSrn="Shoes"
main=putStr mi
--}

```

```
anpttL{-}Wa a  o aeeog f"-}="cakes"
main=putStr anpttL
---

```

N.B. The appearance of `crank` under "What can I not have enough of?" should not be viewed as meaningful.

# Answer
> 4 votes
## Lisp (76 characters)

31-character question, 6 characters in each answer ⟹ length - payload = 33

```
'(: (pprriinncc''fmuacghesnitaa))':(princ "What is your favorite pink hue?")

```

I wanted to use “What is your favorite color?”, but even stretched to British spelling, it only just reached the 30-character minimum for the question length, and I needed an odd-length question to balance the double quotes.

They say Common Lisp is verbose, but you wouldn't think so going by this one-liner. It's not even very obfuscated, you only need to insert a bit of whitespace to see what's getting quoted and what's getting executed.

Many Lisp implementations will shout out the colors, because they warp symbols to uppercase. If that bothers you, change `''fmuacghesnitaa` to `""fmuacghesnitaa""`.

# Answer
> 3 votes
## STATA 295

Question: What are the best desserts to bake right now? Answer: brownies and cookies.

Explanation: Commands in STATA are delimited by new lines.
While "//" is a comment in STATA, "///" tells the compiler to continue to the next line and include its contents in the current command.
Commands in STATA can often be abbreviated to the point where they are considered unique enough to be differentiable (so "generate" becomes "g", "global" becomes "gl" or "glo", "capture" becomes "cap", "display" becomes "di", etc.). The display command displays text to the screen. The capture command captures all errors (including syntax errors), which is why this program compiles properly.
I guess if you want to get picky, any additional "/" after the first 3 consecutive ones in a line are ignored by the compiler. Also, in the "brownies" program, technically +" " is a comment. But I claim that it still counts because the capture command would still have made it irrelevant even if it wasn't a comment.
Thanks for reading my really long explanation. Now for the code:
"What are the best desserts to bake right now?"

```
g   a = "g   q   /b/a/"
g l= "b = ""b r o w n i e s "
g   c = "g   /b/a/"
g lpo= "d = ""c o o k i e s "
g   e = "c a p  "  /////
 +  "d i ""$ b "
g   f = "c a p  "  /////
 +  "d i ""$ d "
g   g = "c a p  "  /////
 + "c a p   / / /  "+ "/ / /"
di "What are the best desserts to bake right now?"

```

"brownies"

```
g a="    ba"
gl b="brownies"
    g ///
 p="  "
g e="   " //
 di "$b"
    cap ///
+" "
g g="   " //
  cap ///   +"  "
i"htaetebs esrst aergtnw"

```

"cookies"

```
    g q ///
 ="  "
g c="  ba"
glo d="cookies"
    cap ///
+" "
g f="   " //
 di "$d"
    cap  ///
+ "       " ///
d Wa r h etdset obk ih o?

```

# Answer
> 2 votes
## Ksh (82 characters)

35-character question, 5 characters in each answer ⟹ length - payload = 37

```
ec=\'o'(;)eehc(h)oe cChroi m$e1;; '\'
echo  What\'s the  country\'s worst problem?

```

I abuse the function definition syntax beyond POSIX. Dash and bash can't take it but ksh (public domain or ATT) can.

Nothing remarkable going on, just a bit of echo. Waste not, want not.

# Answer
> 2 votes
# PowerShell 88

```
"" > $x;{What is my favorite equipment?};"" >> ${x}

${XsXwXoXrXdX};;;${XsXhXiXeXlXdX}

```

**What is my favorite equipment?** (30 chars, H(X) = 4.0314)

```
"  x{hti yfvrt qimn?;"> {}
{sword};$XXXXXXX

```

**sword** (5 chars, H(X) = 2.32193)

```
">$;Wa sm aoieeupet}" >$x
$XXXXXX;;{shield}

```

**shield** (5 chars, H(X) = 2.58496)

On the full program it redirects empty strings to a nonexistent variable `${x}` (the quotes for those empty strings are used to form a nonsense string that gets redirected either to an empty block `{}` or nonexistent variable `$x` on the even/odd versions), then prints the question and declares 2 unused variables (which are printed and placed next to another unused variable `$XXXXXX` or `$XXXXXXX` on the different cases).

# Answer
> 1 votes
# GolfScript, 51 bytes

```
"Which are the sides of a coin? ".;""thaeialdss""

```

### Output

```
Which are the sides of a coin?

```

### How it works

`.;` duplicates the string and deletes the copy. `""` pushes an empty string. `thaeialdss` is undefined, so it does nothing.

## Odd chars

```
"hc r h ie faci?";"heads"

```

### Output

```
heads

```

### How it works

`;` deletes the first string from the stack.

## Even chars

```
Wihaetesdso  on ."tails"

```

### Output

```
tails

```

### How it works

`Wihaetesdso` and `on` are noops. `.` duplicates the empty string on the stack.

---
Tags: code-challenge
---


# Question
Title: Implement bit-wise matrix multiplication
The MMIX architecture is a fairly simple big-endian RISC design. It has a couple of interesting features, one of them is the `MXOR` instruction, which is what you should implement.

The `MXOR` instruction interprets its arguments (two 64-bit registers) as two 8×8 matrices of bits and performs a matrix multiplication where exclusive-or is used for addition and logical and is used for multiplication.

An argument in binary representation where the leftmost digit is most significant

> a0 a1 a2 … a63

is interpreted as a matrix like this:

> a0 a1 … a7
> a8 a9 … a15
> a56 a57 … a63

Your task is to write a function, subroutine or similar in a language of choice which can be evoked from a single-letter name (i.e. `f(x,y)`) that implements this function. The two arguments of the function shall be of equal implementation-defined unsigned 64 bit integer type, the function shall return a value of the same type.

he winner of this competition is the shortest submission (measured in bytes or characters if the language you use uses a meaningful character encoding). You are encouraged to post a readable commented version of your code in addition to the golfed solution so other's can understand how it works.

# Answer
> 7 votes
### APL, 28 characters

```
f←{2⊥,↑≠.×/{8 8⍴(64⍴2)⊤⍵}¨⍵}

```

Usage:

```
> f 12345678 87654321
3977539

```

You can read it almost literally if you go right-to-left. `(64⍴2)⊤` transforms each argument into 64 bit representation and `8 8⍴` makes an 8x8 matrix out of the results. `≠.×/` then applies the inner product to both arguments, where multiplication `×` and xor  is used. The matrix is then transformed back to vector form `,↑`, before `2⊥` undoes the basis transformation.

# Answer
> 7 votes
## x86 machine code, 45 44 40 bytes

```
  40072c:       b1 08                   mov    $0x8,%cl
  40072e:       48 c1 c7 08             rol    $0x8,%rdi
  400732:       b5 08                   mov    $0x8,%ch
  400734:       48 0f 6e c6             movq   %rsi,%mm0
  400738:       0f d7 d0                pmovmskb %mm0,%edx
  40073b:       40 20 fa                and    %dil,%dl
  40073e:       7a 01                   jp     400741 <amul+0x15>
  400740:       f9                      stc
  400741:       48 11 c0                adc    %rax,%rax
  400744:       48 d1 c6                rol    %rsi
  400747:       fe cd                   dec    %ch
  400749:       75 e9                   jne    400734 <amul+0x8>
  40074b:       48 c1 ce 08             ror    $0x8,%rsi
  40074f:       fe c9                   dec    %cl
  400751:       75 db                   jne    40072e <amul+0x2>
  400753:       c3                      retq

```

The code uses two tricky moves. The first is the `pmovmskb` intsruction which takes every 8th bit of an mmx register and packs them together into an integer register. Very useful for extracting columns. The second is the parity flag which is used to accumulate the dot product (the `and`/`jp`/`stc` combo).

Here's the expanded code with comments:

```
    # rowloop
    mov $8, %cl
1:
    rol $8, %rdi    # get next row of A into low 8 bits

    # columnloop
    mov $8, %ch
2:
    # extract first column
    movq    %rsi, %mm0
    pmovmskb    %mm0, %edx

    # dot with current row
    testb   %dil, %dl

    # shift result and add parity bit
    jp  3f
    stc
3:
    adc %rax, %rax

    # shift over columns of B
    rol %rsi

    dec %ch
    jne 2b

    # restore B
    ror $8, %rsi

    dec %cl
    jne 1b
    ret

```

# Answer
> 5 votes
## GolfScript (49 48 45 chars)

This takes a completely different approach to my earlier GolfScript entry, so I think it wants a separate answer.

```
{0{1$M&16.?M/:K*3$K&M*&^@2/@M)/@}255:M*++}:f;

```

It's pure bit-bashing.

If we consider `a` as a series of matrix elements we get

```
a_00 a_01 a_02 a_03 a_04 a_05 a_06 a_07 a_10 a_11 ...

```

Similarly `b`. Now, `c_ij = a_i0 & b_0j ^ a_i1 & b1j ^ ... ^ a_i7 & b7j`. So by grouping over the common index we get

```
c =   (a_00 a_00 ... a_00 a_00 a_10 a_10 ...) & (b_00 b_01 b_02 ... b_07 b_00 b_01 ...)
    ^ (a_01 a_01 ... a_01 a_01 a_11 a_11 ...) & (b_10 b_11 b_12 ... b_17 b_10 b_11 ...)
    ^ ...
  =   (((a >> 7) & 0x0101010101010101) * 0xff) & (((b >> 56) & 0xff) * 0x0101010101010101)
    ^ (((a >> 6) & 0x0101010101010101) * 0xff) & (((b >> 48) & 0xff) * 0x0101010101010101)
    ^ ...

```

That's enough background to be able to explain the code:

```
{                 # Function declaration boilerplate; stack is a b
  0               # Accumulator for the result
  {               # Loop: stack holds a>>k b>>8k partial-sum
    1$M&          #   M holds 255 (see below); get (b>>8k) & 0xff
    16.?M/:K      #   Derive 0x0101010101010101 and store in K
    *             #   Multiply: stack is a>>k b>>8k partial-sum rhs-of-and
    3$K&M*        #   Similarly for a: add lhs-of-and to the stack
    &^            #   Do the pointwise multiplication and addition
    @2/@M)/@      #   Restore loop invariant with a>>=1 and b>>=8
  }255:M*         # Store 255 in M and execute the loop that many times
                  # 8 times suffices to get the correct result; after that b>>8k == 0 and the
                  # partial sum doesn't change. After 64 iterations, a>>k == 0
  ++              # So we can ditch their remnants by adding to the partial sum
}:f;              # Function declaration boilerplate

```

Thanks to Dennis for the observation that `16.?` is equal to `2 64?` (or `2.6??`); since it's one char shorter, I've stolen it. Thanks to Howard for suggesting a 2-char improvement which became 48-\>45.

# Answer
> 4 votes
# CJam, 35 bytes

```
{2{GG#+2b1>8/\}*zm*{z{:&}%:^}%2b}:F

```

Try it online by pasting the following *Code*:

```
{2{GG#+2b1>8/\}*zm*{z{:&}%:^}%2b}:F;  " Define function and clear stack.              ";
12345678 87654321 F                   " Call function.                                ";

```

### How it works

```
2{      " Do the following twice:                                                     ";
  GG#+  " Add 16 ** 16 = 2 ** 64 to the topmost integer on the stack.                 ";
  2b    " Convert it into an array of its digits in base two.                         ";
  1>    " Discard the first digit.                                                    ";
  8/    " Split into arrays of 8 digits.                                              ";
  \     " Swap the resulting array with the second topmost stack element.             ";
}*      " This converts two 64-bit integers into 8×8 matrices of its base 2 digits.   ";
zm*     " Transpose the second matrix and compute the cartesian product of both.      ";
{       " For each pair (one row of the first and one column of the second matrix):   ";
  z     " Transpose the array.                                                        ";
  {:&}% " For each array of the array, compute the logical AND of its elements.       ";
  :^    " Compute the logical XOR of the results.                                     ";
}%      " Note that ^ and & are addition and multiplication in GF(2).                 ";
2b      " Convert the array of base 2 digits into and integer.                        ";

```

# Answer
> 3 votes
## GolfScript (65 chars)

```
{[{2.6??+2base(;8/\}2*zip 8*\{{.}7*}%]zip{zip{~&}%{^}*}%2base}:f;

```

This turns out to be similar to BeetDemGuise's Python solution, although it uses more zips and less eval.

Dissection:

```
{
  # Stack: a b (as integers)
  [                  # Start gathering into array for subsequent zip
    {                # Repeat twice:
      2.6??+2base(;  # Convert to 64 bits
      8/             # Break into an 8x8 matrix
      \              # Flip top of stack
    }2*
    # Stack: a b (as matrices)
    # Each cell of the matrix product needs a row of a and a column of b
    zip 8*           # Get 8 copies of columns of b, ordered
                     #   [col_0 col_1 ... col_7 col_0 col_1 ...]
    \{{.}7*}%        # Get 8 copies of rows of a, ordered
                     #   [row_0 row_0 row_0 ... row_7 row_7]
  ]                  # Gather into array
  zip                # Zip: each array entry is now an array [col_j row_i]
  {                  # Map each array item
    zip              # Pair up each bit from col_j with corresponding bit of row_i
    {~&}%            # Multiply the bits in each pair
    {^}*             # Add the products
  }%

  2base              # Convert back from an array of 64 bits to an integer
}:f;                 # Assign to f and don't leave a copy lying about on the stack

```

# Answer
> 3 votes
## J, 50 chars

Here is a version that does not use J's built-in general matrix product conjunction `.`.

```
   f=:#.@,@:(|."1)@(~:/@:*"2 1"1 2|.)&(8 8$]#:~64#2:)

```

### Testing (with 4×4 matrices)

```
   g=:#.@,@:(|."1)@(~:/@:*"2 1"1 2|.)&(4 4$]#:~16#2:)
   44584 g 28371
46550

```

And the matrices visualized, for manual verification.

```
   (4 4$]#:~16#2:)&.> 44584;28371;46550
┌───────┬───────┬───────┐
│1 0 1 0│0 1 1 0│1 0 1 1│
│1 1 1 0│1 1 1 0│0 1 0 1│
│0 0 1 0│1 1 0 1│1 1 0 1│
│1 0 0 0│0 0 1 1│0 1 1 0│
└───────┴───────┴───────┘

```

### Exploded view

```
                                  &(             ) to each of the arguments,
                                            64#2:    generate 64 2's (radix for below)
                                        ]#:~         decode from radix
                                    8 8$             reshape as 8×8 array
                (              |.)                 reverse the right argument
                       "2 1"1 2                    for each pair of rows,
                      *                              multiply
                    @:                               composed with
                 ~:/                                 xor folded
         (|."1)@                                   reverse each row
      ,@:                                          ravel (flatten array)
   #.@                                             back to binary again
f=:                                                assign function to name 'f'

```

# Answer
> 2 votes
# Python 2 - 183

```
def m(a,b):a,b=map(lambda x:'{:064b}'.format(x),[a,b]);r=range(8);return int(''.join(`eval('^'.join(o+'&'+t for o,t in zip(a[8*i:8+8*i],v)))`for i in r for v in[b[j::8]for j in r]),2)

```

This is the first thing that came to my mind and so it can mostly likely be golfed down quite a bit more. In any case, its pretty straight-forward string manipulation:

```
def m(a,b):
    # Convert the integer inputs to their 64bit binary versions.
    a,b=map(lambda x:'{:064b}'.format(x),[a,b])

    n=''
    # For all rows in matrix a...
    for row in [a[8*i:8+8*i] for i in range(8)]:
        # For all columns in matrix b...
        for col in [b[j::8] for j in range(8)]:
            # Get each pair.
            pairs = zip(row, col)

            # Multiply each pair.
            mul_pairs = ['&'.join(z) for z in pairs]

            # XOR them all together.
            result = '^'.join(mul_pairs)

            # Append the result to n.
            n+=`eval(result)`

    return int(n,2)

```

# Answer
> 2 votes
# J (34)

This *should* work I think. It would be nice if you gave some test cases...

```
f=:~:/ .*&.(8 8&$@(_64&{.) :.,@#:)

```

This works with the test cases supplied in the comments (when changing `8 8` to `4 4` and changing `64` to `16`)

### Explanation

The whole function can be simplified to the following:

```
F&.G

```

Visual representation:

What this means: `G` is applied to both arguments. Then `F` is applied with `G x` as its left argument, and `G y` as its right argument. Then, the inverse of `G` is applied to the result of `F`. "Inverse?", you might ask. With inverse I mean a function applied `_1` times, so for example the inverse of `#:` (dec -\> bin vector) is `#:^:_1` (or `#.`) (bin vector -\> dec).

So, applying this theory, this would be `G`:

* `#:` takes the binary form of the argument
* `_64&{.` takes the last 64 items of the list. When there aren't 64 or more items, it will be padded with 0's
* `8 8&$` shapes it to an 8\*8 matrix
* `:.,` sets the reverse of `(4 4&$@(_16&{.)` to be just `,`: ravel

and this would be `F`:

* `~:/ .*` is matrix multiplication

---
Tags: code-golf, math, bitwise, binary-matrix
---


# Question
Title: Write a program which replaces with spaces the braces in cases where braces in places cause stasis
You are a project manager. One day, one of your programmers went insane (*not your fault*) and took all the expressions in the codebase and added random brackets to them, before quitting on the spot, ranting about your incompetence (*also not your fault*). This would be an easy fix, however, for some reason you aren't using revision control (*totally not your fault*). And for some reason, none of the other programmers want to go through every expression to fix up the mismatched brackets (*by the way, that is not your fault*). Programmers these days, you think to yourself. You will have to do it yourself. The horror! Such tasks were supposed to be beneath you...

The input will be a single line, which will contain a number of left brackets (`( [ {`) and right brackets (`) ] }`). It also may, but not always, contain comments (`/* */`) and string literals (`" "` or `' '`) and various numbers, letters, or symbols.

There will be at least one bracket (outside of a comment or string literal) that does not have a corrosponding opposite (outside of a comment or string literal). For example, an errant `}` without a `{` prior. Another example: a `(` which does not have a `)` afterwards. Your program will replace with a space the minimum number of brackets required to make the brackets match up.

Examples:

`(4 + (2 + 3))]` ==\> `(4 + (2 + 3))`  (the square bracket at the end)
`][][[]]` ==\>  `[][[]]` (the square bracket at the start)
`("Hel(o!"))` ==\> `("Hel(o!")`  (the parenthesis at the end)
`( /* )]*/` ==\>  `/* )]*/` (the parenthesis at the start)
`{()]` ==\>  `()`  (the curly bracket and the square bracket)

* Input can be taken from whichever way is most convenient (STDIN, command line argument, reading from a file, etc.)
* If there is more than one way to resolve the mismatch with the same number of removals, either is acceptable.
* There will be only mismatches in brackets. String literals and comments will always be correctly formed.
* The title comes from this SO thread
* There will never be any quotes in comments, quotes in quotes, comments in comments, or comments in quotes.

This is code golf, so minimum number of bytes wins. Ask questions in comments if the specification is not clear.

# Answer
> 6 votes
# Ruby, 223 characters

This one turned out a bit long.

```
u,b,i=[],[[],[],[]],-1
s=gets.gsub(/(\/\*|"|').*?(\*\/|"|')|~/){|m|u+=[m];?~}
s.chars{|c|i+=1
(t='{[('.index(c))?b[t].push(i):((t='}])'.index(c))&&(b[t].pop||s[i]=' '))}
b.flatten.map{|l|s[l]=' '}
puts s.gsub(/~/){u.shift}

```

What it does is take out the strings and comments first, so they don't get counted (and puts them back in later).

Then, it goes through the string character by character. When it finds an opening brace, it stores its position. When it finds a closing brace, it pops from its respective open brace storage array.

If `pop` returns `nil` (i.e. there weren't enough opening braces), it removes the closing brace. After this entire thing is done, it removes the remaining extra opening braces (i.e. there weren't enough closing braces).

At the end of the program, it puts all the strings and comments back and outputs them.

Ungolfed:

```
in_str = gets

# grab strings and comments before doing the replacements
i, unparsed = 0, []
in_str.gsub!(/(\/\*|"|').*?(\*\/|"|')|\d/){|match| unparsed.push match; i += 1 }

# replaces with spaces the braces in cases where braces in places cause stasis
brace_locations = [[], [], []]
in_str.each_char.with_index do |chr, idx|
    if brace_type = '{[('.index(chr)
        brace_locations[brace_type].push idx
    elsif brace_type = '}])'.index(chr)
        if brace_locations[brace_type].length == 0
            in_str[idx] = ' '
        else
            brace_locations[brace_type].pop
        end
    end
end
brace_locations.flatten.each{|brace_location| in_str[brace_location] = ' ' }

# put the strings and comments back and print
in_str.gsub!(/\d+/){|num| unparsed[num.to_i - 1] }
puts in_str

```

# Answer
> 4 votes
# Python 3, ~~410~~ ~~322~~ 317

```
import re;a='([{';z=')]}';q=[re.findall('".*?"|/\*.*?\*/|.',input())]
while q:
 t=q.pop(0);s=[];i=0
 for x in t:
  if x in a:s+=[x]
  try:x in z and 1/(a[z.find(x)]==s.pop())
  except:s=0;break
 if[]==s:print(''.join(t));break
 while 1:
  try:
   while t[i]not in a+z:i+=1
  except:break
  u=t[:];u[i]=' ';q+=[u];i+=1

```

Tries every possible set of deletions, starting with smaller ones, until it finds one where the braces are balanced. (By which I mean fully correctly balanced: `{{(})` produces  `( )`, not  `{(})`.)

The first version used a recursive generator function, which was really cool but also really long. This version performs a simple breadth-first search using a queue. (Yes, it's a factorial time algorithm. What's the problem? :^D)

# Answer
> 2 votes
## C - 406

An Attempt in C without using regular expressions.

```
#define A if((d==125||d==93||d==41)
char*s;t[256];f(i,m,n,p){while(s[i]!=0){int c=s[i],k=s[i+1],v=1,d;if((c==42&&k==47)||(c==m&&i>n))return i;if(!p||p==2){if((c==39||c==34)||(c==47&&k==42)){i=f(i,c*(c!=47),i,p+1);
c=c==47?42:c;}d=c+1+1*(c>50);A){v=f(i+1,d,i,2);if(!p&&v)t[d]++;if(p==2&&v)i=v;}}d=c;A&&!p){v=!!t[c];t[c]-=v;}if(p<2)putchar(c*!!v+32*!v);i++;}return 0;}main(int c,char*v[]){s=v[1];f(0,0,0,0);}

```

To compile and run (on a linux machine):
gcc -o brackets brackets.c
./brackets "\[(\])"

In undefined cases like \[ ( \] ) it returns the last valid bracket pair ( )

# Answer
> 2 votes
# Python 3, 320

```
import re
O=dict(zip('([{',')]}'))
def o(s,r,m=0,t=[]):m+=re.match(r'([^][)({}/"]|/(?!\*)|/\*.*?\*/|".*?")*',s[m:]).end();return r and o(s[:m]+' '+s[m+1:],r-1,m+1,t)or(o(s,r,m+1,t+[O[s[m]]])if s[m]in O else[s[m]]==t[-1:]and o(s,r,m+1,t[:-1]))if s[m:]else not t and s
s=input();i=0;a=0
while not a:a=o(s,i);i+=1
print(a)

```

Like DLosc's solution, this investigates every possible deletion, but it uses a recursive explore and fallback strategy which is a lot faster. I know that speed is not a criterion in code golf, and exhaustive search is in any case exponential, but this one can handle inputs like `({({({({({({({({(}}}}}}}}` in a couple of seconds.

---
Tags: code-golf, string, balanced-string
---


# Question
Title: Code that runs the Game of Life on itself
Write two rectangular blocks of code, each *w* characters wide and *h* characters tall, that implement Conway's Game of Life when arranged in a grid. (*w* and *h* may be any positive integers)

For example, the two code blocks might be: (*w* = 3, *h* = 2, not actual code)

```
XX|
--+

```

and

```
  |
--+

```

Treat the first block as if it is the "alive" cell in the Game of Life and the second block as if it is the "dead" cell.

Now arrange multiple copies of these two blocks into a larger program that represents a Game of Life grid, such as this glider:

```
  |  |  |  |  |
--+--+--+--+--+
  |  |XX|  |  |
--+--+--+--+--+
  |  |  |XX|  |
--+--+--+--+--+
  |XX|XX|XX|  |
--+--+--+--+--+
  |  |  |  |  |
--+--+--+--+--+
  |  |  |  |  |
--+--+--+--+--+

```

**Now here is the key point:** when this code is run, the output must be the Game of Life grid that is the generation after this, using the same alive and dead code blocks for the cells.

So the output to the program above would be the next generation of the glider, which also serves as a runnable program:

```
  |  |  |  |  |
--+--+--+--+--+
  |  |  |  |  |
--+--+--+--+--+
  |XX|  |XX|  |
--+--+--+--+--+
  |  |XX|XX|  |
--+--+--+--+--+
  |  |XX|  |  |
--+--+--+--+--+
  |  |  |  |  |
--+--+--+--+--+

```

Running this would produce the next generation:

```
  |  |  |  |  |
--+--+--+--+--+
  |  |  |  |  |
--+--+--+--+--+
  |  |  |XX|  |
--+--+--+--+--+
  |XX|  |XX|  |
--+--+--+--+--+
  |  |XX|XX|  |
--+--+--+--+--+
  |  |  |  |  |
--+--+--+--+--+

```

And so on.

The process should be indefinitely repeatable and work for any arrangement of your alive and dead code blocks in a Game of Life grid.

The output grid should have the same the same dimensions as the program that it came from (5 by 6 above). Grid sizes as small as 1 by 1 should work, and they may be arbitrarily large. Naturally, an empty grid will just output itself.

**Update:** Being able to simulate grids of any dimensions without having to change the "tiles" would be ideal but since this seems very difficult I will accept answers that assume the grid is a certain size (maybe around 16\*16).

The Game of Life rules are as follows:

1. Any live cell with less than 2 or more than 3 live (Moore) neighbors dies.
2. Any dead cell with exactly 3 live neighbors comes alive.
3. Other cells do not change.

# Scoring

The challenge is to do this in the smallest code block area possible. Your score is *w* * *h*. The lowest score wins. In case of ties the highest voted answer wins.

# Details

* Besides the newlines needed to make things rectangular, your two code blocks (and therefore your Game of Life grid programs) should only contain printable ASCII characters (hex codes 20 to 7E, **no tabs, no extra newlines**).
* Both code blocks must have exactly *w* * *h* characters (besides the necessary newlines) with at least a one character difference. Padding them with spaces or comments is fine. They should not change from one generation to the next.
* The output should either go to a file or to stdout. There is no input.
* The boundary conditions may either be periodic (where the top edge borders the bottom and the left edge borders the right) or infinite (where all out-of-bounds cells are always dead). Choose whatever suits you best.
* Reading your own source code is **not** allowed.
* Any language or tool that already does this is not allowed. (Just in case one exists.)

**Note:** The `-|+` characters above were only used to emphasize the cell borders. Your blocks do not need any distinguishable border. *However*, when displaying your output it would be helpful if there was some distinguishable separation between blocks, perhaps made with a character never used in the program so it is easy to remove. e.g.

```
DD+DD+DD+DD
+++++++++++
AA+DD+AA+DD

```

instead of

```
DDDDDDDD
AADDAADD

```

# Answer
# Perl, w\*h=233\*1=233 (per cell)

Cells work in any grid size (actually even with irregular row length). Out of boundary cells are considered dead.

*Dead Cell*

```
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});

```

*Living Cell*

```
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});

```

*Glider*

```
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});

```

generates:

```
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=1}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});
my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});my$y;INIT{$y=__LINE__;$h{++$x{$y}}{$y}=0}eval($c=q{$n=0;$o++;for$i(-1..1){$n+=$i|$_&&$h{$o+$i}{$y+$_}for(-1..1)}print"my\$y;INIT{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=",$n==2?$h{$o}{$y}:$n==3||0,"}eval(\$c=q{$c});",!($o%=$x{$y})&&"\n"});

```

*Explanation (not current)*

```
# Perl has several special blocks that are executed at certain stages.
# BEGIN blocks are executed at compilation stage
BEGIN
{
  # current row index and row count in execution stage
  $y=__LINE__;
  # $x{$y} is the cell index in current row and cell count in execution stage
  # $h{..}{..} set cell to dead || alive
  $h{++$x{$y}}{$y}=1
}

# dead || alive
$v=1;
# row index
$p=__LINE__;
# write cell code to $c
$c=q{
  # reset neighbour count
  $n=0;
  # cell index
  $o++;
  # count living neighbours
  for$i(-1..1){$n+=$i|$_?$h{$o+$i}{$p+$_}:0for(-1..1)}
  # reset cell index to 0 when end of row is reached
  $o%=$x{$p};
  # dead || alive for next generation of this cell
  $v=$n==3||$n==2&&$v||0;
  # print the new cell
  print"BEGIN{\$y=__LINE__;\$h{++\$x{\$y}}{\$y}=$v}\$v=$v;\$p=__LINE__;\$c=q{$c};eval\$c;",$o?"":"\n"
};
# execute cell code
eval$c;

```

# Perl, w\*h=140\*2=280 (per cell)

Multi-line cell is not efficient but can eliminate `__LINE__`.

Dead Cell

```
BEGIN{++$v}eval($c=q<;;;;;;++$y;map{$i{$y}+=$h{$y+$_}}(-$a-1..-$a+1,-1,1,$a-1..$a+1);print'BEGIN{++$v}eval($c=q<',$c,'>);',!($y%$a)&&"\n">);
BEGIN{$a||=$v,$h{++$x}=0}eval($c=q<$n=$i{++$z};print'BEGIN{$a||=$v,$h{++$x}=',$n==2?$h{$z}:$n==3||0,'}eval($c=q<',$c,'>);',!($z-$y)&&"\n">);

```

Living Cell

```
BEGIN{++$v}eval($c=q<;;;;;;++$y;map{$i{$y}+=$h{$y+$_}}(-$a-1..-$a+1,-1,1,$a-1..$a+1);print'BEGIN{++$v}eval($c=q<',$c,'>);',!($y%$a)&&"\n">);
BEGIN{$a||=$v,$h{++$x}=1}eval($c=q<$n=$i{++$z};print'BEGIN{$a||=$v,$h{++$x}=',$n==2?$h{$z}:$n==3||0,'}eval($c=q<',$c,'>);',!($z-$y)&&"\n">);

```
> 14 votes

# Answer
## JavaScript ES6 (239 x 1 characters per cell)

Dead cell:

```
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');

```

Alive cell:

```
f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');

```

Only difference being `S[j]=0` for dead and `S[j]=1` for alive cells.

Grid size is controlled with variables W (width) and H (height). Cells outside grid are dead.

**Commented version**

```
f=r=>{
    S=S||[],    // cell states
    j=S.length, // current index
    S[j]=1,     // state of this cell
    W=5,        // width of grid
    H=6;        // height of grid
    if (j+2 > W*H)  // if last cell
        /* Loop all cells and gather code for output */
        for (i in S)
            /* Function source with state replaced */
            r +=("f="+f+";f('');").replace(/0|1/, ~~[S[i],1] // lookup table
                [~~S[i-W] + ~~S[+i+W] + // +i to convert from int to string
                ~~(i % W ? S[--i] + S[i-W] + S[W+i++] : 0) +
                ~~(i % W < W-1 ? S[++i] + S[i-W] + S[W+i--] : 0)-2]),
            r = ++i % W ? r : (console.log(r), "")
};
f(''); // call current cell function to set state of the cell

```

**Glider (5 x 6 grid)**

```
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');

```

Outputs next generation:

```
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=1,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');
f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');f=e=>{S=S||[],j=S.length,S[j]=0,W=5,H=6;if(j+2>W*H)for(i in S)e+=("f="+f+";f('');").replace(/0|1/,~~[S[i],1][~~S[i-W]+~~S[+i+W]+~~(i%W?S[--i]+S[i-W]+S[W+i++]:0)+~~(i%W<W-1?S[++i]+S[i-W]+S[W+i--]:0)-2]),e=++i%W?e:(console.log(e),"")};f('');

```
> 8 votes

# Answer
**Python, 67x33 = 2,211**

Note, that this is my pretty version, where I added a line of "#" to every other line in a life cell, and " " to every other line in a dead cell. Also, the cells are separated by "#" lines. This way, you can place an initial configuration in a text file, e.g. `GOL.py`, and look at it with a tiny font to see what is going on each step. To get to the next step, execute `python GOL.py > GOL1.py;mv GOL1.py GOL.py` and have a look again.

My solution works on a grid of arbitrary size and assumes periodic boundary conditions. I haven't tested varying line widths, but there definitely is capability for that.

I should also mention, that the success of this solution depends on `__del__` being called when `a` is destroyed at the end of the program. The Python documentation states

> It is not guaranteed that `__del__()` methods are called for objects that still exist when the interpreter exits.

So, I just hope, that this not only works with my interpreter.

Live cell:

```
<sup><sub>c=['import sys;o=sys.stdout.write;r=range;l=len;w=66',#############
###################################################################
'class B(list):',' def __getitem__(s,k):',#########################
###################################################################
'  return list.__getitem__(s,k%l(s))','class A(B):',###############
###################################################################
' def e(s,k,m):','  g=(s[k-1][m]+s[k+1][m]+s[k][m-1]+s[k][m+1]',###
###################################################################
'+s[k-1][m-1]+s[k-1][m+1]+s[k+1][m-1]+s[k+1][m+1])',###############
###################################################################
'  if s[k][m]==0:return 1 if g==3 else 0',#########################
###################################################################
'  return 1 if g==2 or g==3 else 0',' def u(s,i,y,b):',############
###################################################################
'  for j in r(l(s[i])):o(y+b[s.e(i,j)]*(w-l(y))+"#")',#############
###################################################################
'  print;print"#".join([b[s.e(i,j)]*w for j in r(l(s[i]))])+"#"',##
###################################################################
' def __del__(s):','  for i in r(l(s)):','   y="";b=[" ","#"]',####
###################################################################
'   for q in ["c=["]+[repr(x)+","for x in c]+[',###################
###################################################################
'"];import os;exec(os.linesep.join(c))"]:',########################
###################################################################
'    if l(y+q)>w:s.u(i,y,b);y=""','    y+=q','   s.u(i,y,b)',######
###################################################################
'   for j in r(l(s[i])):o("a[-1].append(%i);"%s.e(i,j)+" "*51)',###
###################################################################
'   print;print "#"*l(s[i])*(w+1)','if "a" not in locals():a=A()',#
###################################################################
'a.append(B())',];import os;exec(os.linesep.join(c))###############
###################################################################
a[-1].append(1);
###################################################################</sub></sup>
```

Dead cell:

```
<sup><sub>c=['import sys;o=sys.stdout.write;r=range;l=len;w=66',            #
                                                                  #
'class B(list):',' def __getitem__(s,k):',                        #
                                                                  #
'  return list.__getitem__(s,k%l(s))','class A(B):',              #
                                                                  #
' def e(s,k,m):','  g=(s[k-1][m]+s[k+1][m]+s[k][m-1]+s[k][m+1]',  #
                                                                  #
'+s[k-1][m-1]+s[k-1][m+1]+s[k+1][m-1]+s[k+1][m+1])',              #
                                                                  #
'  if s[k][m]==0:return 1 if g==3 else 0',                        #
                                                                  #
'  return 1 if g==2 or g==3 else 0',' def u(s,i,y,b):',           #
                                                                  #
'  for j in r(l(s[i])):o(y+b[s.e(i,j)]*(w-l(y))+"#")',            #
                                                                  #
'  print;print"#".join([b[s.e(i,j)]*w for j in r(l(s[i]))])+"#"', #
                                                                  #
' def __del__(s):','  for i in r(l(s)):','   y="";b=[" ","#"]',   #
                                                                  #
'   for q in ["c=["]+[repr(x)+","for x in c]+[',                  #
                                                                  #
'"];import os;exec(os.linesep.join(c))"]:',                       #
                                                                  #
'    if l(y+q)>w:s.u(i,y,b);y=""','    y+=q','   s.u(i,y,b)',     #
                                                                  #
'   for j in r(l(s[i])):o("a[-1].append(%i);"%s.e(i,j)+" "*51)',  #
                                                                  #
'   print;print "#"*l(s[i])*(w+1)','if "a" not in locals():a=A()',#
                                                                  #
'a.append(B())',];import os;exec(os.linesep.join(c))              #
                                                                  #
a[-1].append(0);
###################################################################</sub></sup>
```

**Python, 67x17 = 1,139** To get a golfed version, still with some way to recognise life cells from afar, the second print statement in lines 19 and 31 as well as every other line is deleted.

Live cell:

```
<sup><sub>c=['import sys;o=sys.stdout.write;r=range;l=len;w=66',#############
'class B(list):',' def __getitem__(s,k):',#########################
'  return list.__getitem__(s,k%l(s))','class A(B):',###############
' def e(s,k,m):','  g=(s[k-1][m]+s[k+1][m]+s[k][m-1]+s[k][m+1]',###
'+s[k-1][m-1]+s[k-1][m+1]+s[k+1][m-1]+s[k+1][m+1])',###############
'  if s[k][m]==0: return 1 if g==3 else 0',########################
'  return 1 if g==2 or g==3 else 0',' def u(s,i,y,b):',############
'  for j in r(l(s[i])):o(y+b[s.e(i,j)]*(w-l(y))+"#")','  print',###
' def __del__(s):','  for i in r(l(s)):','   y="";b=[" ","#"]',####
'   for q in ["c=["]+[repr(x)+","for x in c]+[',###################
'"];import os;exec(os.linesep.join(c))"]:',########################
'    if l(y+q)>w:s.u(i,y,b);y=""','    y+=q','   s.u(i,y,b)',######
'   for j in r(l(s[i])):o("a[-1].append(%i);"%s.e(i,j)+" "*51)',###
'   print','if "a" not in locals():a=A()','a.append(B())',#########
];import os;exec(os.linesep.join(c))###############################
a[-1].append(1);                                                   </sub></sup>
```

Dead cell:

```
<sup><sub>c=['import sys;o=sys.stdout.write;r=range;l=len;w=66',            #
'class B(list):',' def __getitem__(s,k):',                        #
'  return list.__getitem__(s,k%l(s))','class A(B):',              #
' def e(s,k,m):','  g=(s[k-1][m]+s[k+1][m]+s[k][m-1]+s[k][m+1]',  #
'+s[k-1][m-1]+s[k-1][m+1]+s[k+1][m-1]+s[k+1][m+1])',              #
'  if s[k][m]==0: return 1 if g==3 else 0',                       #
'  return 1 if g==2 or g==3 else 0',' def u(s,i,y,b):',           #
'  for j in r(l(s[i])):o(y+b[s.e(i,j)]*(w-l(y))+"#")','  print',  #
' def __del__(s):','  for i in r(l(s)):','   y="";b=[" ","#"]',   #
'   for q in ["c=["]+[repr(x)+","for x in c]+[',                  #
'"];import os;exec(os.linesep.join(c))"]:',                       #
'    if l(y+q)>w:s.u(i,y,b);y=""','    y+=q','   s.u(i,y,b)',     #
'   for j in r(l(s[i])):o("a[-1].append(%i);"%s.e(i,j)+" "*51)',  #
'   print','if "a" not in locals():a=A()','a.append(B())',        #
];import os;exec(os.linesep.join(c))                              #
a[-1].append(0);                                                   </sub></sup>
```

If there is demand, I will gladly explain the inner workings of my solution when I find the time.
> 6 votes

---
Tags: code-golf, quine, game-of-life, source-layout
---


title: The Forest Path

text:
# Question
Title: The Forest Path
After your disastrous canoe ride, you ended up falling off a waterfall at the end of the river rapids. Your canoe exploded, but you managed to survive the explosion. However, your river journey went completely off the map - you have now found yourself lost in the midst of a forest. Luckily, you still have your programming skills, so you decide to carve a program into the side of a tree to help you find your way through the forest. However, there is not much surface area on the tree, so you must make your program as short as possible.

The forest can be described as a `n` by `n` (`n > 5`) square of characters, which will only consist of the lowercase letters `a-z`. An example forest:

```
anehcienwlndm
baneiryeivown
bnabncmxlriru
anhahirrnrauc
riwuafuvocvnc
riwnbaueibnxz
hyirorairener
ruwiiwuauawoe
qnnvcizdaiehr
iefyioeorauvi
quoeuroenraib
cuivoaisdfuae
efoiebnxmcsua

```

You may have noticed that in this forest, there is a diagonal line of `a` characters running through it from the top left corner to the bottom right corner. This is a "path" through the forest which will lead you somewhere if you follow it. Your task is to write a program which will find the singular path. I will now more specifically describe what connotates a "path" in this challenge.

A "path", in this challenge, is defined as a line similiar to one which might have been generated with a Bresenham algorithm, but with the added requirements that:

* The line must be a minimum 6 characters long
* Each collinear (completely adjacent) group of characters in the line *must be the same length*.
* It will begin at one edge of the forest and end at the opposite edge (see my comment here for elaboration)

To explain the second requirement more clearly, consider the following line:

```
aaa
   aaa
      aaa
         aaa
            aaa

```

This line is composed of collinear "segments" of characters, each of which are exactly three characters long. It qualifies as a path. Now consider this line:

```
a
 aa
   a
    aa
      a
       aa

```

This line is composed of collinear "segments" that are not all exactly the same length of characters (some of them are 1 character long and some of them are 2). Thus, this one does not qualify as a path.

Your program, given a map of the forest, identify the characters used in the path. Input is to whatever is convienient (e.g. command line argument, STDIN, `prompt()`, etc.). It cannot be pre initialised into a variable. The first part of the input is a single integer `n` representing the size of the forest (the forest is always a square). After that is a space and then the entire forest as a single string. For instance, the example forest would be presented, as an input, like this:

```
13  anehcienwlndmbaneiryeivownbnabncmxlriruanhahirrnraucriwuafuvocvncriwnbaueibnxzhyirorairenerruwiiwuauawoeqnnvcizdaiehriefyioeorauviquoeuroenraibcuivoaisdfuaeefoiebnxmcsua

```

The output for this would be:

```
a

```

because the path is formed using the letter `a`. There will only be one path in the forest. This is code golf, so the lowest number of characters wins. If you have questions, ask in the comments.

# Answer
> 3 votes
## APL (Dyalog 14) (70)

```
⎕ML←3⋄Z/⍨1=≢¨Z←∪¨(↓⍉F),(↓F),{(⍳≢⍵)⌷¨↓⍵}¨(⊂F),⊂⌽F←⊃{⍵⍴⍨2/⍎⍺}/I⊂⍨' '≠I←⍞

```

Explanation:

* `⎕ML←3`: set `ML` to `3`, meaning  has its APL2 meaning.
* `I←⍞`: read a line from the keyboard and store it in `I`
* `I⊂⍨' '≠I`: split `I` on the spaces
* `{`...`}/`: apply this function to the two resulting strings:
    + `2/⍎⍺`: evaluate the left argument and replicate it twice, giving the matrix size
    + `⍵⍴⍨`: format the right argument using that size
* `F←⊃`: unbox it and store it in `F`.
* `{(⍳≢⍵)⌷¨↓⍵}¨(⊂F),⊂⌽F`: get the diagonals: from each row in both `F` and `⌽F` (vertically mirrored `F`), get the value at column X, where X is its row number
* `(↓⍉F),(↓F),`: get the rows and columns of `F`
* `Z←∪¨`: find the unique values on each row, column and diagonal and store them in `Z`.

Since the 'forest' is rectangular, if there is a valid path it means one of these will consist of only one character, which is the path character, so:

* `Z/⍨1=≢¨Z`: take those subarrays from `Z` that have only one element.

This will display the characters for all valid paths, but since there should be only one that doesn't matter.

# Answer
> 4 votes
# Lua - ~~506~~ 380 - bytes

I felt kinda bad that you hadn't received any submission for your well thought out challenge, so I threw this together. It was quit fun inferring what the minimum distinguishable properties the path must have from the information you gave. I hope I got it right... AND correctly implemented it.

```
a=io.read"*l"n=a:match("%d+")+0 m=a:match"[a-z]+"o=""for i=1,n do for k=1,n^2,n do o=o..m:sub(i+k-1,i+k-1)end end q={m,o}for g=1,n^2 do for u=1,2 do l=q[u]:sub(g,g)for r=1,n do i=1 t=0 e=0 while i do s,e=q[u]:find(l:rep(r),e+1)if s then x=s-(e-s)-i-1 print(s,i,r,n,r)if x==n or x==n-2 or t==0 then t=t+1 i=s end else i=nil end end if t*r==n then print(l)os.exit()end end end end

```

It can be tested with:

```
lua divisorPath.lua "input"

```

~~If a wild challenger appears, I'll look to golf my code for what it's worth.~~

**Update**: golfed in honour of those who will rise above us. While I was at it I had to fix my code to recognized path going from right to left. Oops.

# Answer
> 3 votes
## Python - ~~384~~ ~~325~~ 275

This Algorithm basically checks the first and last row of the matrix for matching characters and then calculates the length of each line segment

```
012345
------
aaVaaa|0
aaVaaa|1
aaaVaa|2
aaaVaa|3
aaaaVa|4
aaaaVa|5

```

In the Example above:
The V in the first row is at index 2, the V in the last row at index 4.
So the length of each line segment would be n / (4-2)+1 = 2 with n=6.

It then checks if the line is valid.

In order to find a path from left to right, it swaps rows with columns and does the same thing again.

**Edit:** Can't quite get to 270 (Damn you Python and your damn indentation!!)

```
n,m=raw_input().split()
n,r=int(n),range
t=r(n)
a=[m[i:i+n]for i in r(0,n*n,n)]
for v in a,["".join([a[i][j]for i in t])for j in t]:
 for i in t:
  for j in t:
   p=1-2*(j-i<0);d,c=p*(j-i)+1,v[0][i]
   if 6<=sum([v[z][i+(z/(n/d))*p*(n%d==0)]==c for z in t])==n:print c;exit()

```

# Answer
> 3 votes
# MATLAB - 270 characters

The following defines a function `x` that accepts a forest string as an argument and returns the character representing the valid "path" through the forest subject to the given rules.

```
function F=x(s),A=sscanf(s,'%d%s');n=A(1);A=reshape(A(2:end),n,n);for c=A(:)',B=A==c;for i=1:n,if~mod(n,i),C=[kron(eye(i),ones(n/i,1)),zeros(n,n-i)];for j=0:n-i,f=@(B)sum(sum(B&circshift(C,[0,j]))==n;D=fliplr(B);if f(B)|f(B')|f(D)|f(D'),F=char(c);end;end;end;end;end;end

```

The non-minified version is

```
function F = x(s)
    A = sscanf( s, '%d %s' );
    n = A(1);
    A = reshape( A(2:end), n,n );
    for c = A(:)'
        B = A==c;
        for i = 1:n
            if ~mod( n, i )
                C = [kron( eye(i), ones( n/i,1 ) ), zeros( n,n-i )];
                for j = 0:n-i
                    f = @(B) sum(sum( B & circshift( C, [0 j] ))) == n;
                    D = fliplr(B);
                    if f(B) | f(B') | f(D) | f(D')
                        F = char(c);
                    end
                end
            end
        end
    end
end

```

The basic premise is to construct a boolean mask for every possible valid path and return any character whose index function in the matrix covers any mask. To accomplish this, only vertical or top-to-bottom backslash-shaped masks are created, but the forest matrix is compared in all four orientiations: identity, flipped, rotated 90°, flipped rotated 90°.

The function runs for any `n`. An example of it being invoked on the commandline is

```
x('13 anehcienwlndmbaneiryeivownbnabncmxlriruanhahirrnraucriwuafuvocvncriwnbaueibnxzhyirorairenerruwiiwuauawoeqnnvcizdaiehriefyioeorauviquoeuroenraibcuivoaisdfuaeefoiebnxmcsua')

ans =

    a

```

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