title: How varied is my obstacle course?

text:
# Question
Title: How varied is my obstacle course?
## Background

I have constructed a simple obstacle course by placing boxes in a rectangular room. Now I want to count the number of essentially different ways in which it can be solved. I need you to write me a program for that.

## Input

Your input is a non-empty rectangular array of the characters `.#`. The dots `.` are empty space, and the `#` are obstacles.

A *path* through the obstacle course begins at the top left corner and ends at the bottom right corner, and goes only right or down. Also, a valid path cannot go through an obstacle. Here are some examples drawn with `+`-characters:

```
Valid path  Invalid path  Invalid path  Invalid path
++........   ++........    +++++.....    ..+.......
.++++++#..   .+.....#..    ....+++#++    ..++...#..
......+#..   .+.++++#..    .......#.+    ...+++.#..
....#.++++   .+++#.++++    ....#....+    ....#+....

```

Two paths are *essentially similar*1 if one can be transformed into the other by moving one `+` at a time. The intermediate paths must also be valid, so you can't bend a path over an obstacle. For example, the first two paths here are essentially similar, but the third is essentially different from them, since it can't be wiggled over the two obstacles:

```
++........   +.........   +++++++++.
.+++++.#..   ++.....#..   .......#+.
.....+.#..   .++++++#..   .......#++
....#+++++   ....#.++++   ....#....+

```

## Output

Your output is the number of essentially different paths through the obstacle course. In other words, if all the valid paths are divided into classes of essentially similar paths, the output is the number of classes. Note that this number may be 0, if there are no valid paths.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. There are no time bounds, except that you should evaluate your program on every test case before submitting it.

## Test cases

```
....
....
.... => 1

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

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

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

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

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

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

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

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

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

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

```

1 The correct technical term is "homotopic".

# Answer
> 8 votes
# Snails, ~~53~~ 49 bytes

```
A^
\.+d!{.l\.+a3(.|~c!~}\.+r!(.u\.+e(.|~},\.,=~d~

```

For once, I did not have to use `t`, the dreaded teleport instruction. As a result, the test cases finish instantly instead of taking aeons.

Ungolfed:

```
A^
r\.+
{
    d\.+
    !{ r\.u \.+ a3 (.|~)}
    r\.+
    !{ d\.l \.+ a3 (.|~)}
},
d\.,
!(dr .)

```

The options `A^` mean to start at the upper-left corner and count all matching paths. The main idea is to check a canonicity condition for the paths. I honestly did not expect it to work, but it nailed the test cases, so.... What it tries to check for is that, within the current path, the greediest route has been selected, i.e. going right as many times as possible, down as many times as possible, etc. without crossing over any obstacles. This is done by checking, after moving right 1 or more times and then down 1 or more times, that the next square (which must be to the right) could not have been reached by going right one more time in the previous rightward segment. The analogous condition is also checked after moving right and then down.

# Answer
> 10 votes
# Python 2, ~~170~~ ~~131~~ 112 bytes

```
def f(C,t=1):i="#".join(C).find("#")+1;return([]<C)*(i<1or(i<t
and f([r[i:]for r in C],t-i))+(i>1)*f(C[1:],i-1))

```

A function, `f`, taking the obstacle course as a list of rows, and returning the number of essentially different paths.

## Explanation

The basic concept is this: We choose a certain obstacle, *o*, such that there are no other obstacles in the box bounding *o* and the top-left corner.

```
+--+....
|..|....
+--#<==== o
.....#..
.#......
........

```

We then consider the two sub-courses to the east and to the south of *o*. We only consider either of these sub-courses if *o* can actually be crossed from a direction that leads to them, that is, crossed from the north to get to the east, and crossed from the west to get to the south. We solve the problem for each of the selected sub-courses, and return the sum of the results. These numbers correspond to the number of essentially different paths when crossing *o* from the left and from the right, respectively, therefore the two resulting sets of paths are essentially different. Since there are no obstacles between the starting point and *o*, there is a path between the starting point and any entry point into each of these regions, and all such paths that lead to the same point are essentially similar, hence the above sum is the complete number of essentially different paths in the entire course.

```
                               A
_
........       ...|////      |....
........       ...|////      |....
...#....  -->  ...#////  -->  ....
.#....#.       .#..//#/       ..#.
........       ....////       ....

   |                           |
   v                           v
                  B
........       ___
........       .#....#.
___#....  -->  ........  -->   +
/#////#/
////////

```

Things are slightly complicated by the fact that the obstacle course alone doesn't convey all the information needed. For example, consider course *B* in the diagram above. Taken by itself, we can't determine whether each of the obstacles can be crossed from the north. If *B* were the input course, then, since all paths start at the top-left corner, neither obstacle could have been crossed from the north, but, since we can reach *B* from either side of the left obstacle when crossing *o* from the east, we should treat this obstacle as though it can be crossed from the north when solving the course; the same doesn't hold for the right obstacle, however, which can't be crossed from this direction.

We convery this extra information by specifying, along with the obstacle course, the number of characters along the first row, starting from the left, that the path can start at. In the diagram above, this is depcited as the solid line next to each course. While, technically, we also need to specify the corresponding number of characters along the first column that the path can start at, as in the case of sub-course *A*, in practice we always selected the highest obstacle, so this information is not required.

The actual selection of *o* is as follows: We pretend that each row, other than the last, is followed by an obstacle (i.e., has a `#` appended to it), and select the first obstacle in the resulting course, in reading order. For rows (other than the last) that had no obstacle originally, this effectively mean that we skip them (while noting that the path below may start at any character along the top row). Eventually, we end up with a course that has a single row with no obstacles, for which there is only one possible path.

# Answer
> 6 votes
## CJam, ~~85~~ ~~84~~ ~~82~~ ~~81~~ ~~80~~ 79 bytes

```
qN/:Q,(Qz,(:R_T]2/e~e!{'#Qs@{\(\@>}%s-},{_}{(a\L{@+_@\-_{2$\f.=0fe=2&},}h;}w;],

```

Try it online. Or run the entire test suite.

The efficiency of this solution is probably quite horrible but it solves each test case within a few seconds.

### Explanation

I'll have to add a full breakdown of the code later, but the algorithmic idea is this:

* Let the width and height of the grid be `W` and `H`, respectively.
* We generate all possible paths as the distinct permutations of `W-1` copies of `0` and `H-1` copies of `W-1` (where `0` represents a horizontal step and `W-1` a vertical step). We walk all of those paths by repeatedly taking the first element of the grid and then skipping `step` cells in reading order (where `step` is `0` or `W-1`). We discard all paths which contain a `#`.
* Then we repeatedly remove one group of similar paths (which will be all paths similar to the first of the remaining paths). Checking for similar paths gets a bit easier by relaxing the condition for them slightly: instead of checking whether one `x` has moved, we check whether the paths differ in exactly two places. If that is the case, those two places will have a vertical and horizontal move swapped. This causes the entire segment between those moves to be shifted diagonally by one cell. But if both of those paths are valid, shifting any part of the path by one cell diagonally cannot cross an obstacle, so they are similar. We still need to find the transitive closure, so we keep doing that until we find no more similar paths before moving on to the next group.
* Finally, we count the groups we've found, which we left at the bottom of the stack.

---
Tags: code-golf, grid, path-finding, counting
---


title: Golf a Purple Interpreter

text:
# Question
Title: Golf a Purple Interpreter
# Golf a Purple Interpreter

Purple is an esolang which is designed with two main purposes:

* To be a minimization of Aubergine, since there just aren't enough self-modifying one-instruction languages around.
* To admit the possibility of *terrifyingly small* golfed interpreters. My first pass at a reasonably full-featured Python 2 interpreter is only 702 bytes, and I'm sure a more experienced golfer could shave quite a bit from that.

Your goal is to write an interpreter for this language.

## Information on Purple:

A Purple program is a sequence of characters placed into an infinite, addressable memory array such that the first character of the program is placed at address zero. The rest of the array (both before and after where the Purple program is stored) is initialized to zero.

There are three registers in Purple, called *a* and *b* and *i*, each of which can hold a signed integer and is initialized to zero. *i* is also the instruction pointer, and always points to the currently executing Purple instruction.

Each cycle, the interpreter will read a sequence of three contiguous characters beginning from the memory location indicated by the instruction pointer and attempt to execute this sequence as the Purple instruction. Afterwards, the instruction pointer is always incremented by 3.

Syntactically, the Purple instruction consists of three characters (or encodings thereof) in a row, like "*xyz*".

The first character *x* can be any of the following:

```
abABio

```

These symbols have the following meaning:

```
a - Place the result in register a.
b - Place the result in register b.
A - Place the result in the location in memory referred to by register a.
B - Place the result in the location in memory referred to by register b.
i - Set the instruction pointer to the result.
o - Output the result to stdout.

```

The other two bytes *y* and *z* can be any of the following:

```
abABio1

```

Each of these symbols has the following meaning:

```
a - Return the contents of register a.
b - Return the contents of register b.
A - Return the contents of the memory array at the address stored in register a.
B - Return the contents of the memory array at the address stored in register b.
i - Return the contents of register i (the instruction pointer).
o - Return the value of a single character read from stdin.
1 - Return the literal numeric value 1.

```

After fetching the instruction, the Purple interpreter will evaluate *y* and then *z*, subtract the result of *z* from the result of *y*, and then perform the action indicated by *x* on the difference.

If the sequence of three characters (or encodings thereof) is not a valid Purple instruction, the interpreter halts immediately without giving any errors.

## Your interpreter must:

* Be a complete program, not a function.
* Never output to stderr, unless EOF is read.
* Behave identically to the reference implementation on all well-formed inputs that do not involve very large numbers, including the test programs given below. (Well, identically up to timing--it can run slower, but not by too much!)

You may provide the program to the interpreter in any form you wish: read it from a file, embed it in the program as a string, or read it from stdin.

## Test cases:

The program

```
ooo

```

when run with input

```
z!

```

should yield

```
Y

```

---

The program

```
bbboobiii

```

when run with input

```
It's a cat program.

```

(or any other input) should yield

```
It's a cat program.

```

(or whatever input it received) and then *start over and do the same thing again*.

---

The program

```
Aoab11bi1bABoAaiba

```

when run with input

```
0

```

should yield

```
0

```

and then halt, but when run with input

```
1

```

should continue outputting

```
1

```

forever.

---

The program

```
b1bbb1oAbabaa1ab1Ab1Bi1b

```

should yield

```
b1bbb1oAbabaa1ab1Ab1Bi1b

```

---

The program

```
aA1aa1bb1oAbbi1bb1bbAb1Bi1b Purple is the awesomest! Why haven't you tried it yet?
!dlroW ,olleG

```

should yield

```
Hello, World!

```

## Scoring:

This is , so shortest source in bytes, as potentially modified by the following bonus, wins.

### Bonus:

* -10% if your interpreter reads a filename from either stdin or from a command line argument and loads the program from the file.

# Answer
# Pyth, ~~148~~ ~~128~~ 121 bytes (or 124 * .9 = 111.6, see bottom)

```
J,00=kjb.z .eXHkCbz#=b-Fm?=zx"oabABi1"C@H+Zd@s[0Jm.x@Hk0JZ1H)zCh~tkS2 ?hKx"abAB"=YC@HZ?PKXH@JKbXJKb?qY\i=Zb?qY\opCbvN=+Z3

```

Test suite

Code given on first line of STDIN, input to the Purple program on the rest of STDIN. To use code with newlines, use alternate version at the bottom.

Reasonably golfed. Here's it with linebreaks and indentation for clarity:

```
J,00
=kjb.z
 .eXHkCbz
#
  =b-Fm
    ?=zx"oabABi1"C@H+Zd
      @
        s[0Jm.x@Hk0JZ1H)
        z
      Ch~tk
    S2
   ?hKx"abAB"=YC@HZ
    ?PK
      XH@JKb
      XJKb
  ?qY\i=Zb
  ?qY\opCb
  vN
  =+Z3

```

Basically, a `#` loop does the execution and halting via error-break.

`a` and `b` are combined into a single variable, `J`. `Z` is the instruction pointer. `k` is input to the Purple program. `H` is the tape, represented as a dictionary. `b` is the current result. `Y` is the current first byte of the instruction.

## Reading from file:

```
J,00=kjb.z .eXHkCbjb'z#=b-Fm?q\o=zC@H+ZdCh~tk@s[Jm.x@Hk0JZ1H)x"abABi1"zS2 ?hKx"abAB"=YC@HZ?PKXH@JKbXJKb?qY\i=Zb?qY\opCbvN=+Z3

```

Give file name as first line of STDIN. Test run:

```
$ cat purple-final.pyth
J,00=kjb.z .eXHkCbjb'z#=b-Fm?=zx"oabABi1"C@H+Zd@s[0Jm.x@Hk0JZ1H)zCh~tkS2 ?hKx"abAB"=YC@HZ?PKXH@JKbXJKb?qY\i=Zb?qY\opCbvN=+Z3
$ cat purple-code.txt
aA1aa1bb1oAbbi1bb1bbAb1Bi1b Purple is the awesomest! Why haven't you tried it yet?
!dlroW ,olleG
$ pyth purple-final.pyth <<< 'purple-code.txt'
Hello, World!

```
> 8 votes

# Answer
# JavaScript (ES6), 292 bytes

```
eval(`a=b=i=d=0;v=n=>(x=m[i+n])==97?a_98?b_65?m[a]_66?m[b]_105?i_111?p()[c]()_49?1:d=1;for(m=[...(p=prompt)()].map(b=>b[c="charCodeAt"]());!d;i+=3)(y=v(1),d)||(z=v(2),d)?1:(x=m[r=y-z,i])==97?a=r_98?b=r_65?m[a]=r_66?m[b]=r_105?i=r-3_111?alert(String.fromCharCode(r)):d=1`.replace(/_/g,":x=="))

```

## Explanation

JavaScript answers are always weird when `STDIN` and `STDOUT` are required...

The first prompt is the input for the program string. Each prompt that results from an `o` instruction will read only the first character.

`eval` is used to replace a common phrase which saves a few bytes. Ungolfed and without the `eval` the program looks like this:

```
// Initialisation
a=b=i=                            // initialise registers to 0
  d=0;                            // d is set to true when the program should die

// Gets the result of Y or Z
v=n=>                             // n = offset from i
  (x=m[i+n])==97?a:               // x = value of instruction
  x==98?b:
  x==65?m[a]:
  x==66?m[b]:
  x==105?i:
  x==111?p()[c]():
  x==49?1:
  d=1;                            // if it was none of the valid values, die

// Execution loop
for(
  m=                              // m = memory array
    [...(p=prompt)()]             // receive the program
    .map(b=>b[c="charCodeAt"]()); // initialise m to the ASCII values of the program
  !d;                             // finish if an error occured
  i+=3                            // increment i
)
  (y=v(1),d)||                    // get the value of Y and check for errors
  (z=v(2),d)?1:                   // get the value of Z and check for errors

    // Get the result of X
    (x=m[r=y-z,i])==97?a=r:       // r = result of y - z
    x==98?b=r:
    x==65?m[a]=r:
    x==66?m[b]=r:
    x==105?i=r-3:
    x==111?alert(String.fromCharCode(r)):
    d=1

```
> 5 votes

# Answer
## Ceylon, ~~827~~ ~~792~~ 671 bytes

```
import ceylon.language{l=variable,I=Integer,x=nothing,p=process,m=map}shared void run(){try{if(exists d=p.arguments[0]){l value t=m{*d*.hash.indexed};l I a=0;l I b=0;l I i=0;I g(I j)=>t[j]else 0;l{I*}c=[];I o{if(c==[]){if(exists e=p.readLine()){c=e*.hash.chain{10};}else{c={-1}.cycled;}}assert(is I r=c.first);c=c.rest;return r;}value f=m{97->{a},98->{b},65->{g(a)},66->{g(b)},105->{i},111->{o},49->{1}};value s=m{97->((I v)=>a=v),98->((I v)=>b=v),65->((I v)=>t=m{a->v,*t}),66->((I v)=>t=m{b->v,*t}),105->((I v)=>i=v),111->((I v)=>p.write("``v.character``"))};I h(I v)=>f[v]?.first else x;while(0<1){(s[g(i)]else x)(h(g(i+1))-h(g(i+2)));i+=3;}}}catch(AssertionError e){}}

```

It behaves a bit differently than the reference implementation when the program tries to read input at EOF – the reference implementation crashes with a TypeError, which is too costly to reproduce here (and also likely a bug), so this will return -1 instead (repeatedly, if necessary).

(When trying to write this -1 to stdout, the interpreter will finish with an OverflowError, though. Similar will happen if an Integer outside of the Unicode range is output.)

The interpreter takes the program as its first command line argument (make sure to quote it for your shell when it contains whitespace or other interesting stuff).

In Ceylon we can only easily read input line-wise (I guess this will change in one of the next versions), so when `o` is used for reading, I'm reading a whole line and buffer the parts for future uses. I guess it works similar in the Python implementation when connected to a terminal.

---

When trying to execute a command (part) which is not one of the valid characters, the `nothing` will cause an AssertionError to be thrown, which we then catch in the catch block around the main loop.

I think this should be preferably be a custom Exception type (as AssertionError could also occur at other places if I have a bug), but that would take much more space, eating most improvements I made from the first version.

Some tricks used for golfing:

* The previous versions used a ceylon.collection.HashMap – instead we now use an immutable map as created by the `map` function, and create a new one each time `A` or `B` is used as *x*.
* I use alias-imports for all identifiers from ceylon.language which are used more than once (including the `variable` annotation, which is now `l`).
* I got rid of the class `E` (for environment) and the `s` (step) method – everything now happens inside the `run` function.
* Instead of using `.integer` for getting the codepoint of a character, `.hash` gives the same result. Thus `string*.hash` is the same as `string.map(Character.integer)` (gives an iterable of the codepoints from a string).
* When a type is alias-imported, `is I ...` is shorter than `exists ...`.
* When converting something (e.g. `x`) into a string, `"``t``"` is shorter than `t.string` (or, what I used for a character, `String{t}`).
* functions used just once can often be inlined.

Here is the formatted (and commented) version:

```
// Purple – a self-modifying, "one-instruction" language.
//
// Question:  http://codegolf.stackexchange.com/q/65411/2338
// My answer: http://codegolf.stackexchange.com/a/65492/2338

import ceylon.language {
    l=variable,
    I=Integer,
    x=nothing,
    p=process,
    m=map
}

shared void run() {
    try {
        // Reading code from file certainly takes more than 73 characters,
        // this isn't worth the 10% bonus.
        if (exists d = p.arguments[0]) {

            // The memory tape, as a Map<Integer, Integer>.
            // We can't modify the map itself, but we
            // can replace it by a new map when update is needed.
            l value t = m {
                // It is initialized with the code converted to Integers.
                // We use `.hash` instead of `.integer` because it is shorter.
                *d*.hash.indexed };

            // three registers
            l I a = 0;
            l I b = 0;
            l I i = 0;

            // get value from memory
            I g(I j) =>
                    t[j] else 0;

            // cached input which is still to be read
            l {I*} c = [];

            // get value from stdin.
            // we can only comfortably access stdin by line, so we read a whole line
            // and cache the rest for later.
            I o {
                if (c == []) {
                    if (exists e = p.readLine()) {
                        c = e*.hash.chain { 10 }; // convert string into ints, append \n
                    } else {
                        // EOF – return just -1 from now on.
                        c = { -1 }.cycled;
                    }
                }
                assert (is I r = c.first);
                c = c.rest;
                return r;
            }

            // Map of "functions" for fetching values.
            // We wrap the values in iterable constructors for lazy evaluation
            //  – this is shorter than using (() => ...).
            // The keys are the (Unicode/ASCII) code points of the mapped
            // source code characters.
            value f = m {
                // a
                97 -> { a },
                // b
                98 -> { b },
                // A
                65 -> { g(a) },
                // B
                66 -> { g(b) },
                // i
                105 -> { i },
                // o
                111 -> { o },
                // 1
                49 -> { 1 }
            };

            // Map of functions for "storing" results.
            // The values are void functions taking an Integer,
            // the keys are the ASCII/Unicode code points of the corresponding
            // source code characters.
            value s = m {
                // a
                97 -> ((I v) => a = v),
                // b
                98 -> ((I v) => b = v),
                // Modification of the memory works by replacing the map with a new one.
                // This is certainly not runtime-efficient, but shorter than importing
                // ceylon.collections.HashMap.
                // A
                65 -> ((I v) => t = m { a->v, *t }),
                // B
                66 -> ((I v) => t = m { b->v, *t }),
                // i
                105 -> ((I v) => i = v),
                // o – output as a character.
                111 -> ((I v) => p.write("``v.character``"))
            };

            // accessor function for the f map
            I h(I v) =>
                    f[v]?.first else x;

            // the main loop, can only be left by exception
            while (0 < 1) {
                (s[g(i)] else x)(h(g(i + 1)) - h(g(i + 2)));
                i += 3;
            }
        }
    } catch (AssertionError e) {
        // abort silently
    }
}

```
> 3 votes

---
Tags: code-golf, interpreter
---


title: Does the fishy road have an end?

text:
# Question
Title: Does the fishy road have an end?
I love \>\<\>, \>\<\> is life! 2D langages are amazing! In this challenge, you will have to say if a "fishy" road has an end, while code-golfing.

## Definition

A fishy road is constructed with tiles, including the following ones:

```
v (go down)
> (go right)
^ (go up)
< (go left)
/ (mirror)
\ (mirror)

```

Any other character (except `-|+`) may be considered as a distraction, like some flowers (or fish heads) on the border of the road.

A road always start on the upper-left corner of a rectangular grid, delimited by `-|+`symbols. The road has an end if, by following it, you end up on a border, else, you'll be trapped in an infinite path.

Finding your way on the road is accomplished by following directions given by `v>^<`and mirrors. A mirror will reflect by 90° depending on where you came from. Here's how it works (using `v>^<`to show directions):

```
 ^    ^
>/<  >\<
 v    v
</>  <\>
 ^    ^

```

A road might be looking like this if it ends:

```
+--------------------+
|>\/  this way >\/>  | this one ends here
| v^            \/   |
| v^   ^.^           |
| \/\         >v     |
| /\/         ^<     |
+--------------------+

```

An infinite loop :

```
+--------+
|>>\ This|
|\\   is |
|  \\ a  |
| \ /trap|
+--------+

```

## Specifics

A road doesn't necessarily consist only of instructions. Spaces or letters can be used to complete it. This means you have to continue moving in the same direction except if you cross a character in `<v^>-|`.

There will always be one of `v>^<` in the upper-left corner, `<` or `^` implies this road ends.

You may submit a function taking a string as parameter, or a standalone program using STDIN/whatever is the closest alternative in your language.

Your submission must return or print on STDOUT truthy/falsy values when it's done. Truthy values meaning the road has an end, while falsy means it is an infinite loop.

## Test cases

```
+--------------------+
|>\/  this way >\/>  | this one ends here
| v^            \/   |
| v^   ^.^           |
| \/\         >v     |
| /\/ ><>     ^<     |
+--------------------+
    True

+--------+
|>>\ This|
|\\   is |
|  \\ a  |
| \ /trap|
+--------+
    False

+--+
|<v|
|^<|
+--+
    True

+--+
|>v|
|^<|
+--+
    False

+----------+
|v Hello \ |
|\\/\/   / |
| \/\\   \ |
|/  // >\  |
|  ^/\>\\/ |
|\  /\/\/  |
+----------+
    False

+-----+
|>\/\\|
|//\\/|
|\/\\\|
|//\//|
|\/\/ |
+-----+
    True

2 test cases added as suggested by @MartinBüttner
+----+
|v   |
|\\  |
|//\ |
|\\v |
| \/ |
+----+
    False

+----+
|v   |
|\\  |
|//\ |
|\\^ |
| \/ |
+----+
    False

Test case inspired by @ETHproductions
+-------------------------+
|><>                      |
|something smells fishy...|
+-------------------------+
    False

```

Standard loopholes are forbidden (as always).

The winner will be the one with the shortest code in bytes. (it would be amazing to see a \>\<\> answer :))

# Answer
> 4 votes
# JavaScript, ES6, ~~177~~ ~~161~~ 145 bytes

```
f=(s,i=1,M=[],D)=>D==5||!~M[O="indexOf"](D+i)&&f(s,i-[M.push(D+i),L=s[O]('|'),-L,1,-1][D=`431255${5-D+'X3412'[D]}`['><^v-|/\\'[O](s[i+L])]||D],M,D)

```

We can detect a cycle by traversing the path and detecting a repeat of the tuple

* location
* coming-from direction

That is, if we are entering some position `(x,y)` coming from some direction `D` for the second time, we know that this cycle will repeat forever. Therefore, the code keeps track of all locations that were visited, and from what direction, and checks against that record each time a new space is visited.

The directions up, down, left, and right are assigned the numbers `1`, `2`, `3`, and `4`. The code considers the current symbol being visited (`s[i+L]`) and changes the current direction (`D`), then the new direction is used to recursively call the function and evaluate the next space. `5` as a direction indicates a wall, and a `true` termination of the program.

Here is an explanation of less-golfed code:

```
f=
(s,     // input string
 i=1,   // current location as offset string index
 M=[],  // record of previously visited spaces
 D      // current direction
  )=>(
    L=s[O="indexOf"]('|'), // find arena width `L` by index of first `|`

    // if D is 5, return true, or...
    D==5 ||

    // if direction + position is not new, return false
    !~M[O](D+i) &&

    // otherwise, save this direction + position
    M.push(D+i) &&

    // recursively call `f` with new direction and position
    f(s,
      i-[,L,-L,1,-1][D=            // modify position based on active direction
        `431255${5-D+'X3412'[D]}`  // from these possible directions...
          [                        // chose the one at the index...
            '><^v-|/\\'[O](        // based on the index of the symbol
                           s[i+L]  // of the current character
                                 )
          ]
        ||D     // or preserve old D if symbol is not directional
      ],
      M,D)

```

The template string ``431255${5-D+'X3412'[D]}`` has a nested expression that handles the mirrors: because the directions are numbers, they can also be used as indexes. The expression `'X3412'[D]`, evaluates to the 8th character in the possible-direction string, and so corresponds to `\`, the 8th character in the symbol string `'><^v-|/\\'`). The expression says,

* If current direction `D` is `1` (up), then the new direction on hitting a `\` mirror will be `3` (left)
* If current direction `D` is `2` (down), then the new direction on hitting a `\` mirror will be `4` (right)
* etc.

The other mirror `/` would use the expression `'X4321'[D]`, but since that's simply an ordered count-down from `4`, we can express it more simply as `5-D`.

# Answer
> 6 votes
# Non-compliant \>\<\> answer

You wanted \>\<\>, I give you \>\<\> !

I believe the only sane way to do this in \>\<\> is by copying the input in the codespace and letting the interpreter decide by itself if the input leads somewhere. Since \>\<\> doesn't implement threading anymore, that leaves us with a big problem : if the input has a loop, we'll get stuck into it.

These considerations taken into account, I decided to make a solution compatible with \>\<\> online interpreter so that it would be possible to assert if the interpreter is stuck in the input or just taking ages to do everything. I also had to add trailing lines to the code so the online interpreter shows the added code and doesn't crash when trying to write to it.

Oh and since I'm clearly disqualified by now, I didn't bother with golfing the code.

Without further ado, the code in all its glory :

```
50i:0(?v   :"^"=?v:"v"=?v:">"=?v:"<"=?v:"/"=?v:"\"=?v:"|"=?v:"-"=?va=?v1+10.
>.!603f<         v"."~                                     <      <   >~1+010.
>.!01+1p}:$}:}v! <      <      <      <      <      <
  ;oooo"true" <<
              ^

```

To use it, copy it in the online interpreter, add enough trailing lines to handle your input, submit the code, give it the input as `;`-separated lines and enjoy the ride.

A few tests :

> With
>
> ```
> +--------------------+
> |>\/  this way >\/>  | this one ends here
> | v^            \/   |
> | v^   ^.^           |
> | \/\         >v     |
> | /\/         ^<     |
> +--------------------+`
>
> ```
>
> Final codespace :
>
> ```
> 50i:0(?v   :"^"=?v:"v"=?v:">"=?v:"<"=?v:"/"=?v:"\"=?v:"|"=?v:"-"=?va=?v1+10.
> >.!603f<         v"."~                                     <      <   >~1+010.
> >.!01+1p}:$}:}v! <      <      <      <      <      <
>   ;oooo"true" <<
>             ^
>  ....................
> .>\/           >\/>  .
> . v^            \/   .
> . v^   ^ ^           .
> . \/\         >v     .
> . /\/         ^<     .
>  ....................
>
> ```
>
> Outputs "true" and stops.

---

> With
>
> ```
> +--------+
> |>>\ This|
> |\\   is |
> |  \\ a  |
> | \ /trap|
> +--------+
>
> ```
>
> Final codespace :
>
> ```
> 50i:0(?v   :"^"=?v:"v"=?v:">"=?v:"<"=?v:"/"=?v:"\"=?v:"|"=?v:"-"=?va=?v1+10.
> >.!603f<         v"."~                                     <      <   >~1+010.
> >.!01+1p}:$}:}v! <      <      <      <      <      <
>   ;oooo"true" <<
>             ^
>  ........
> .>>\     .
> .\\      .
> .  \\    .
> . \ /    .
>  ........
>
> ```
>
> Loops forever.

---
Tags: code-golf, string, grid, decision-problem
---


title: Resolving the Date Format Dispute

text:
# Question
Title: Resolving the Date Format Dispute
The formatting order of dates is one of the most complex and divisive issues the world faces today. Some of us vehemently argue that Month/Day/Year is appropriate, considering that's how we say dates out loud. Others loudly proclaim that Day/Month/Year is best, because it puts the terms in ascending order of the duration they represent.

Enough is enough. Computers can resolve this dispute simply and fairly. Your code, a complete function or program, will take a date string delimited by slashes, e.g. `12/1/2015`. Note this is the exact format, without leading zeroes and with a four-digit year at the end.

* If it's *definitely* Month/Day/Year, e.g. `10/31/1998`, output a text representation of that date in this exact format, with the full month name, day, and year: `October 31, 1998`
* If it's *definitely* Day/Month/Year, e.g. `25/12/1989`, output the same sort of text representation: `December 25, 1989`.
* If it's ambiguous whether it's Month/Day/Year or Day/Month/Year, output a date that resolves the ambiguity by combining the two possible dates as follows:
    1. Create a new month name by taking the first half of the name of the **earlier** month and append the second half of the **later** month. For months with odd length, the first half gets the extra letter. To be explicit, the first halves of the months are `Janu`, `Febr`, `Mar`, `Apr`, `Ma`, `Ju`, `Ju`, `Aug`, `Septe`, `Octo`, `Nove`, and `Dece` and the second halves are therefore `ary`, `uary`, `ch`, `il`, `y`, `ne`, `ly`, `ust`, `mber`, `ber`, `mber`, and `mber`.
    2. Calculate the day by averaging the two possible days, taking the floor when the average is not an integer.
    3. Output the text representation of this date, e.g. for `10/8/2011`, output `Augber 9, 2011`.

If the input date cannot be Month/Day/Year or Day/Month/Year (e.g. `13/13/2013` or even `2/30/2002`), any behavior is acceptable. This code golf, shortest code wins!

**Test cases:**

`10/31/1998` gives `October 31, 1998`

`25/12/1989` gives `December 25, 1989`

`10/8/2011` gives `Augber 9, 2011`

`8/5/1957` gives `Maust 6, 1957`

`9/12/2012` (oddly enough) gives `September 10, 2012`

`1/1/2000` gives `January 1, 2000`

# Answer
> 1 votes
# Pyth - 156 bytes

Really bad code, and will need to use packed strings, but its something.

```
Kc"January February March April May June July August September October November December"dJhM.g>k12=GsMcz\/?<eJ32++@KthJdtP`,eJeGss[@VCcL2KStMPGdPt`,s.OPGeG

```

Test Suite.

# Answer
> 3 votes
# Mathematica ~~341 304 298 288~~ 293 bytes

This uses a pure or anonymous function, that is, a function without its own name.

`DateString` returns an error message if the date is ambiguous. `Check`catches the ambiguity and sends the offending date to `DateList`, which transforms it into list of 3 integers (which it believes to be `{year, month, day}`). The month and day integers are sorted by size and used to determine the month and day as per the OP's instructions.

`Quiet` silences error printing.

```
t=StringSplit;v=ToString;x=t[#,"-"]&/@t["Janu-ary Febr-uary Mar-ch Apr-il Ma-y Ju-ne Ju-ly Aug-ust Septe-mber Octo-ber Nove-mber Dece-mber"];
Quiet@Check[#~DateString~{"MonthName"," ","DayShort",", ","Year"},
{m,n,o}=DateList@#;{p,q}=Sort@d[[2;;3]];x[[p,1]]<>x[[q,2]]<>" "<>v@Floor@Mean@{n,o}<>", "<>v@d[[1]]]&

```

---

```
t=StringSplit;v=ToString;x=t[#,"-"]&/@t["Janu-ary Febr-uary Mar-ch Apr-il Ma-y Ju-ne Ju-ly Aug-ust Septe-mber Octo-ber Nove-mber Dece-mber"];
Quiet@Check[#~DateString~{"MonthName"," ","DayShort",", ","Year"},
{m,n,o}=DateList@#;{p,q}=Sort@d[[2;;3]];x[[p,1]]<>x[[q,2]]<>" "<>v@Floor@Mean@{n,o}<>", "<>v@d[[1]]]& /@
{"10/31/1998","25/12/1989", "10/8/2011", "8/5/1957", "9/12/2012", "1/1/2012"}

```

> {"October 31, 1998", "December 25, 1989", "Augber 9, 2011", "Maust 6, 1957", "September 10, 2012", "January 1, 2012"}

# Answer
> 3 votes
# Javascript (ES6), ~~311~~ ~~295~~ ~~282~~ ~~274~~ ~~246~~ 238 bytes

```
a=>(a=a.split`/`,b=c=>e(c).length+1>>1,d=' ',e=f=>new Date(99,a[+f]-1).toLocaleString('en',{month:'long'}),g=+a[0],h=+a[1],i=g>h,j=g>12,k=h>12,(j&&!k?e(1)+d+g:k&&!j?e(0)+d+h:e(i).slice(0,b(i))+e(1-i).slice(b(1-i))+d+((g+h)>>1))+', '+a[2])

```

**Edit:** Uses `toLocaleString` to generate month names. Change the locale to get results using month names in different locales!

**Edit 2:** Now generates two month names instead of all 12!

Ungolfed:

```
func = inp => (
    inp = inp.split `/`,
    get = arg => months(arg).length + 1 >> 1,
    space = ' ',
    months = key => new Date(99, inp[+key] - 1).toLocaleString('en', { month: 'long' }),
    tmp1 = +inp[0],
    tmp2 = +inp[1],
    first = tmp1 > tmp2,
    t1greater = tmp1 > 12,
    t2greater = tmp2 > 12,
    (t1greater && !t2greater ?
        months(1) + space + tmp1
    :
        t2greater && !t1greater ?
            months(0) + space + tmp2
        :
            months(first).slice(0, get(first)) + months(1 - first).slice(get(1 - first)) + space + ((tmp1 + tmp2) >> 1)
    )
    + ', ' + inp[2]
)

```

Example:

```
console.log(
    func('10/31/1998') + '\n' +
    func('25/12/1989') + '\n' +
    func('10/8/2011') + '\n' +
    func('8/5/1957') + '\n' +
    func('9/12/2012') + '\n' +
    func('1/1/2000')
);

```

*Thanks to:
@user81655, 274 =\> 246 bytes
@edc65, 246 =\> 238 bytes*

# Answer
> 2 votes
# JavaScript ES6, 204

```
x=>(s=x=>x.split`/`,[a,b,y]=s(x).sort((a,b)=>a-b),(c=b)>12?c=a:b=a- -b>>1,s('/Janu/Febr/Mar/Apr/Ma/Ju/Ju/Aug/Septe/Octo/Nove/Dece')[a]+s('/ary/uary/ch/il/y/ne/ly/ust/mber/ber/mber/mber')[c]+` ${b}, `+y)

```

Test snippet:

```
F=x=>(
  s=x=>x.split`/`,
  [a,b,y]=s(x).sort((a,b)=>a-b),
  (c=b)>12?c=a:b=a- -b>>1,
  s('/Janu/Febr/Mar/Apr/Ma/Ju/Ju/Aug/Septe/Octo/Nove/Dece')[a]
  +s('/ary/uary/ch/il/y/ne/ly/ust/mber/ber/mber/mber')[c]+` ${b}, `+y
)

console.log=x=>O.innerHTML+=x+'\n'

;['10/31/1998','25/12/1989','10/8/2011','8/5/1957','9/12/2012','1/1/2000']
.forEach(x=>console.log(x+' -> '+F(x)))
```

```
<pre id=O></pre>
```

# Answer
> 2 votes
# Python 3 (290 bytes)

Similar to Ashwin Gupta's answer, but taking advantage of Python's calendar module to avoid writing out all of the month names.

```
import calendar as C
M,I,P,S,L,A=C.month_name,int,print," ",len,", "
def d(i):
 w=i.split("/")
 f,s,y=I(w[0]),I(w[1]),w[2]
 if(f>12):P(M[s]+S+w[0]+A+y)
 elif(s>12):P(M[f]+S+w[1]+A+y)
 else:l,h=min(f,s),max(f,s);P(M[l][:I(L(M[l])/2+.5)]+M[h][I(L(M[h])/2+.5):]+S+str(I((f+s)/2))+A+y)

```

Python 2 should trim a few bytes with integer division and losing the parentheses for `print`.

# Answer
> 1 votes
## Python, ~~558~~ 554 bytes

A really, really, really horribly golfed example of how to do this in python. Sorry, I'm super bad at this golfing stuff `D:` . It works though. I'm sure there are plenty of ways to simplify this so let me know in the comments. **Golfed:**

```
import math
def d(i):
 l=["","January","February","March","April","May","June","July","August","September","October","November","December"]
 w=i.split('/')
 f=int(w[0])
 s=int(w[1])
 S=" "
 y=w[2]
 if(f>12):
  e=int(w[1])
  print(l[e]+S+w[0]+", "+y)
  elif(f<=12 and s>12):
   e=int(w[0])
   print(l[e]+S+w[0]+", "+y)
   else:
    if(f<s):
     o=l[f]
     t=l[s]
    else:
     o=l[s]
     t=l[f]
    o=o[0:int(math.ceil(len(o)/2))]
    t=t[int(math.ceil(len(t)/2)):len(t)]
    print(o+t+S +  str(math.floor((f + s)/2)) + ", " + y)

```

***Ungolfed***

```
import math
def d(i):
    l = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    w = i.split('/')
    f = int(w[0])
    s = int(w[1])
    y = w[2]
    if(f > 12):
        e = int(w[1])
        print(l[e] + " " + w[0] + ", " + y)

    elif(f <= 12 and s > 12):
         e = int(w[0])
         print(l[e] + " " + w[0] + ", " + y)
    else:
         if(f < s):
            o=l[f]
            t=l[s]
         else:
            o=l[s]
            t=l[f]
         o = o[0:int(math.ceil(len(o)/2))]
         t = t[int(math.ceil(len(t)/2)):len(t)]
         print(o+t+" " +  str(math.floor((f + s)/2)) + ", " + y)

```

Screenshot:

# Answer
> 0 votes
## PHP, ~~301~~ 294 bytes

```
function r($t){$e='return date("F",mktime(0,0,0,$o));';list($a,$b,$c)=explode('/',$t);$o=min($a,$b);$m=eval($e);$o=max($a,$b);$n=eval($e);echo(($a|$b)<13)?substr($m,0,ceil(strlen($m)/2)).substr($n,ceil(strlen($n)/2))." ".floor(($a+$b)/2).", $c":date("F j, Y",strtotime(($a>12)?"$b/$a/$c":$t));}

```

I thought I could compete with the Javascript answer. Oh well.

I think I could make it smaller and I don't like the code I used for the ambiguous dates. I think there is a better way to do it.

Ungolfed:

```
function r($t){
    // Eval'd code to reduce char count
    $e='return date("F",mktime(0,0,0,$o));';

    // Split the date
    list($a,$b,$c)=explode('/',$t);

    // Get the earliest month
    $o=min($a,$b);
    $m=eval($e);

    // Get the latest month
    $o=max($a,$b);
    $n=eval($e);

    // If ambiguous
    if ($a<13 && $b<13) {
        print substr($m,0,ceil(strlen($m)/2)).substr($n,ceil(strlen($n)/2))." ".floor(($a+$b)/2).", $c";
    }
    else {
        print date("F j, Y",strtotime(($a>12)?"$b/$a/$c":$t));
    }
}

```

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


title: Interpret StackyMath!

text:
# Question
Title: Interpret StackyMath!
*Time for you to implement my new stack based language! It's called StackyMath. This will be a stack based language with 8 operations on the stack and ways to add numbers to the stack.*

### List of operations:

* `/`: Division. Performed on the top 2 numbers of the stack. Pushes the result back on the stack.
* `*`: Multiplication. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
* `-`: Subtraction. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
* `+`: Addition. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
* `^`: Exponentiation. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
* `%`: Modulo. Performed on the top 2 numbers of the stack. Pushes the result back on the stack
* `!`: Factorial. Performed on the top number on the stack. Pushes the result back on the stack
* `D`: Duplicate the top number on the stack

### Operations defined in pseudo code:

* `/`: `push(pop divided by pop)`
* `*`: `push(pop times pop)`
* `-`: `push(pop minus pop)`
* `+`: `push(pop plus pop)`
* `^`: `push(pop to the pop)`
* `%`: `push(pop mod pop)`
* `!`: `push(factorial pop)`
* `D`: `t = pop; push(t); push(t)`

### How to push numbers to the stack:

Adding numbers to the stack is easy, just put the raw number in your program where you need it. If you need to put multiple numbers on the stack you can separate them with a comma (`,`). Your program will not need to process `-` numbers in the input, If the user wants one they should push the number they want negated, zero, and `-`. Numbers in the input of the program are also constrained to positive integers.

### Input:

Your program should take the input on the command line, or from std in. Input will only consist of numbers (no scientific notation or decimals) delimited by `,` as needed, and the operations defined above.

### Output:

Your program should print the number on the top of the stack.

Error cases:

* If the program tries to over-pop the stack, you should print `StackUnderflowException!!!` .
* If you have division by zero, print `DivisionByZeroException!!!`
* If a number that exceeds 64-bits, either while executing the program or processing a number in the input, print `NumberOverflowException!!!`
* If somehow you get a negative number on the top of the stack and you need to do a factorial, print `NegativeFactorialException!!!`
* If you have a floating point number on the tops of the stack and the next operation is factorial, print `FloatingFactorialException!!!`
* If no numbers are on the stack when the program exits (i.e. the program was empty) print `EmptyProgram!!!`

### Notes:

* All error output to should got yo std err or closest equivalent.
* All numbers are constrained to 64-bit floating point.

Example programs:

```
50,47*                 -> 2350
50,47/                 -> 0.94
100,8!                 -> 40320
100D*                  -> 10000
!                      -> StackUnderflowException!!!
5,2/!                  -> FloatingFactorialException!!!
4,3!2*/                -> 3
654,489,48,43/5*7D+-*% -> 77.68749999999909
                       -> EmptyProgram!!!

```

(I can add more if needed)

# Answer
# Ruby, ~~412~~ ~~410~~ ~~404~~ ~~392~~ ~~380~~ 377 characters

```
def e m,x='Exception';warn m+x+?!*3;exit;end
def o;e'StackUnderflow'if$*==[];$*.pop;end
u=->n{e'DivisionByZero'if n.infinite?;e'NumberOverflow'if n>2**64;$*<<n}
f=->n{e'NegativeFactorial'if n<0;e'FloatingFactorial'if n.to_i<n;n<2?1:f[n-1]*n}
gets.gsub(/(\d+)|([+*\/%^-])|(!)|D/){$1?u[$1.to_f]:$2?u[eval"o#{$2>?A?:**:$2}o"]:$3?u[f[o]]:u[x=o]+u[x]}
e'EmptyProgram',''if$*==[]
p o

```

This is regular precision version using `Float`. The result precision is as in the sample code, but numeric overflow detection is not exact.

Sample run:

```
bash-4.3$ ruby StackyMath.rb <<< '654,489,48,43/5*7D+-*%'
77.68749999999909

```

## Ruby, ~~378~~ 377 characters

```
def e m,x='Exception';warn m+x+?!*3;exit;end
def o;e'StackUnderflow'if$*==[];$*.pop;end
u=->n{e'NumberOverflow'if n>2**64;$*<<n}
f=->n{e'NegativeFactorial'if n<0;e'FloatingFactorial'if n.to_i<n;n<2?1:f[n-1]*n}
gets.gsub(/(\d+)|([+*\/%^-])|(!)|D/){$1?u[Rational$1]:$2?u[eval"o#{$2>?A?:**:$2}o"]:$3?u[f[o]]:u[x=o]+u[x]}rescue e'DivisionByZero'
e'EmptyProgram',''if$*==[]
p o.to_f

```

This is high precision version using `Rational`. The result precision is not always the same as in the sample code, but numeric overflow detection is exact.

Sample run:

```
bash-4.3$ ruby StackyMath-hi.rb <<< '654,489,48,43/5*7D+-*%'
77.6875

```
> 5 votes

# Answer
# JavaScript (ES6), 430 bytes

422 bytes with ES7 by changing `Math.pow(2,2)` to `2**2`

```
e=m=>{throw alert(m)};u=prompt();u?alert(eval('u.match(/\\d+|[^,]/g).map(o=>s.push(t=o=="/"?(b=p(a=2))?a/b:e`DivisionByZero43*"?2*23-"?2-23+"?2+23%"?2%23^"?Math.pow(2,2)3D"?s.push(r=2)&&r3!"?eval("for(r=i=2;i<0?e`Negative54:i%1?e`Floating54:--i;)r*=i;r"):+o)&&t==Infinity&&e`NumberOverflow4,s=[],p=_=>s.length?s.pop():e`StackUnderflow4);t'.replace(/[2-5]/g,x=>[,,'p()',':o=="','Exception!!!`','Factorial'][x]))):e`EmptyProgram!!!`

```

## Explanation

Uses `eval` to replace certain common phrases. Ungolfed and without the `eval` it looks like this:

```
e=m=>{throw alert(m)};                           // e = throw error, alert displays
                                                 //     message, throw stops execution
u=prompt();                                      // u = received input
u?alert(                                         // display the result
  u.match(/\d+|[^,]/g)                           // get array of numbers and operators
    .map(o=>                                     // iterate over operators
      s.push(t=                                  // t = last pushed value

        // Execute operator
        o=="/"?(b=p(a=p()))?a/b:                 // make sure argument B is not 0
          e`DivisionByZeroException!!!`:
        o=="*"?p()*p():
        o=="-"?p()-p():
        o=="+"?p()+p():
        o=="%"?p()%p():
        o=="^"?Math.pow(p(),p()):
        o=="D"?s.push(r=p())&&r:
        o=="!"?eval("                            // eval to enable for loop in ternary
          for(                                   // no factorial in JS so do this manually
            r=i=p();
            i<0?e`NegativeFactorialException!!!` // check for errors
              :i%1?
                e`FloatingFactorialException!!!`
                :--i;
          )
            r*=i;
          r"):                                   // return r
        +o                                       // if not an operator cast as a number
      )&&t==Infinity&&                           // JS turns anything over 64 bit float
        e`NumberOverflowException!!!`,           //     max value into Infinity
      s=[],                                      // s = stack array
      p=_=>s.length?s.pop():                     // p = check stack then pop
        e`StackUnderflowException!!!`
    )&&t                                         // return top stack element
  ):e`EmptyProgram!!!`                           // error if input length is 0

```
> 4 votes

# Answer
# Groovy, 718 bytes. *Fore!*

May as well post my impl golfed. Meet my big wall of code:

```
g='Exception!!!'
a={System.err.print(it);System.exit(1)}
b=new Stack()
c={b.push(it)}
v=2d**64d
d={b.pop()}
e={if(b.size()<it)a('StackUnderflow'+g)}
f={a('NumberOverflow'+g)}
h={e(2)
c(Eval.xy(d(),d(),"x$it y"))
if(b.peek()>v)f()}
k={i->if(i<0)a('NegativeFactorial'+g)
if(Math.abs(i-(i as long))>1E-6)a('FloatingFactorial'+g)
(2..i).inject{x,y->(v/x<y)?f():x*y}}
l=['/':{e(2)
m=d()
n=d()
if(n==0)a('DivisionByZero'+g)
c(m/n)},'!':{e(1)
c(k(d()))},'D':{e(1)
c(b.peek())}]
System.in.newReader().readLine().findAll(~/\d+|[^,]/).each{x->if(x.matches(/\d+/))try{c(x as double)}catch(Exception e){f()}
else if("+-*%^".contains(x))h(x.replace('^','**'))
else l[x]()}
if(b){o=d()
if(Double.isInfinite(o))f()
println o}else a('EmptyProgram!!!')

```

Ungolfed:

```
error = {System.err.print(it);System.exit(1)}

stack = new Stack()
maxVal = 2d**64d

push = {stack.push(it)}
pop = {stack.pop()}

checkAtLeast = {if (stack.size() < it) error('StackUnderflow'+exception)}
numberOverflow = {error('NumberOverflow'+exception)}

exception = 'Exception!!!'

def dArgOp(i) {
    checkAtLeast(2)
    push(Eval.xy(pop(), pop(), "x$i y"))
    if(stack.peek() > maxVal) numberOverflow
}

factorial = {i->
    if (i < 0)
        error('NegativeFactorial'+exception)
    if (Math.abs(i - (i as long)) > 1E-6)
        error('FloatingFactorial'+exception)
    (2..i).inject {acc, it ->
        (maxVal/acc < it)?numberOverflow():acc*it
    }
}

ops = [
'/' : {
    checkAtLeast(2)
    first = pop()
    second = pop()
    if (second == 0)
        error('DivisionByZero'+exception)
    push(first / second)
},
'!' : {
    checkAtLeast(1)
    push(factorial(pop()))
},
'D' : {
    checkAtLeast(1)
    push(stack.peek())
}]

input = System.in.newReader().readLine()
tokens = input.findAll(~/\d+|[^,]/)

tokens.each {
    print "current token: $it  \t stack before eval: $stack "
    if (it.matches(/\d+/))
        try {
            push(it as double)
        } catch (Exception e) {
            numberOverflow()
        }

    else if ("+-*%^".contains(it))
        dArgOp(it.replace('^','**'))
    else
        ops[it]()
    println "result: ${stack.peek()}"
}

if (stack) {
    top = pop()
    if (Double.isInfinite(top))
        numberOverflow()
    println top
} else
    error('EmptyProgram!!!')

```

Edit 1: save ~15 bytes thanks to @Doorknob
Edit 2: drop ~130 bytes with a few more tricks
> 1 votes

# Answer
# Candy, ~~298~~ ~~348~~ 392 bytes

Although Candy is stack based, I'm not sure that really helped...

```
&{|"EmptyProgram!!!\n"(;).}(=bYZay0=zx4k"!%*+,-/D^"(iYe{Z=x})aYb=z=ya=X{Y{cZ0=yza}b212202221(i=ZXe{y})a0=zcY0j{XjZ{|D1b#64R(=c2*)c>{b"NumberOverFlow"(;)i}}|i}aZ{(=)"Exception!!!\n"(;).}0=yz|A#48-Z#10*+=z1=y})c?(=).@0&<{1|b"StackUnderflow"(;)c0}.@1~ALe{A0<{b"Negative"(;)i|1bAR(=cA*)}|b"Floating"(;)i}Z{b"Factorial"(;)}.@2W%.@3*.@4+@5.@6W-.@7WD{/|b"DivisionByZero"(;)i}.@8~A.@9=xK=y=1bA_(cX*).

```

Formatted a bit reveals a bit of structure:

```
&{|"EmptyProgram!!!\n"(;).}
(=bYZay0=zx4k
  "!%*+,-/D^"
  (iYe{Z=x})
  aYb=z=ya=X
  {
    Y{cZ0=yza}b
    212202221(i=ZXe{y})
    a0=zcY0j
    {XjZ{|D1b#64R(=c2*)c>{b"NumberOverFlow"(;)i}}|i}
    aZ{(=)"Exception!!!\n"(;).}
    0=yz|A#48-Z#10*+=z1=y
  }
)c?(=).
@0&<{1|b"StackUnderflow"(;)c0}.
@1~ALe{A0<{b"Negative"(;)i|1bAR(=cA*)}|b"Floating"(;)i}Z{"Factorial"(;)}.
@2W%.@3*.@4+@5.@6W-.@7WD{/|"DivisionByZero"(;)i}.@8~A.@9=xK=y=1bA_(cX*).

```

The actual math occurs on the last two lines. It's driven there by a jump table on the third line.
> 1 votes

---
Tags: code-golf, math, interpreter, stack
---


title: Euchre bots (card game)

text:
# Question
Title: Euchre bots (card game)
The idea of this challenge is simple: create a bot to play the card game Euchre.

For those of you who don't already know them, I've written out the rules to Euchre here as they pertain to this challenge.

I recommend using python or something similar, but the only real restriction is that it has to be compatible with the controller code

### Input:

Your euchre bot will get different kinds of input depending on the current phase of the game or round. Generally speaking, you'll get the game phase on the first line followed by a comma and a the number of points your team has, and then the relevant data on the following lines.

Chronologically, your bot will get input in the following order:

```
Ordering Trump:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    ordering        // the phase of the game
    th              // the turned up card
    p,p             // each previous player’s decision

Naming Trump:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    naming          // the phase of the game
    p               // each previous player’s decision

Dealer Discarding:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    discard         // the phase of the game
    th              // the card you will pick up

Going alone:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    alone           // the phase of the game
    h               // the trump suit
    n,n             // each previous player’s decision

Your turn:
    js,ah,qc,ts,jc  // the cards in your hand
    2               // number of points your team has
    0               // number of tricks your team has taken
    turn            // the phase of the game
    h               // the trump suit
    td,8h,p         // each previous player’s card

Trick data:
                    // the cards in your hand (none, since this happens at the end of a trick)
    2               // number of points your team has
    1               // number of tricks your team has taken
    trick           // the phase of the game
    0               // the index of the following list that is your card
    js,tc,4d,js     // the cards played during the trick in the order they were played

```

### Output:

Your euchre bot will have different outputs depending on the current phase of the game or round.

```
Ordering Trump:
    p   //for pass
    OR
    o   //for order up

Naming Trump:
    p           //for pass
    OR ANY OF
    c,s,h,d     //the suit you want to name

Going alone:
    n   // no
    OR
    y   // yes

Your turn:
    js  //the card you want to play

```

### Scoring:

Your bot's score is the total number of games it wins.

Your bot will play against every other bot, and it will always be partnered with a copy of itself.

### Notes:

Here's a simple template in python2.7:

```
#!/usr/bin/python2.7
import sys

data = sys.stdin.readlines()

hand = data[0].strip().split(',')   # Hand as a list of strings
points = int(data[1])       # Number of points
tricks = int(data[2])       # Number of tricks

out = ''

if data[3] == 'ordering':
    card = data[4]              # The upturn card
    prev = data[5].strip().split(',')   # The previous player's decisions as a list
    # Ordering logic
    out =       # 'o' or 'p'
elif data[3] == 'naming':
    prev = data[4].strip().split(',')   # The previous player's decisions as a list
    # Naming logic
    out =       # 'p', 'h', 's', 'c', or 'd'
elif data[3] == 'discard':
    card = data[4]              # The card you'll take
    # Discarding logic
    out =       # The card you want to discard
elif data[3] == 'alone':
    trump = data[4]             # The trump suit
    prev = data[5].strip().split(',')   # The previous player's decisions as a list
    # Alone logic
    out =       # 'y' for yes, 'n' for no
elif data[3] == 'turn':
    trump = data[4]             # The trump suit
    prev = data[5].strip().split(',')
    # Turn logic
    out =       # The card you want to play
elif data[3] == 'trick':
    trump = data[5]
    cards = data[6].strip().split(',')
    my_card = cards[int(data[4])]
    # Data logic

print(out)

```
1. There will always be 4 total responses. If someone goes alone, then their partner's response will be "p" on their turn.
2. I tried to shave down the amount of redundant input, so to be extra clear:

2a. Both your position relative to the dealer/leader and the card your partner played can be determined by the number of previous outputs. There is 1 player between you and your partner. There For instance, if you get "td,8h,p" as the last line on your turn, you can see that your partner played an 8h, and the other team has a player that is going alone.
3. If you are curious, the deal is done in the traditional way (in two rounds alternating packets of 2 and 3 cards) but that's not really relevant to your bot, so...
4. If the second player decides to order up in the trump phase, that phase will continue, but their outputs will pretty much be ignored. In other words, whoever orders up first is on the Namers team regardless of any other output.
5. The following are the defaults for the various game phases. If you don't output a valid response for that round, then your response is changed to what's below.

Ordering Trump: p

Naming Trump: p

Discarding: (the first card in your hand)

Going Alone: n

Your Turn: (the first legal card in your hand)
6. Here's the controller code for your testing purposes.

6a. Notice you can pass in either 2 or 4 bot names, if you give it 4 bots then they get partnered up randomly, and with 2 they are partnered up with copies of themselves.

6b. You need a 'bots' directory in the same directory as the controller code, and your bot code needs to be in the bots directory.
7. For those that want their bot to remember what cards were played, you are given the opportunity during the "trick" phase, which tells your bot which cards were played. You can write to a file in the bots directory as long as that file doesn't exceed 1kb.

### Scoreboard:

```
Old Stager:  2
Marius:      1
Random 8020: 0

```

# Answer
> 2 votes
# Marius

I wrote that bot in R. I did some tests with your controller and they seem to communicate correctly.

```
#!/usr/bin/Rscript
options(warn=-1)
infile = file("stdin")
open(infile)
input = readLines(infile,5)
hand = strsplit(input[1],",")[[1]]
phase = input[4]
if(!phase%in%c("discard","naming")) input = c(input,readLines(infile,1))
other_o = c("a","k","q","j","t","9")
alone = "n"
ord = "p"
trumpify = function(color){
    tr_suit = switch(color,
            "c" = c("c","s",rep("c",5)),
            "s" = c("s","c",rep("s",5)),
            "h" = c("h","d",rep("h",5)),
            "d" = c("d","h",rep("d",5)))
    paste(c("j","j","a","k","q","t","9"),tr_suit,sep="")
    }

if(phase%in%c("ordering","alone")){
    flip = input[5]
    if(phase=="ordering") trump = trumpify(substr(flip,2,2))
    if(phase=="alone") trump = trumpify(flip)
    hand_value = sum((7:1)[trump%in%c(hand,flip)])
    if(hand_value>13) ord = "o"
    if(hand_value>18) alone = "y"
    if(phase=="alone") cat(alone)
    if(phase=="ordering") cat(ord)
    }

if(phase=="naming"){
    name = "p"
    colors = unique(substr(hand,2,2))
    col_values = sapply(colors,function(x)sum((7:1)[trumpify(x)%in%hand]))
    if(any(col_values>13)){name = colors[which.max(col_values)]}
    cat(name)
    }

if(phase=="discard"){
    flip = input[5]
    new_hand = c(hand,flip)
    trump = trumpify(substr(flip,2,2))
    discardables = new_hand[!new_hand%in%trump]
    if(length(discardables)){
        val = sapply(substr(discardables,1,1),function(x)(6:1)[other_o==x])
        d = discardables[which.min(val)]
    }else{d = tail(trump[trump%in%new_hand],1)}
    cat(d)
    }

if(phase=="turn"){
    trump = trumpify(input[5])
    fold = strsplit(gsub("[[:punct:]]","",input[6]),",")[[1]]
    if(length(fold)&!any(is.na(fold))){
        fold_c = substr(fold[1],2,2)
        f_suit = if(fold_c!=input[5]){paste(other_o,fold_c,sep="")}else{trump}
        l = length(f_suit)
        current = (l:1)[f_suit%in%fold]
        if(any(hand%in%f_suit)){
            playable = hand[hand%in%f_suit]
            val = sapply(playable,function(x)(l:1)[f_suit==x])
            if(all(max(val)>current)){
                play = playable[which.max(val)]
            }else{play = playable[which.min(val)]}
        }else if(any(hand%in%trump)){
            playable = hand[hand%in%trump]
            val = sapply(playable,function(x)(7:1)[trump==x])
            if(!any(fold%in%trump)){
                play = playable[which.min(val)]
            }else{
                trumped = fold[fold%in%trump]
                val_o = max((7:1)[trump%in%trumped])
                play = ifelse(any(val>val_o), playable[which.min(val[val>val_o])], playable[which.min(val)])
            }
        }else{
            val = sapply(substr(hand,1,1),function(x)(6:1)[other_o==x])
            play = hand[which.min(val)]
            }
    }else{
        col = c("c","s","h","d")
        non_tr = col[col!=input[5]]
        aces = paste("a",non_tr,sep="")
        if(any(hand%in%aces)){
            play = hand[hand%in%aces][1]
        }else if(any(hand%in%trump)){
            playable = hand[hand%in%trump]
            val = sapply(playable,function(x)(7:1)[trump==x])
            play = playable[which.max(val)]
        }else{
            val = sapply(substr(hand,1,1),function(x)(6:1)[other_o==x])
            play = hand[which.max(val)]
        }
    }
    cat(play)
}

```

I'll probably modify it later since I didn't implement a "turn" logic for when the bot is defending, but I'm posting it now so that people have another bot to test against.

For now, it only implements very basic strategies such as leading with an ace, a trump or any other high card; following with a higher card when possible or playing the lowest valued card if not; ordering when hand has high value and naming the color in which the hand would have had the highest value; going alone when hand has very high value. The "value" of each card is computed very simply: value of trumps starts from 7 for the first jack and decreases along the trump suit.

# Answer
> 1 votes
# Old Stager

This bot follows some simple rules which served him well for a long time:

* Intuitively assign a score to each card
* Choose the trump if the hand score is good enough
* In case of a really good hand play alone
* Choose best card when playing first
* Choose a better card than the opponents if they are winning
* Choose worst card if the partner is winning or if winning is not possible

I increased the target score from 10 to 100 for testing in the controller. The results are still very random, but way more stable than before.

```
#!/usr/bin/python2.7
from __future__ import print_function
import sys, re, math

base = 1.2
playThreshold = 27.0
aloneThreshold = 36.0
sameColor = { 'd' : 'h', 'h' : 'd', 's' : 'c', 'c' : 's' , '' : '', 'n' : 'n' }
cardValue = { 'p' : 0, '9' : 1, 't' : 2, 'j' : 3, 'q' : 4, 'k' : 5, 'a' : 6 }

class Card(object):
    def __init__(self, name, trump):
        self.name = name
        self.value = cardValue[name[0:1]]
        self.suit = name[1:2]
        self.trump = False
        self.updateScore(trump)
    def updateScore(self, trump):
        self.score = self.value
        if self.suit == trump:
            self.trump = True
            self.score += 6
        if self.value == 3:
            if self.suit == trump:
                self.score = 14
            if self.suit == sameColor[trump]:
                self.trump = True
                self.score = 13

class Cards(object):
    def __init__(self, cards, trump):
        self.list = []
        self.score = 0.0
        if cards:
            for c in cards.split(','):
                self.append(Card(c, trump))
    def append(self, card):
        self.list.append(card)
        self.score += math.pow(base, card.score)
    def updateScore(self, trump):
        self.score = 0.0
        for card in self.list:
            card.updateScore(trump)
            self.score += math.pow(base, card.score)
    def best(self):
        card = self.list[0]
        for i in self.list[1:]:
            if i.score > card.score:
                card = i
        return card
    def worst(self):
        card = self.list[0]
        for i in self.list[1:]:
            if i.score < card.score:
                card = i
        return card
    def better(self, ref):
        card = None
        for i in self.list:
            if i.score > ref.score and (card is None or i.score < card.score):
                card = i
        return card

def ordering(hand, card, decisions):
    if len(decisions) == 3:
        hand.append(card)
    return 'o' if hand.score > playThreshold else 'p'

def naming(hand):
    result = 'p'
    score = playThreshold
    for trump in ['d', 'h', 's', 'c']:
        hand.updateScore(trump)
        if hand.score > score:
            result = trump
            score = hand.score
    return result

def turn(hand, decisions):
    bestIndex = -1
    for i, d in enumerate(decisions.list):
        if d.suit:
            bestIndex = i
            break
    if bestIndex == -1:
        return hand.best()
    else:
        suit = decisions.list[bestIndex].suit
        for i in range(2, len(decisions.list)):
            if (decisions.list[i].suit == suit or decisions.list[i].trump) and decisions.list[i].score > decisions.list[bestIndex].score:
                bestIndex = i
        matching = Cards('', '')
        for card in hand.list:
            if card.suit == suit:
                matching.append(card)
        if not matching.list:
            if bestIndex == len(decisions.list) - 2:
                return hand.worst()
            for card in hand.list:
                if card.trump:
                    matching.append(card)
            if not matching.list:
                return hand.worst()
        if bestIndex == len(decisions.list) - 2:
            return matching.worst()
        card = matching.better(decisions.list[bestIndex])
        if card:
            return card
        return matching.worst()

output = ''
input = re.split('\n', re.sub(r'[^a-z0-9,\n]+', '', sys.stdin.read()))

if input[3] == 'ordering':
    output = ordering(Cards(input[0], input[4][1:2]), Card(input[4], input[4][1:2]), input[5].split(','))
elif input[3] == 'naming':
    output = naming(Cards(input[0], 'n'))
elif input[3] == 'discard':
    output = Cards(input[0], input[4][1:2]).worst().name
elif input[3] == 'alone':
    output = 'y' if Cards(input[0], input[4]).score > aloneThreshold else 'n'
elif input[3] == 'turn':
    output = turn(Cards(input[0], input[4]), Cards(input[5], input[4])).name

print(output)

```

# Answer
> 0 votes
# Random 8020

A simple random bot, which will pass 80% of the time. Uncomment the last line to see the (cleared up) input and output.

```
#!/usr/bin/python2.7
from __future__ import print_function
import sys, re, random

output = ''
input = re.split('\n', re.sub(r'[^a-z0-9,\n]+', '', sys.stdin.read()))
hand = input[0].split(',')

if input[3] == 'ordering':
    output = random.choice(['p', 'p', 'p', 'p', 'o'])
elif input[3] == 'naming':
    output = random.choice(['p', 'p', 'p', 'p', random.choice(hand)[1:2]])
elif input[3] == 'discard':
    output = random.choice(hand)
elif input[3] == 'alone':
    output = random.choice(['n', 'n', 'n', 'n', 'y'])
elif input[3] == 'turn':
    output =  random.choice(hand)
    if input[5]:
        suited = filter(lambda x: input[5][1:2] in x, hand)
        if suited:
            output = random.choice(suited)

print(output)
#print(input, " --> ", output, file=sys.stderr)

```

---
Tags: king-of-the-hill, card-games
---


title: The FizzBuzz-ish String matcher

text:
# Question
Title: The FizzBuzz-ish String matcher
Say that you have a string like this:

`abaabbbbbaabba`

Count the number of times that a specified character appears in the input string, but only if the character appears *only once in a row*. For example, if the character is `a`,

```
abaabbbbbaabba
^ x      x   ^

```

The total would be 2 (the `aa`'s wouldn't count because the `a` appears two times in a row).

*How is this related to FizzBuzz?*

If the character appears 3 (or a multiple of 3) times in a row, or 5 (or a multiple of 5) times in a row, the counter is *decremented* instead. If it is a multiple of both 3 *and* 5 times, the counter is still incremented. Remember that the counter is also incremented if the character appears only once in a row, and it is ignored if the character appears any other number of times in a row (besides the situations described above).

To recap, if the string to match is `a`,

```
input            counter (explanation)

a                 1 (single occurence)
aaa               -1(multiple of 3)
aaaaa             -1(multiple of 5)
aaaaaaaaaaaaaaa   1 (multiple of 15)
aa                0 (none of the above)

aba               2 (two single instances)
aaba              1 (one single occurence(+1) and one double occurence(ignored))
aaaba             0 (one single occurence(+1) and one triple (-1)
aaaaaa            -1 (six is a multiple of three)

```

Reference (ungolfed) implementation in java:

```
import java.util.Scanner;
import java.util.regex.*;

public class StrMatcher {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); //Scanner to get user input
        int total = 0;//Running total of matches

        System.out.println("Enter a string: ");
        String strBeingSearched = sc.nextLine(); //String that will be searched

        System.out.println("Enter string to match with: ");
        String strBeingMatched = sc.nextLine(); //Substring used for searching

        //Simple regex matcher
        Pattern pattern = Pattern.compile("(" + strBeingMatched + ")+");
        Matcher matcher = pattern.matcher(strBeingSearched);

        while(matcher.find()){  //While there are still matches

            int length = matcher.end() - matcher.start();
            int numberOfTimes = length/strBeingMatched.length();//Calculate how many times in a row the string is matched

            if((numberOfTimes == 1)||((numberOfTimes % 3 == 0) && (numberOfTimes % 5 == 0))){
                total++; //Increment counter if single match or divisible by 15
            } else if((numberOfTimes % 3 == 0)||(numberOfTimes % 5 == 0)) {
                total--; //Decrement counter if divisible by 3 or 5 (but not 15)
            }

            strBeingSearched = strBeingSearched.substring(matcher.end());
            matcher = pattern.matcher(strBeingSearched); //Replace string/matcher and repeat
        }

        System.out.println(total);
    }
}

```
* The string that will be searched can be any length, but the pattern will only be a single character.
* Neither string will have regex special characters.
* This is ; shortest program in bytes wins.
* No standard loopholes.

# Answer
# Funciton, 1840 bytes

Damn, this language is ungolfable.

This program expects the first character of the input to be the character to search for, and the rest of the input to make the string to search through. This means that `aaaba` will search for `a` in the input `aaba` (and thus output 1). You *can* separate them with a newline or space (`a aaba`) but only because the extra newline/space makes no difference to the output.

As always, you can get a nicer-looking rendering (without the line spacing) if you execute `$('pre').css('line-height',1)` in your browser console.

```
      ┌───┐
      │╓─╖└─────────────┐
      └╢³╟┐    ┌─────┐ ┌┴┐╓─╖
┌─────┐╙─╜└────┤┌─╖ ┌┴╖│┌┘║¹║
│     ├───────┐└┤²╟─┤·╟┘│ ╙┬╜╔═══════╗
│    ┌┴╖╔═╗┌─╖├┐╘╤╝ ╘╤╝┌┘  └┬╢2097151║
│    │♭║║5╟┤%╟┘└─┴──┐│┌┘┌───┘╚═══════╝
│    ╘╤╝╚═╝╘╤╝╔═╗┌─╖│││┌┴┐┌────┐
│    ┌┴╖   ┌┘ ║3╟┤%╟┘││└┬┘│╔══╗└┐
│  ┌─┤·╟─┐ │  ╚═╝╘╤╝ │└┐  │║21╟┐│
│  │ ╘╤╝ ├─┘┌─────┘  └┐└┐ │╚══╝│└─┐
│ ┌┴╖┌┴╖┌┴╖┌┴╖┌─╖    ┌┴╖│ │┌─╖┌┴─╖│
│┌┤·╟┤?╟┤?╟┤?╟┤+╟────┤³║│ └┤²╟┤>>║└──┐
││╘╤╝╘╤╝╘╤╝╘╤╝╘╤╝    ╘╤╝│  ╘╤╝╘╤═╝╓─╖│
││ │ ┌┴╖┌┴╖┌┴╖┌┴╖╔═╗ ┌┴╖│  ┌┴╖ ├──╢²╟┤
││ └─┤·╟┤·╟┤?╟┤·╟╢1║┌┤·╟┘  │♯║┌┴╖ ╙─╜│
│└──┐╘╤╝╘╤╝╘╤╝╘╤╝╚═╝│╘╤╝   ╘╤╝│¹║┌───┘
└──┐│╔╧╗ └┬─┘ ┌┴╖   │┌┴─╖   │ ╘╤╝│
   ││║1║ ┌┴┐┌─┤?╟───┴┤>>╟┐ ┌┴╖┌┴╖│
   ││╚═╝ └┬┘│ ╘╤╝    ╘══╝│┌┤?╟┤=║│
   │└────┐│╔╧╗     ┌─────┘│╘╤╝╘╤╝│
╔═╗└────┐│├╢0║╔══╗┌┴╖┌─╖ ╔╧╗   └─┘
║ ║     │└┘╚═╝║21╟┤×╟┤♯╟┐║0║
╚╤╝     └──┐  ╚══╝╘═╝╘═╝│╚═╝
 │┌──┴────╖└────────────┘
 ││int→str║
 │╘══╤════╝
┌┴─╖┌┴╖┌─╖╔╗
│>>╟┤³╟┤¹╟╢║
╘═╤╝╘═╝╘═╝╚╝
╔═╧╗
║21║
╚══╝

```

(1840 bytes when encoded as UTF-16.)

# Explanation

* `¹` returns the first character of a string.
* `²` counts the number of occurrences of a character at the start of a given string. For example, given the character `a` and the string `aaba`, it returns 2. For `a` and `baa`, it returns 0.
* `³` calls `²` to get the number of characters at the start, examines whether the number is divisible by 3 and 5 and whether it is equal to 1 and determines the proper increment/decrement. It also removes one extra character from the start of the string (e.g. given `aaabba` it removes 3+1=4 characters, giving `ba`). Then it calls itself recursively with the shorter string and adds the result.
* The main program calls `¹` to remove the first character from the input and calls `³` with that character and the rest of the string as separate arguments.
> 32 votes

# Answer
# CJam, ~~40~~ ~~36~~ ~~35~~ ~~32~~ 30 bytes

```
0llcf=e`::*{(_g+Y13515Yb+=(+}/

```

*Thanks to @MartinBüttner for golfing off 1 byte!*

*Thanks to @AndreaBiondo for golfing off 2 bytes and paving the way for 3 more!*

Try it online in the CJam interpreter.

### How it works

```
0          e# Push a 0 (accumulator).
l          e# Read a line from STDIN.
lc         e# Read a second line and keep only the first character.
f=         e# Check each character from the first line for equality.
           e# This results in 1 for the specified character and 0 for others.
e`         e# Perform run-length encoding.
::*        e# Multiply each element by its number of repetitions.
{          e# For each remaining integer I:
  (_!      e#   Subtract 1, copy and push sign(I-1).
  +        e#   Add the results.
           e#     If I == 0, I-1 + sign(I-1) =  -1 + -1 = -2.
           e#     If I == 1, I-1 + sign(I-1) =   0 +  0 =  0.
           e#     If I >= 2, I-1 + sign(I-1) = I-1 +  1 =  I.
  Y        e#   Push 2.
  13515Yb  e#   Convert 13515 into the array of its binary digits.
  +        e#   Concatenate 2 and the array.
           e#   This pushes [2 1 1 0 1 0 0 1 1 0 0 1 0 1 1].
  =        e#   Retrieve the digit at (index I-1 + sign(I-1))%15.
           e#     If I == 0, this pushes 1.
           e#     Else, if I == 1, this pushes 2.
           e#     Else, if I%15 == 0, this pushes 2.
           e#     Else, if I%3==0 or I%5==0, this pushes 0.
           e#     Else, this pushes 1.
  (        e#   Decrement the result.
  +        e#   Add it to the accumulator.
}/         e#

```
> 14 votes

# Answer
## **C, ~~160~~ ~~126~~ ~~125~~ ~~119~~ ~~114~~ ~~109~~ ~~104~~ 100 bytes**

```
main(int q,char **z){int i=0,t=0,s=0,a=z[1][0],c;do{if((c=z[2][i])!=a){s+=(!!t)*((t==1)-!(t%3)-!(t%5)+3*!(t%15));t=0;}else{++t;}++i;}while(c);printf("%d\n",s);}

```

Probably can be made better... This takes input from command line arguments (first argument is pattern, second is string). Does not support searching for pattern of NULL char (\x00).

EDIT \**~~126~~ ~~125~~ ~~119~~ ~~114~~ ~~109~~ ~~104~~ 100 bytes \**: After incorporating Dennis's suggestions, and some additional ideas (removed else clause, combined the while into one single statement and used subtraction instead of !=). Also removed extra semicolon in for loop (that was actually part of Dennis's suggestion). Shortened even more by removing the variables 'i' and 'a'.

```
t,s;main(c,z)char**z;{for(;c;t++)if((c=*z[2]++)-*z[1])s+=!!t*((t<2)-!(t%3)-!(t%5)+3*!(t%15)),t=-1;printf("%d",s);}

```

Removed the if and negation ('!') operators by abusing the ternary operator. Compressed the modularity checks by using ~~that bitwise 'AND' trick~~ a double && because bitwise '&' has a bug, and putting the (t\<2) comparison inside the ternary operators. Replaced !!t * (...) by moving !!t into the ternary operator, thus allowing me to remove parentheses.

Man, I really want to get it below the 100 byte mark :S

```
t,s;main(c,z)char**z;{for(;c;)(c=*z[2]++)-*z[1]?s+=t%15?t%3&&t%5?t<2:-1:!!t,t=0:t++;printf("%d",s);}

```

TENTATIVE solutions: I am not sure if these would be considered valid, but I can get down to 93 chars if I use exit(s) instead of printf("%d",s). But then the output would not be visible, rather it would be a return code. If output is really necessary, I can also get it down to 98 bytes, but it would require printing all intermediate values of s before the final answer as well...
> 7 votes

# Answer
# Ruby, ~~111 103~~ 96 bytes

```
->s,m{s.chars.chunk{|x|x}.reduce(0){|x,(c,g)|l=g.size
x+(c!=m ?0:l<2||l%15<1?1:l%3*l%5<1?-1:0)}}

```

This challenge was made for Ruby's `Enumerable#chunk`, so I had to post this. :)

Online test: http://ideone.com/pG4mAn

The code is pretty much straightforward. Here's a more readable version: http://ideone.com/ub3siA.
> 4 votes

# Answer
# Python 3, ~~361, 300, 296, 263, 256, 237, 229, 188, 178~~, 164 bytes.

Saved 15 bytes thanks to vaultah from SOPython.
Saved 9 bytes thanks to Joe Kington from SOPython.
Saved 11 bytes thanks to DSM from SOPython.

This is my first time submitting an answer, so I'm sure this could be much shorter. It takes the test string as the first response to input, and the search char as the second one.

```
t=input()
m=input()
c=u=0
g=iter(t)
while g:
 r=next(g,0)
 if r==0:print(c);g=0
 while r==m:u+=1;r=next(g,0)
 if u:b=u%3<1;v=u%5<1;c+=((0,-1)[b|v],1)[u<2or b&v];u=0

```

Ungolfed version:

```
import sys
test = sys.argv[1]
match_char = sys.argv[2]
counter = char_counter = 0
char_generator = (c for c in test)
while char_generator:
    try:
        char = next(char_generator)
    except StopIteration:
        print(counter)
        break
    while char == match_char:
        char_counter += 1
        try:
            char = next(char_generator)
        except StopIteration:
            break
    if char_counter == 0:
        continue
    counter += 1 if char_counter == 1 or (char_counter % 3 == 0 and char_counter % 5 == 0) else -1 if char_counter % 3 == 0 or char_counter % 5 == 0 else 0
    char_counter = 0

```

Discovered I was failing one of the test cases.
> 4 votes

# Answer
# Java, ~~146~~ ~~152~~ ~~143~~ ~~138~~ ~~139~~ 136 bytes

1. Fixed a bug.
2. shifted operations, switched to bitwise operator for the `%3&%5` checks.
3. Shortened `i<2` comparison.
4. Fixed a bug (`%3&%5` check not working as thought).
5. Used multiplication shortcut as seen in @w0lf's Ruby answer.

Implemented as a `BiFunction<String, String, Integer>` in Java 8, let me know if this is required to be a full program (or if I can even drop the `java.util.regex` package prefix below).

Byte count above does not include the newline below, which is simply added for formatting purposes on this site.

```
(a,b)->java.util.regex.Pattern.compile("[^"+b+"]").splitAsStream(a)
.mapToInt(v->v.length()).map(i->i<2?i:i%15<1?1:i%3*i%5<1?-1:0).sum();

```

Rough explanation:

1. Apply regex with pattern that *does not* match `b`, i.e. `"[^"+b+"]"`.
2. Get length of each token (e.g. `"a" -> 1`).
3. Apply the desired mapping to `-1`, `0` and `1`.
4. `sum()` to get answer.
> 3 votes

# Answer
# Haskell, 120 bytes

```
import Data.List
f c=sum.map(v.length).filter((==c).head).group
v 1=1
v n|n%3&&n%5=1|(n%3||n%5)=(-1)|0<1=0
x%y=x`mod`y<1

```

`f` does the job.
> 3 votes

# Answer
# Javascript, 206 bytes

```
function f(n,e){var t=n.match(new RegExp(e,"g")).length,g=n.match(new RegExp(e+"{2,}","g"));return null!==g&&g.forEach(function(n){t-=n.length,n.length%15==0?t+=1:(n.length%3==0||n.length%5==0)&&(t-=1)}),t}

```

### Expanded:

```
function funkyFizzb(n, c) {
    var score = n.match(new RegExp(c, "g")).length;
    var repeatOccurence = n.match(new RegExp(c + "{2,}", "g"));

    if(repeatOccurence !== null) {
        repeatOccurence.forEach(function(v,i){
            // remove multiple occurrence counts
            score -= v.length;

            if(v.length % 15 == 0) {
                score += 1;
            }

            else if(v.length % 3 == 0 || v.length % 5 == 0) {
                score -= 1;
            }
        });
    }

    return score;
};

```

### Explanation:

I'm using regex to count total times a character appears, then subtract from that all the times it appeared in groups. Finally, I go through the groups and do the fizz buzz increment / decrement.

Passes the test cases given in the question:

```
funkyFizzb("aaa", "a") => -1

```

and so on
> 2 votes

# Answer
# Perl, ~~82~~ ~~65~~ ~~63~~ 59 bytes

58 bytes + 1 byte command line parameter

Not particularly short, but it's a start - will continue shortening it.

```
$l=y///c,$i+=!($l>1&&$l%15)||-!($l%3*$l%5)for/$^I+/g;$_=$i

```

Assuming `-i` can be used to give the input string an example usage is as follows:

```
echo "aaabaaa" | perl -pi"a" entry.pl

```
> 2 votes

# Answer
# Pyth, 32 bytes

so close! 2 more bytes to tie Dennis' excellent CJam entry

```
s.b?qYz?tN@+,0_1 1+}3PN}5PN1Zrw8

```

Test it Online
> 0 votes

# Answer
# gawk, 140

```
p=$2{b="[^"$1"]";for($0=2;$i-->0;){sub("^"b"*",_,p);p=substr(p,$++i=match(p,b))}for($i=length(p);$++j;)s+=$j%5?$j%3?$j<2:-1:$j%3?-1:1}$0=s""

```

Input as "char space string", like so

```
echo "x axxbxcxdexxxfffghixxj" | awk 'p=$2{b="[^"$1"]";for($0=2;$i-->0;){sub("^"b"*",_,p);p=substr(p,$++i=match(p,b))}for($i=length(p);$++j;)s+=$j%5?$j%3?$j<2:-1:$j%3?-1:1}$0=s""'

```

### Ungolfed

```
p=$2{
    #i=j=s=0                # make reusable
    b="[^"$1"]";           # pattern "not matching char"
    $0=2;                  # help starting the while loop
    while($i-->0){         # match didn't return -1; dec stack top
        sub("^"b"*",_,p);  # remove not matching chars at head of string
        $++i=match(p,b);   # push index of first occurence of not matching char
        p=substr(p,$i)     # remove matching chars from head of string
    };
    $i=length(p);          # get last value
    while($++j)            # sometimes last value on stack is 0
        s+=$j%5?$j%3?$j<2:-1:$j%3?-1:1

        # if $j%5!=0
        #   if $j%3!=0     (not divisible by 5 AND 3)
        #     s+=($j==1)   (single character)
        #   else           (divisible by 3 but not by 5)
        #     s-=1
        # else             (divisble by 5)
        #   if $j%3!=0
        #     s-=1         (divisible by 5 but not by 3)
        #   else
        #     s+=1         (divisible by 3 AND 5)

}$0=s"" # output

```
> 0 votes

# Answer
# Pyth, 27 bytes

```
sm|!JPdx,02+}3J}5JhMf}zTrw8

```

Test suite

Input in the form e.g.:

```
a
aaaba

```

Explanation:

```
sm|!JPdx,02+}3J}5JhMf}zTrw8
                               z = input() (The match character)
                         w     input() (The string)
                        r 8    Run length encode
                    f}zT       Filter for the runs z is in.
                  hM           Take their lengths
 m|                            Map (d) to the logical or of
    Pd                         Find all prime factors of the current run length
   J                           Save them in J
  !                            Take the logical negation. This will be 1 if
                               d is 1, and 0 otherwise.
           +}3J                If d wasn't 1, add up 1 if 3 is in J
               }5J             and 1 if 5 is in J.
       x,02                    Then, take the index of the result in [0,2]
                               so 0 -> 0, 2 -> 1, 1 -> -1 (not found)
s                              Sum up the values for each run.

```
> 0 votes

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


title: Crack the safe!

text:
# Question
Title: Crack the safe!
Inspired by https://puzzling.stackexchange.com/questions/24334/to-catch-a-thief

You are given an `n` by `n` (`n` itself is optional input) grid filled with `0`s and `1`s (or any other character of your choice). You aim is to make every cell the same (either `0` or `1`). You can make a series of moves as defined below (note dissimilarity with Puzzling SE link):

* Select a cell.
* Every cell in the same row and column (except the cell itself) gets changed into its opposite. `0` to `1` and `1` to `0`.

Output the minimum number of moves required to complete the task. If unsolvable, output anything except a non-negative integer. Shortest code wins.

**Sample data**

```
1 0 0
0 0 0
0 0 0

```

`-1`

```
1 1 1
1 1 1
1 1 1

```

`0`

```
1 0 1
0 1 0
1 0 1

```

`1`

```
1 1 1 1
0 0 0 0
0 0 0 0
1 1 1 1

```

`2`

```
0 1 0 1
1 0 1 0
1 0 1 0
0 1 0 1

```

`2`

# Answer
# Matlab 171 bytes

The input should be a 2d matrix, so you would call it like `c([1,1,1,1;0,0,0,0;0,0,0,0;1,1,1,1])` (semicolons start a new row). This function just bruteforces all possible moves, so we get a runtime of `O(2^(n^2))`.

### How it is done

This is done by choosing all possible ways to fill another matrix of the same size with ones and zero, this is basically counting in binary wich where each entry of the matrix represents a certain power of 2.

Then we perform the *moves* on those cells that are 1, this is done by the sum (mod 2) of two two dimensional convolution with an vector of ones of size 1xn and nx1.

Finally we decide if those moves actually produced the desired result, by computing the standard deviation over all entries. The standard deviation is only zeros if all entries are the same. And whenever we actually found the desired result we compare it with the number of moves of previous solutions. The function will return `inf` if the given problem is not solvable.

### Math?

It is actually worth noting that all those *moves* together generate an abelian group! If anyone actually manages to calssify those groups please let me know.

Golfed version:

```
function M=c(a);n=numel(a);p=a;M=inf;o=ones(1,n);for k=0:2^n-1;p(:)=dec2bin(k,n)-'0';b=mod(conv2(p,o,'s')+conv2(p,o','s'),2);m=sum(p(:));if ~std(b(:)-a(:))&m<M;M=m;end;end

```

Full version (with the output of the actual moves.)

```
function M = c(a)
n=numel(a);
p=a;
M=inf;                                               %current minimum of number of moves
o=ones(1,n);
for k=0:2^n-1;
    p(:) = dec2bin(k,n)-'0';                         %logical array with 1 where we perform moves
    b=mod(conv2(p,o,'same')+conv2(p,o','same'),2);   %perform the actual moves
    m=sum(p(:));                                     %number of moves;
    if ~std(b(:)-a(:))&m<M                           %check if the result of the moves is valid, and better
        M=m;
        disp('found new minimum:')
        disp(M)                                      %display number of moves of the new best solution (not in the golfed version)
        disp(p)                                      %display the moves of the new best solution                               (not in the golfed version)
    end
end

```
> 4 votes

# Answer
# Perl 5, 498 bytes

This accepts 'n' and the desired result, and outputs the count, or 'X' if none.

For example:

```
perl ./crack.golf.pl 3 000111111

```

gives `2`. It will only work when n^2 \<= 64, so `n <= 8`. Although it's pretty slow even with n as low as 5. It builds a n^3 bit array, and sorts a 2^(n^2) array beforehand, because *why not*?

I have wasted a couple of linefeeds here for *readability*:

```
$n=shift;$y=shift;$p=$n*$n;@m=(0..$n-1);@q=(0..$p-1);@v=(0..2**$p-1);@d=map{0}(@q);@b=map{$r=$_;map{$c=$_;$d[$r*$n+$_]^=1 for(@m);$d[$_*$n+$c]^=1 for(@m);$j=0;$k=1;
map{$j|=$k*$d[$_];$k<<=1;}@q;@d=map{0}(@q);$j;}@m}@m;for$k(sort{$a->[0]<=>$b->[0]}map{$z=0;map{$z+=$_}split(//,sprintf"%b",$_);[$z,$_]}@v){$l=sprintf"%0${p}b",$k->[1];
@m=map{$_}split(//,$l);$s=0;for(@q){$s^=$b[$_]if$m[$_];}$z=0;map{$z+=$_}split(//,sprintf"%b",$_);if($y eq sprintf"%0${p}b",$s){print"$k->[0]\n";exit 0;}}print"X\n";

```
> 1 votes

---
Tags: code-golf, grid, puzzle-solver, path-finding
---


title: Life can be colorful!

text:
# Question
Title: Life can be colorful!
Each cell in a life-like cellular automaton only needs one bit to represent it since it can only be alive or dead. That means there are only two colors; pretty boring.

Normal images have 24 bits per pixel (8 in each of R G B). This means in a normal image with pixels as cells you could simulate 24 life-like games at once!

# Challenge

Your task is to write a program that will apply one generation of the rules of a life-like cellular automaton to a 24-bit depth image (in any well known format you like), and output the resulting image.

Each of the 24 layers will use the same life-like ruleset, strictly within it's own layer. **The 24 layers do not interact with each other.**

**Also**

* Zeros are dead cells and ones are live cells.
* Boundary conditions are periodic (forming a torus).
* Any image dimensions should work.

# Input/Output

Your program needs to take in 3 arguments, via stdin or command line (or your language's closest equivalent):

1. The name of the input image file.
2. A string of the digits 0 to 8 in increasing order that denotes when new cells are born:
    * If the digit *d* is in the string then dead cells come alive when they have *d* living neighbors.
    * Example: `3` is normal Life \- Dead cells with exactly 3 living neighbors come to life.
3. A string of the digits 0 to 8 in increasing order that denotes when existing cells survive:
    * If the digit *d* is in the string then living cells with *d* living neighbors survive to the next generation, otherwise they die.
    * Example: `23` is normal Life - Only cells with exactly 2 or 3 neighbors survive to the next round.

*Note that the Moore neighborhood is always used. Read this or this for more info on what precisely defines a life-like automaton and many interesting rulesets.*

The 1-generation-later output image should either be displayed or saved as `out.png` (or `bmp` or whatever).

# Submission

The shortest code in bytes wins.

You are **required** to include at least one test image and its three immediate subsequent generations for some non-trivial ruleset. Use your avatar and the normal Life rules if you can't think of anything better.

If you like you may use this Gosper Glider Gun where the only living bits are in the green 128 layer (it's only sure to work in normal Life):

Posting interesting sequences or even animations is highly encouraged.

# Answer
# MATLAB: 275

My favorite of the parameters I tried is `45678`, `568` which following a gradual disintegration results in a sky of twinkling stars. This image depicts, "the disintegration of the persistence of memory."

Ungolfed gif-producing code (accepts PNG without extension):

```
B = input('B', 's') - 48;
S = input('S', 's') - 48;
f0 = input('file: ', 's');
frames = 60;

f = sprintf('%s.png',f0);
fout = sprintf('%s.gif',f0);
first = 1;
img = imread(f);
for i = 1:60
    out = img * 0;
    [r, c, turd] = size(img);
    for b=0:7
        bimg = ~~bitand(img,2^b);
        pimg = [bimg,bimg,bimg;bimg,bimg,bimg;bimg,bimg,bimg];
        fun = @(ro,co) pimg(r+ro:r+r+ro-1,c+co:c+c+co-1,:);
        sum = fun(0,0)+fun(0,1)+fun(0,2)+fun(1,0)+fun(1,2)+fun(2,0)+fun(2,1)+fun(2,2);
        bnew = uint8(bimg & ismember(sum,S) | ~bimg & ismember(sum, B));
        out = out + 2^b * bnew;
    end
    %imwrite(out,'out.png');
       if first
           [img1,img2] = rgb2ind(img,256);
           imwrite(img1,img2,fout,'gif','Loop',Inf);
          imwrite(img1,img2,fout,'gif','WriteMode','append');
           first = 0;
       end
       img = out;
       [img1,img2] = rgb2ind(img,256);
       imwrite(img1,img2,fout,'gif','WriteMode','append');%,'DelayTime', 2*delay);
end

```

Golfed code that accepts a full filename (which can be GIF, JPEG, and perhaps other stuff) and writes to `out.png`:

```
I=@()input('','s');B=I();S=I();i=imread(I());o=0;[r,c,t]=size(i);for b=0:7
g=~~bitand(i,2^b);p=repmat(g,3);F=@(z,Z)p(r+z:r+r+z-1,c+Z:c+c+Z-1,:);M=@(A)ismember(F(0,0)+F(0,1)+F(0,2)+F(1,0)+F(1,2)+F(2,0)+F(2,1)+F(2,2),A-48);o=o+2^b*uint8(g&M(S)|~g&M(B));end
imwrite(o,'out.png')

```

A previously discovered fact is that parameters `12`, `1` can be used to generate a Sierpinski carpet-like fractal. Here is one with a randomly placed seed point in each bit:
> 17 votes

# Answer
## Mathematica, 359

```
i=InputString;f=Transpose;b=(p=FromDigits/@Characters@#&)@i[];s=p@i[];Map[FromDigits[#,2]&/@#~ArrayReshape~{3,8}&,f[(g=#;{#,Total[g~RotateRight~#&/@Drop[Join@@Table[{i,j},{i,-1,1},{j,-1,1}],{5}],1]}~f~{3,1,2}/.{l_,n_}:>Boole[l<1&&!b~FreeQ~n||l>0&&!s~FreeQ~n])&/@Apply[Join,IntegerDigits[ImageData[Import@i[],y="byte"],2,8],{2}]~f~{2,3,1},{3,1,2}],{2}]~Image~y

```

I'm taking input from string prompts in the order (1) birth rules, (2) survival rules, (3) file name, and I'm displaying the result right in Mathematica.

This should be able to deal with most popular formats, as long as the file actually has 24-bit depth.

Here is a somewhat ungolfed version:

```
i = InputString;
f = Transpose;
b = (p = FromDigits /@ Characters@# &)@i[];
s = p@i[];
Map[
  FromDigits[#,2] & /@ #~ArrayReshape~{3, 8} &,
  f[
   (
      g = #;
      {#,
         Total[g~RotateRight~# & /@
           Drop[Join @@ Table[{i, j}, {i, -1, 1}, {j, -1, 1}], {5}],
          1]}~f~{3, 1, 2} /. {l_, n_} :>
        Boole[l < 1 && ! b~FreeQ~n || l > 0 && ! s~FreeQ~n]
      ) & /@
    Apply[Join,
      IntegerDigits[ImageData[Import@i[], y = "byte"], 2, 8], {2}]~
     f~{2, 3, 1},
   {3, 1, 2}
   ],
  {2}
  ]~Image~y

```

Here are two examples using Rainbolt's avatar:

20 generations using the standard Game of Life `[3,23]`:

20 generations using `[456,34567]`:

And here is a GIF of the first 200 generations of the latter rule. The GIF skips every third frame, because I couldn't compress it below 2MB otherwise:
> 14 votes

# Answer
# Python 2, 427

For those who don't have Mathematica ;)

```
import Image as I
t=raw_input
r=range
A=I.open(t())
G=map(int,t())
S=map(int,t())
w,h=A.size
B=I.new('RGB',(w,h))
A=[[map(int,("{:08b}"*3).format(*A.load()[x,y]))for y in r(h)]for x in r(w)]
for x in r(w):
 for y in r(h):
  p=''
  for i in r(24):
    c=A[x][y][i]
    n=sum(A[(x+k-1)%w][(y+j-1)%h][i]for j in r(3)for k in r(3))-c
    p+=str(~~[n in G,n in S][c])
  B.load()[x,y]=tuple(int(p[i*8:i*8+8],2)for i in r(3))
B.save('out.bmp')

```

It prompts for the filename, then the birth cases, then the survival cases. So for normal life rules you might input `test.bmp`, then `3`, then `23` (no quotes or anything needed).

I used string formatting to index into and recombine the color bits, though I fear that's probably not optimal.

Note that's it's pretty slow.

# Example

High life and great art mix right? (Rule `36` / `23`.)

Original / Generation 1

Generation 2 / Generation 3
> 11 votes

# Answer
# Java, 1085 bytes

```
import java.awt.image.*;import java.io.*;import javax.imageio.*;class F{static int n(boolean[][][]a,int x,int y,int z){int k=0;for(X=Math.max(x-1,0);X<Math.min(x+2,w);X++)for(Y=Math.max(y-1,0);Y<Math.min(y+2,h);Y++)if(a[X][Y][z])k++;return k-(a[x][y][z]?1:0);}static int p(String k){return Integer.parseInt(k,2);}static int w,h,x,y,z,X,Y;public static void main(String[]a)throws Exception{BufferedImage i=ImageIO.read(new File(a[0]));w=i.getWidth();h=i.getHeight();boolean[][][]G=new boolean[w][h][24];for(x=0;x<w;x++)for(y=0;y<h;y++){String k="".format("%24s",Integer.toBinaryString(0xFFFFFF&i.getRGB(x,y)));for(z=0;z<24;z++){G[x][y][z]=k.charAt(z)>48;}}for(x=0;x<w;x++)for(y=0;y<h;y++){String r="",g="",b="",k;for(z=0;z<8;){k=""+n(G,x,y,z);r+=(-1!=(G[x][y][z++]?a[1].indexOf(k):a[2].indexOf(k)))?1:0;}for(;z<16;){k=""+n(G,x,y,z);g+=(-1!=(G[x][y][z++]?a[1].indexOf(k):a[2].indexOf(k)))?1:0;}for(;z<24;){k=""+n(G,x,y,z);b+=(-1!=(G[x][y][z++]?a[1].indexOf(k):a[2].indexOf(k)))?1:0;}i.setRGB(x,y,new java.awt.Color(p(r),p(g),p(b)).getRGB());}ImageIO.write(i,"png",new File("out.png"));}}

```

Examples (rule 368/245):

Gen 0:

Gen 1:

Gen 2:

Gen 3:

Gen 4:
> 7 votes

---
Tags: code-golf, graphical-output, image-processing, game-of-life
---