title: Solve a Solitaire Chess Puzzle

text:
# Question
Title: Solve a Solitaire Chess Puzzle
Recently, I was introduced to a puzzle game known as Solitaire Chess. I'll summarize the rules here:

* The board is a 4x4 checkerboard.
* All pieces are the same color (no teams) and all pieces can capture any other piece.
* Every move must be a capture. No moving to empty squares.
* There must be exactly one piece remaining at the end.
* All pieces move exactly like they do in chess, with one modification: the pawn can capture in any diagonal direction (which technically makes it a *ferz*). For the benefit of those who may not know, I have included movement diagrams.
* None of the other rules of chess (such as check, castling, etc.) apply here. It's all about captures.

**King (K)**

```
K * . . | * K * . | * * * .
* * . . | * * * . | * K * .
. . . . | . . . . | * * * .
. . . . | . . . . | . . . .

```

**Queen (Q)**

```
Q * * * | * Q * * | * * * .
* * . . | * * * . | * Q * *
* . * . | . * . * | * * * .
* . . * | . * . . | . * . *

```

**Rook (R)**

```
R * * * | * R * * | . * . .
* . . . | . * . . | * R * *
* . . . | . * . . | . * . .
* . . . | . * . . | . * . .

```

**Bishop (B)**

```
B . . . | . B . . | * . * .
. * . . | * . * . | . B . .
. . * . | . . . * | * . * .
. . . * | . . . . | . . . *

```

**Knight (N)**

```
N . . . | . N . . | . . . *
. . * . | . . . * | . N . .
. * . . | * . * . | . . . *
. . . . | . . . . | * . * .

```

**Pawn (P)**

```
P . . . | . P . . | * . * .
. * . . | * . * . | . P . .
. . . . | . . . . | * . * .
. . . . | . . . . | . . . .

```

## Input/output

For reference, the sample puzzle from the Solitaire Chess webpage will be used:

```
. . . .
. B . .
R P . .
. . . N

```

The solution is to take the pawn with the knight, then take the knight with the rook, and finally take the bishop with the rook.

**Input**

Input must be in one of three forms; you are free to pick the one that is most convenient for you.

* A string of characters such as `.....B..RP.....N`, with or without newlines. The character representing a blank space may be any character that isn't one of `KQRBNP`.
* A list of lists (or a flattened list) where the elements are either characters or numbers, like so: `[['.', '.', '.', '.'], ['.', 'B', '.', '.'], ['R', 'P', '.', '.'], ['.', '.', '.', 'N']]` or `[[0, 0, 0, 0], [0, 4, 0, 0], [3, 6, 0, 0], [0, 0, 0, 5]]`. For the former, the character that represents a blank space may be anything that isn't one of `KQRBNP`. For the latter, I've given pieces the number that corresponds to their rank in my earlier list of moves (`1` is a king, `4` is a bishop, `6` is a pawn, etc.). You are free to change the numbering.
* A list of coordinates where each element has the form `[x, y, 'c']`, like so: `[[1, 2, 'B'], [0, 1, 'R'], [1, 1, 'P'], [3, 0, 'N']]`.

If you pick one of the list-based input formats, the separators and delimiters may be any reasonable and understandable characters.

**Output**

Output must be a sequence of moves or a sequence of board states. Some puzzles have more than one solution; you may output one or all of them. If you choose to output a sequence of board states, each board must be in one of the three input formats, with a reasonable separator (such as newlines) between them.

If you choose to output a sequence of moves, they must be expressed as a list of pairs of coordinate pairs, like so: `[[[3,0], [1,1]], [[0,1], [1,1]], [[1,1], [1,2]]]`. `[0,0]` represents the bottom left corner, and again, separating and delimiting characters may be any reasonable choice.

If a given board cannot be solved, output any falsy value (`0`, empty string, etc.). If a given board has fewer than two pieces, behavior is undefined.

## Test Cases

*Note: outputs are only given as a list of pairs of coordinates since the other formats should be fairly easy to check for correctness (and I didn't feel like typing out all the possible output formats). Also, for the puzzles that have more than one solution, only one possibility is provided.*

**Input 1:**

```
. . . N
. . . .
. R . .
. . B .

...N.....R....B.

[['.', '.', '.', 'N'], ['.', '.', '.', '.'], ['.', 'R', '.', '.'], ['.', '.', 'B', '.']]

[[0, 0, 0, 5], [0, 0, 0, 0], [0, 3, 0, 0], [0, 0, 4, 0]]

[[3, 3, 'N'], [1, 1, 'R'], [2, 0, 'B']]

```

**Output 1:**

```
[[[2,0], [1,1]], [[1,1], [3,3]]]

```

**Input 2:**

```
. . . .
. B . .
R P . .
. . . N

.....B..RP.....N

[['.', '.', '.', '.'], ['.', 'B', '.', '.'], ['R', 'P', '.', '.'], ['.', '.', '.', 'N']]

[[0, 0, 0, 0], [0, 4, 0, 0], [3, 6, 0, 0], [0, 0, 0, 5]]

[[1, 2, 'B'], [0, 1, 'R'], [1, 1, 'P'], [3, 0, 'N']]

```

**Output 2:**

```
[[[3,0], [1,1]], [[0,1], [1,1]], [[1,1], [1,2]]]

```

**Input 3:**

```
. N R .
B . . .
N . . B
. . P .

.NR.B...N..B..P.

[['.', 'N', 'R', '.'], ['B', '.', '.', '.'], ['N', '.', '.', 'B'], ['.', '.', 'P', '.']]

[[0, 5, 3, 0], [4, 0, 0, 0], [5, 0, 0, 4], [0, 0, 6, 0]]

[[1, 3, 'N'], [2, 3, 'R'], [0, 2, 'B'], [0, 1, 'N'], [3, 1, 'B'], [2, 0, 'P']]

```

**Output 3:**

```
[[[2,0], [3,1]], [[0,1], [1,3]], [[0,2], [1,3]], [[2,3], [1,3]], [[3,1], [1,3]]]

```

**Input 4:**

```
. . . N
. . . R
R B B .
N P P .

...N...RRBB.NPP.

[['.', '.', '.', 'N'], ['.', '.', '.', 'R'], ['R', 'B', 'B', '.'], ['N', 'P', 'P', '.']]

[[0, 0, 0, 5], [0, 0, 0, 3], [3, 4, 4, 0], [5, 6, 6, 0]]

[[3, 3, 'N'], [3, 2, 'R'], [0, 1, 'R'], [1, 1, 'B'], [2, 1, 'B'], [0, 0, 'N'], [1, 0, 'P'], [2, 0, 'P']]

```

**Output 4:**

```
[[[2,1], [3,2]], [[1,1], [3,3]], [[3,2], [1,0]], [[3,3], [0,0]], [[0,1], [0,0]], [[0,0], [1,0]], [[1,0], [2,0]]]

```

**Input 5:**

```
P . . .
. R . .
R . R .
. R . .

P....R..R.R..R..

[['P', '.', '.', '.'], ['.', 'R', '.', '.'], ['R', '.', 'R', '.'], ['.', 'R', '.', '.']]

[[6, 0, 0, 0], [0, 3, 0, 0], [3, 0, 3, 0], [0, 3, 0, 0]]

[[0, 3, 'P'], [1, 2, 'R'], [0, 1, 'R'], [2, 1, 'R'], [1, 0, 'R']]

```

**Output 5:**

```
[[[0,3], [1,2]], [[1,2], [2,1]], [[2,1], [1,0]], [[1,0], [0,1]]]

```

**Input 6:**

```
. P . N
K . . .
. . B .
. . R Q

.P.NK.....B...RQ

[['.', 'P', '.', 'N'], ['K', '.', '.', '.'], ['.', '.', 'B', '.'], ['.', '.', 'R', 'Q']]

[[0, 6, 0, 5], [1, 0, 0, 0], [0, 0, 4, 0], [0, 0, 3, 2]]

[[1, 3, 'P'], [3, 3, 'N'], [0, 2, 'K'], [2, 1, 'B'], [2, 0, 'R'], [3, 0, 'Q']]

```

**Output 6:**

```
[[[3,0], [2,0]], [[2,0], [2,1]], [[3,3], [2,1]], [[2,1], [1,3]], [[0,2], [1,3]]]

```

# Answer
# Haskell, ~~226~~ ~~195~~ ~~191~~ 188 bytes

Returns a list of all solutions. Each solution is a list of moves. Returns an empty list if there is no solution.

Saved 4 bytes Thanks to Lynn.

Try it online

```
m"P"=[2]
m"N"=[5]
m"K"=[1,2]
m"R"=[1,4,9]
m"B"=[2,8,18]
m _=m"B"++m"R"
l%x=[z|z<-l,fst z/=x]
f[_]=[[]]
f l=[(i,j):r|(i@(s,t),a)<-l,(j@(u,v),_)<-l,(s-u)^2+(t-v)^2`elem`m a,r<-f$(j,a):l%i%j]

```

Usage:

```
main = do
    print $ f [((3, 3), "N"), ((1, 1), "R")]
    putStrLn""
    mapM_ print $ f [((3, 3), "N"), ((1, 1), "R"), ((2, 0), "B")]
    putStrLn""
    mapM_ print $ f [((1, 2), "B"), ((0, 1), "R"), ((1, 1), "P"), ((3, 0), "N")]
    putStrLn""
    mapM_ print $ f [((1, 3), "P"), ((3, 3), "N"), ((0, 2), "K"), ((2, 1), "B"), ((2, 0), "R"), ((3, 0), "Q")]

```

Output:

```
[]

[((2,0),(1,1)),((1,1),(3,3))]

[((3,0),(1,1)),((0,1),(1,1)),((1,1),(1,2))]

[((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2))]
[((1,3),(0,2)),((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2))]
[((1,3),(0,2)),((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(0,2))]
[((1,3),(0,2)),((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2))]
[((1,3),(0,2)),((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))]
[((1,3),(0,2)),((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))]
[((1,3),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(0,2))]
[((1,3),(0,2)),((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))]
[((1,3),(0,2)),((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2))]
[((1,3),(0,2)),((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(0,2))]
[((3,3),(2,1)),((2,1),(1,3)),((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3))]
[((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2)),((3,0),(2,0)),((2,0),(0,2))]
[((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3))]
[((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((1,3),(0,2))]
[((3,3),(2,1)),((2,1),(0,2)),((3,0),(2,0)),((1,3),(0,2)),((2,0),(0,2))]
[((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2)),((3,0),(2,0)),((2,0),(0,2))]
[((3,3),(2,1)),((1,3),(0,2)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2))]
[((3,3),(2,1)),((1,3),(0,2)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(0,2))]
[((3,3),(2,1)),((1,3),(0,2)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2))]
[((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2)),((0,2),(1,3))]
[((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2)),((1,3),(0,2))]
[((3,3),(2,1)),((3,0),(2,1)),((2,1),(2,0)),((1,3),(0,2)),((2,0),(0,2))]
[((3,3),(2,1)),((3,0),(2,1)),((1,3),(0,2)),((2,1),(2,0)),((2,0),(0,2))]
[((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3)),((2,1),(1,3))]
[((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(0,2)),((1,3),(0,2))]
[((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((2,1),(1,3)),((0,2),(1,3))]
[((3,3),(2,1)),((3,0),(2,0)),((2,0),(0,2)),((1,3),(0,2)),((2,1),(0,2))]
[((3,3),(2,1)),((3,0),(2,0)),((2,1),(1,3)),((2,0),(0,2)),((0,2),(1,3))]
[((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2)),((0,2),(1,3))]
[((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((2,0),(0,2)),((1,3),(0,2))]
[((3,3),(2,1)),((3,0),(2,0)),((2,1),(0,2)),((1,3),(0,2)),((2,0),(0,2))]
[((3,3),(2,1)),((3,0),(2,0)),((1,3),(0,2)),((2,0),(0,2)),((2,1),(0,2))]
[((3,3),(2,1)),((3,0),(2,0)),((1,3),(0,2)),((2,1),(0,2)),((2,0),(0,2))]
[((0,2),(1,3)),((2,1),(3,0)),((2,0),(3,0)),((3,0),(3,3)),((3,3),(1,3))]
[((0,2),(1,3)),((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))]
[((0,2),(1,3)),((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))]
[((0,2),(1,3)),((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))]
[((2,1),(3,0)),((0,2),(1,3)),((2,0),(3,0)),((3,0),(3,3)),((3,3),(1,3))]
[((2,1),(3,0)),((2,0),(3,0)),((3,0),(3,3)),((3,3),(1,3)),((0,2),(1,3))]
[((2,1),(3,0)),((2,0),(3,0)),((3,0),(3,3)),((0,2),(1,3)),((3,3),(1,3))]
[((2,1),(3,0)),((2,0),(3,0)),((0,2),(1,3)),((3,0),(3,3)),((3,3),(1,3))]
[((2,0),(2,1)),((1,3),(0,2)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))]
[((2,0),(2,1)),((0,2),(1,3)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))]
[((2,0),(2,1)),((3,0),(2,1)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))]
[((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))]
[((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))]
[((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))]
[((2,0),(2,1)),((3,0),(2,1)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))]
[((2,0),(2,1)),((3,0),(2,1)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))]
[((3,0),(3,3)),((3,3),(1,3)),((1,3),(0,2)),((0,2),(2,0)),((2,0),(2,1))]
[((3,0),(2,1)),((2,1),(2,0)),((2,0),(0,2)),((0,2),(1,3)),((1,3),(3,3))]
[((3,0),(2,1)),((1,3),(0,2)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))]
[((3,0),(2,1)),((0,2),(1,3)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))]
[((3,0),(2,1)),((2,0),(2,1)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))]
[((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))]
[((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))]
[((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))]
[((3,0),(2,1)),((2,0),(2,1)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))]
[((3,0),(2,1)),((2,0),(2,1)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))]
[((3,0),(2,0)),((2,0),(0,2)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))]
[((3,0),(2,0)),((2,0),(0,2)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))]
[((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))]
[((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))]
[((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))]
[((3,0),(2,0)),((2,0),(0,2)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))]
[((3,0),(2,0)),((2,0),(2,1)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2))]
[((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3)),((0,2),(1,3))]
[((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2))]
[((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2))]
[((3,0),(2,0)),((2,0),(2,1)),((3,3),(2,1)),((0,2),(1,3)),((2,1),(1,3))]
[((3,0),(2,0)),((2,0),(2,1)),((0,2),(1,3)),((3,3),(2,1)),((2,1),(1,3))]
[((3,0),(2,0)),((1,3),(0,2)),((2,0),(0,2)),((3,3),(2,1)),((2,1),(0,2))]
[((3,0),(2,0)),((1,3),(0,2)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(0,2))]
[((3,0),(2,0)),((1,3),(0,2)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2))]
[((3,0),(2,0)),((1,3),(0,2)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(0,2))]
[((3,0),(2,0)),((3,3),(2,1)),((2,1),(1,3)),((2,0),(0,2)),((0,2),(1,3))]
[((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2)),((0,2),(1,3))]
[((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((2,0),(0,2)),((1,3),(0,2))]
[((3,0),(2,0)),((3,3),(2,1)),((2,1),(0,2)),((1,3),(0,2)),((2,0),(0,2))]
[((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((0,2),(1,3)),((2,1),(1,3))]
[((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(0,2)),((1,3),(0,2))]
[((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((2,1),(1,3)),((0,2),(1,3))]
[((3,0),(2,0)),((3,3),(2,1)),((2,0),(0,2)),((1,3),(0,2)),((2,1),(0,2))]
[((3,0),(2,0)),((3,3),(2,1)),((1,3),(0,2)),((2,1),(0,2)),((2,0),(0,2))]
[((3,0),(2,0)),((3,3),(2,1)),((1,3),(0,2)),((2,0),(0,2)),((2,1),(0,2))]
[((3,0),(2,0)),((0,2),(1,3)),((2,0),(2,1)),((3,3),(2,1)),((2,1),(1,3))]

```
> 10 votes

# Answer
## Javascript (ES6), ~~372~~ ~~361~~ 358 bytes

It (still) needs some optimizing. But here is a ~~first~~ ~~2nd~~ 3rd attempt.

```
b=>{for(n=-4,b=[...b];n<36;b.splice(n+=8,0,0,0,0,0));l=[];(M=(P,u,Z,z,L)=>{for(P=u=n;u--;)
for((z=[640,164928,641,259,899,898]["PNBRQK".indexOf(b[u])])&&P++,L=1,s=z&1;z>>=1;L++)for(Z
=u;z&1&!((Z+=L)&n)&&(b[Z]<'A'||!(M(l.push([b[Z],[u&3,31-u>>3],b[u],[Z&3,31-Z>>3]]),b[Z]=b[u
],b[u]='.'),b[u]=b[Z],b[Z]=l.pop()[0]))&&s||(L=-L,Z=u,L<0););P-37||console.log(l)})()}

```

Output format:

```
// Puzzle #1
[["B", [2, 0], "R", [1, 1]], ["B", [1, 1], "N", [3, 3]]]

```

Example:

```
let F =
b=>{for(n=-4,b=[...b];n<36;b.splice(n+=8,0,0,0,0,0));l=[];(M=(P,u,Z,z,L)=>{for(P=u=n;u--;)for((z=[640,164928,641,259,899,898]["PNBRQK".indexOf(b[u])])&&P++,L=1,s=z&1;z>>=1;L++)for(Z=u;z&1&!((Z+=L)&n)&&(b[Z]<'A'||!(M(l.push([b[Z],[u&3,31-u>>3],b[u],[Z&3,31-Z>>3]]),b[Z]=b[u],b[u]='.'),b[u]=b[Z],b[Z]=l.pop()[0]))&&s||(L=-L,Z=u,L<0););P-37||console.log(l)})()}

console.log("Puzzle #1");
F("...N.....R....B.");
console.log("Puzzle #2");
F(".....B..RP.....N");
```
> 1 votes

---
Tags: code-golf, chess
---


title: Hiding elements with CSS only

text:
# Question
Title: Hiding elements with CSS only
In the following markup without changing it or using JS, implement the behavior to show only the `ul` element of `div` which name is clicked in the first `ul` (before `div`). Name is content of `li` in top `ul` and it matches the content of the first `li` in `ul` you want to show. Elements that have `{content}` are just fillers and have no meaning for problem.

```
<ul>
  <li class="head"><a href="#favorites">Favourite dishes</a></li>
  <li><a href="#breakfasts"><i>Breakfasts</i></a></li>
  <li><a href="#dinners"><i>Dinners</i></a></li>
  <li><a href="#suppers"><i>Suppers</i></a></li>
</ul>
<div>
    <ul id="breakfasts">
       <li class="head">Breakfasts</li>
       <li>{Breakfast 1}</li>
       <li>{Breakfast 2}</li>
       <li>{Breakfast 3}</li>
    </ul>
    <ul id="dinners">
       <li class="head">Dinners</li>
       <li>{Dinner 1}</li>
       <li>{Dinner 2}</li>
       <li>{Dinner 3}</li>
    </ul>
    <ul id="suppers">
       <li class="head">Dinners</li>
       <li>{Supper 1}</li>
       <li>{Supper 2}</li>
       <li>{Supper 3}</li>
    </ul>
    <ul class="favorites">
       <li class="head">Favourites</li>
       <li>{Favourite 1}</li>
       <li>{Favourite 2}</li>
       <li>{Favourite 3}</li>
    </ul>
</div>

```

This problem really has the solution and was very interesting for me, so I decided to post it here even if it's not very practical. Hint: you have to use `:target` pseudo-class.

# Answer
> 1 votes
I think your hint gave too much away:

```
div>ul:target{
   display: block;
}
div>ul{
   display: none;
}

```

---
Tags: programming-puzzle, css
---


title: Repetition of letters

text:
# Question
Title: Repetition of letters
Your task is to take an input, for example:

`a,b,4,5`

And produce an output, which per this example is `aaaabbbbb`

`a,b,4,5` means: the lowercase character "a" is repeated 4 times, and is then followed by the lowercase character "b" repeated 5 times, making the total number of characters 4+5=9

Another example: the input `a,B,5,4`, should produce the output `aaaaaBBBB`, which is: the lowercase letter "a" is repeated 5 times, followed by the uppercase letter "B" repeated 4 times.

Some more examples:

```
Input --> Output

a,b,4,6         --> aaaabbbbbb
a,b,c,1,2,3     --> abbccc
a,e,d,f,g,1,2,3,4,5 --> aeedddffffggggg
A,b,4,5         --> AAAAbbbbb
A,b,C,1,2,3     --> AbbCCC
A,B,c,D,1,2,3,4 --> ABBcccDDDD

```

Note how the output must have only the required letters, nothing else, except trailing newlines.

The format of the input should be exactly as you see in the above examples, so your code does not have to support any additional formats/styles of the input.

The output must be displayed in a format exactly as the examples show, this means no commas, spaces, etc, separating the letters. Trailing newlines are okay, if you cannot avoid them.

Standard loopholes are disallowed, and the output is case sensitive.

This is , so the shortest code in bytes wins!

# Answer
## 05AB1E, 11 bytes

```
',¡2äøvy`×?

```

**Explanation**

```
',¡             # turn input into a list split at commas
   2ä           # divide that list in 2
       ø        # zip, turning the list into pairs of [letter, number]
        v       # for each pair
         y`×?   # print letter number of times

```

Try it online
> 3 votes

# Answer
# Pyth - 14 bytes

```
Ac2cz\,s*VGsMH

```

Try it online here.
> 2 votes

# Answer
# Python 2 - 88 bytes

```
X=map(str,input().split(','))
k=len(X)/2
print''.join(X[i]*int(X[i+k])for i in range(k))

```

Edited to remove whitespace
> 2 votes

# Answer
# APL, 26 bytes

```
{(∊(//)C⎕VFI⍵)/⍵~⎕D,C←','}

```

Test:

```
          {(∊(//)C⎕VFI⍵)/⍵~⎕D,C←','}'A,b,C,1,2,3'
AbbCCC

```

APL has a built-in for this, so all the code is really doing is parsing the string:

```
      1 2 3/'AbC'
AbbCCC

```

Explanation:

* `⍵~⎕D,C←','`: remove all digits and commas from the input, leaving only the letters. (Since it only has to deal with single letters, this works.)
* `∊(//)C⎕VFI⍵`: using the comma as a field separator, get all valid numbers in the input.
* `/`: replicate each letter by the required amount
> 2 votes

# Answer
# PHP, 84 bytes

```
$b=split(',',$argv[1]);while($i<$n=count($b)/2)echo str_repeat($b[+$i],$b[$n+$i++]);

```

Takes the input string as the first argument as in `php script.php a,B,c,3,2,6`.
> 1 votes

# Answer
# Python 2, 66 bytes

```
i=input();l=len(i)/2
print''.join(s*y for s,y in zip(i[:l],i[l:]))

```

Uses every Python golfer's favourite function, `zip()`. Takes input with letters in quotes e.g.:

```
'a','b',4,6

```

**Ideone it!**
> 1 votes

---
Tags: code-golf
---


# Question
Title: Code golf ABC's: The ASCII Box Challenge
Given two positive integers, 'a' and 'b', output an ascii-art "box" that is *a* characters wide and *b* characters tall. For example, with '4' and '6':

```
****
*  *
*  *
*  *
*  *
****

```

Simple right? Here's the twist: The border of the box must be the characters of "a" and "b" alternating. This starts at the top left corner, and continues in a clockwise spiral. For example, the previous example with 4 and 6 should be

```
4646
6  4
4  6
6  4
4  6
6464

```

A and B *may* be two-digit numbers. For example, the inputs "10" and "3" should output this:

```
1031031031
1        0
3013013013

```

In order to keep the output relatively small, you do not have to support three or more digit numbers. Also, since inputs are restricted to *positive* integers, '0' is an invalid input, which you do not have to handle.

Here are some more test cases:

```
Input: (3, 5)
Output:

353
5 5
3 3
5 5
353

Input: (1, 1)
Output:

1

Input: (4, 4)
Output:

4444
4  4
4  4
4444

Input: (27, 1)
Output:

271271271271271271271271271

Input: (1, 17)
Output:

1
1
7
1
1
7
1
1
7
1
1
7
1
1
7
1
1

Input: (12, 34):
Output:

123412341234
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
4          1
3          2
2          3
1          4
432143214321

```

You may take input and output in any reasonable format, and standard loopholes are banned. Since this is code-golf, the shortest answer in bytes wins!

# Answer
> 4 votes
# Pyth, ~~65~~ 51 bytes

```
~~juXGhHX@GhHeH@jkQ~hZ{s[+L]0UhQ+R]thQUeQ+L]teQ_UhQ+R]0_UeQ)m*;hQeQ~~
AQjuXGhHX@GhHeH@jkQ~hZ{s[,L0G,RtGH_,LtHG_,R0H)m*;GH

```

Try it online!

# Answer
> 4 votes
## C#, 301 bytes

I'm sure there is a lot more golfing that can be done here but I'm just happy I got a solution that worked.

I found a bug where the bottom line was in the wrong order, damnit!

```
a=>b=>{var s=new string[b];int i=4,c=b-2,k=a;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");for(;--k>=0;)s[b-1]+=t.Substring(a+c,a)[k];}return s;};

```

Old version: 280 bytes

```
a=>b=>{var s=new string[b];int i=4,c=b-2;var t="";for(;i++<2*(a+b);)t+=t.EndsWith(a+"")?b:a;s[0]=t.Substring(0,a);if(b>2){for(i=0;++i<b-1;)s[i]=(a<2?t.Substring(1,c):t.Substring(2*a+c))[c-i]+(a>1?new string(' ',a-2)+t.Substring(a,c)[i-1]:"");s[b-1]=t.Substring(a+c,a);}return s;};

```

# Answer
> 2 votes
# Python 2, 199 bytes

```
w,h=input()
s=(`w`+`h`)*w*h
r=[s[:w]]+[[" "for i in[0]*w]for j in[0]*(h-2)]+[s[w+h-2:2*w+h-2][::-1]]*(h>1)
for y in range(1,h-1):r[y][w-1],r[y][0]=s[w+y-1],s[w+h+w-2-y]
print"\n".join(map("".join,r))

```

# Answer
> 2 votes
# JavaScript, ~~213~~ ~~212~~ 202

```
c=>a=>{for(a=$=a,c=_=c,l=c*a*2,b=0,s=Array(l+1).join(c+""+a),O=W=s.substr(0,a),W=W.substr(0,a-2).replace(/./g," ");--_;)O+="\n"+s[l-c+_]+W+s[$++];return O+"\n"+[...s.substr(l-a-c+1,a)].reverse().join``}

```

Surely has room for improvement.

**Edit:** Saved a byte thanks to TheLethalCoder

# Answer
> 2 votes
# Ruby, 128 bytes

```
->w,h{s="%d%d"%[w,h]*q=w+h;a=[s[0,w]];(h-2).times{|i|a<<(s[2*q-5-i].ljust(w-1)+s[w+i,1])[-w,w]};puts a,h>1?(s[q-2,w].reverse):p}

```

Outputs trailing newline if height is 1.

Ideone link: https://ideone.com/96WYHt

# Answer
> 2 votes
# C, 311 bytes

```
char s[5];sprintf(s,"%d%d",a, b);int z=strlen(s);int i=0;while(i<a){printf("%c",s[i++%z]);}if(b>2){i=1;while(i<b-1){char r=s[(a+i-1)%z];char l=s[(2*a+2*b-i-4)%z];if(a>1){printf("\n%c%*c",l,a-1,r);}else{printf("\n%c",l);}i++;}}printf("\n");if(b>1){i=0;while(i<a){printf("%c",s[(2*a+b-i-3)%z]);i++;}printf("\n");}

```

Uses automatically included libraries `stdio.h` and `string.h`.

# Answer
> 2 votes
## JavaScript (ES6), 171 bytes

```
(w,h)=>[...Array(h)].map((_,i)=>i?++i<h?(w>1?s[p+p+1-i]+` `.repeat(w-2):``)+s[w+i-2]:[...s.substr(p,w)].reverse().join``:s.slice(0,w),s=`${w}${h}`.repeat(p=w+h-2)).join`\n`

```

Where `\n` represents the literal newline character. Creates a repeated digit string, then decides what to concatenate based on which row we're on; top row is just the initial slice of the repeated digit string, bottom row (if any) is a reversed slice from the middle of the string, while intervening rows are built up using characters taken from other parts of the string.

# Answer
> 0 votes
# TSQL, 291 bytes

**Golfed:**

```
DECLARE @ INT=5,@2 INT=4

,@t INT,@z varchar(max)SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)v:PRINT iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)+isnull(space(@-2)+left(@z,1),''),reverse(@z)))SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))IF @<=len(@z)goto v

```

**Ungolfed:**

```
DECLARE @ INT=5,@2 INT=4

,@t INT,@z varchar(max)
SELECT @t=iif(@*@2=1,1,(@+@2)*2-4),@z=left(replicate(concat(@,@2),99),@t)

v:
  PRINT
    iif(len(@z)=@t,left(@z,@),iif(len(@z)>@,right(@z,1)
      +isnull(space(@-2)+left(@z,1),''),reverse(@z)))
  SET @z=iif(len(@z)=@t,stuff(@z,1,@,''),substring(@z,2,abs(len(@z)-2)))
IF @<=len(@z)goto v

```

**Fiddle**

# Answer
> 0 votes
# Python 3, ~~155~~ 148 bytes

Golfed off 7 more bytes:

```
p=print
def f(w,h):
 s=((str(w)+str(h))*w*h)[:2*w+2*h-4or 1];p(s[:w])
 for i in range(h-2):p(['',s[-i-1]][w>1]+' '*(w-2)+s[w+i])
 p(s[1-h:1-h-w:-1])

```

Substituted `2*w+2*h-4or 1` for `max(1,2*w+2*h-4)` and `['',s[-i-1]][w>1]` for `(s[-i-1]if w>1else'')`.

Prior version:

```
p=print
def f(w,h):
 s=((str(w)+str(h))*w*h)[:max(1,2*w+2*h-4)];p(s[:w])
 for i in range(h-2):p((s[-i-1]if w>1else'')+' '*(w-2)+s[w+i])
 p(s[1-h:1-h-w:-1])

```

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


title: Number Plate Golf: Recognition

text:
# Question
Title: Number Plate Golf: Recognition
**See also: Parsing**

## Introduction

You're working on a government programming team, who have been programming the speed cameras. However, the group of people who have programmed the speed calculator have taken up too much space, so you have to make the number plate recognition software as small as possible.

## Challenge

Given an image of a number plate, return the text on the plate.

## Number plates

The following are all of the characters which your program must recognise:

### ABCDEFG

### H1JKLMN0

### PQRSTUVW

### XYZ01234

### 56789

### Note

On British number plates, the characters for I (i) and 1 (one) are the same and the characters for O (o) and 0 (zero) are the same. For that reason, always assume characters are the numbers. I.e. the following number plate is 10 (one zero):

## Examples

### C0D3 GLF

### B3T4 DCY

### M1NUS 15

### YET1CGN

## Other rules

Internet access and OCR libraries and functions are disallowed.

The number plates will always look identical to the ones shown above. All number plates will be roughly same size (there will be some inaccuracies due to cropping method).

If you require lossless PNG versions of any number plates, I will supply them to you.

## Scoring

The shortest program in bytes wins.

<sub>**All number plates are screenshots of the search bar at this site**</sub>

# Answer
# C, 409 bytes (and I'm as surprised as anybody)

```
f(w,h,d,X,T,B,x,y,b,v,u,t,a)char*d;{for(x=X=0;++x<w;){for(y=b=h;y--;a=0)d[(y*w+x)*3+1]&224||(b=0,X||(X=x,T=B=y),T=y<T?y:T,B=y>B?y:B);if(X*b){for(B+=1-T,X=x-X,v=5;v--;)for(u=4;u--;a|=(b>X/4*(B/5)*.35)<<19-u*5-v)for(b=0,t=X/4;t--;)for(y=B/5;y--;)b+=!(d[((v*B/5+y+T)*w+x-X+u*X/4+t)*3+1]&224);X=!putchar("g------a----mj---et-u--6----7--8s4-c-x--q--d9xy5-0v--n-2-hw-k-----3---bf-----t-r---pzn-1---l"[a%101-7]);}}}

```

Takes as input: the width (`w`) and height (`h`) of the image, followed by the packed RGB data as an array of `char`s (`d`). All the other function parameters are variable declarations in disguise. Ignores everything except the green channel, and applies a threshold of 32 as an initial pass.

Mostly the same as @DavidC's method, except this checks that at least 35% of each sample box is filled. Hopefully that makes it more robust to scale changes, but who knows.

I used a brute-force method to find out which resampling size and coverage percent to use for the best reliability (i.e. fewest cases of one character having multiple interpretations). It turned out that a 4x5 grid with 35% coverage was best. I then used a second brute-force method to calculate the best bit arrangement and modulo value to pack the character data into a short string — the low bit at the top-left, increasing in x then y, with the final value % 101 turned out best, giving this lookup table:

```
-------g------a----mj---et-u--6----7--8s4-c-x--q--d9xy5-0v--n-2-hw-k-----3---bf-----t-r---pzn-1---l--

```

Subtracting 7 means the initial -'s can be removed, and the last 2 can be removed without any extra work. This removal means that certain invalid inputs could cause an invalid memory read, so it could segfault on particular images.

### Usage:

To get the images into it, I wrote a wrapper using libpng. Also it turns out that despite the filename, the images in the question are actually jpegs (!), so you'll need to manually export them as pngs first.

```
#include <png.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, const char *const *argv) {
    if(argc < 2) {
        fprintf(stderr, "Usage: %s <file.png>\n", argv[0]);
        return 1;
    }

    const char *file = argv[1];

    FILE *const fp = fopen(file, "rb");
    if(fp == NULL) {
        fprintf(stderr, "Failed to open %s for reading\n", file);
        return 1;
    }

    png_structp png_ptr = png_create_read_struct(
        PNG_LIBPNG_VER_STRING, NULL, NULL, NULL
    );

    if(!png_ptr) {
        fclose(fp);
        fprintf(stderr, "Failed to initialise LibPNG (A)\n");
        return 1;
    }

    png_infop info_ptr = png_create_info_struct(png_ptr);

    if(!info_ptr) {
        png_destroy_read_struct(&png_ptr, NULL, NULL);
        fclose(fp);
        fprintf(stderr, "Failed to initialise LibPNG (B)\n");
        return 1;
    }

    if(setjmp(png_jmpbuf(png_ptr))) {
        png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
        fclose(fp);
        fprintf(stderr, "Error while reading PNG\n");
        return 1;
    }

    png_init_io(png_ptr, fp);
    png_set_sig_bytes(png_ptr, 0);

    png_read_png(
        png_ptr, info_ptr,
        PNG_TRANSFORM_STRIP_16 |
        PNG_TRANSFORM_GRAY_TO_RGB |
        PNG_TRANSFORM_STRIP_ALPHA,
        NULL
    );
    const png_bytep *const rows = png_get_rows(png_ptr, info_ptr);
    const int w = png_get_image_width(png_ptr, info_ptr);
    const int h = png_get_image_height(png_ptr, info_ptr);
    unsigned char *const data = malloc(w*h*3 * sizeof(unsigned char));
    for(int y = 0; y < h; ++ y) {
        for(int x = 0; x < w; ++ x) {
            memcpy(&data[y*w*3], rows[y], w * 3 * sizeof(unsigned char));
        }
    }
    png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
    fclose(fp);

    f(w, h, (char*) data);

    free(data);

    return 0;
}

```

### Breakdown

```
f(                          // Function
    w,h,d,                  // Parameters: width, height, RGB data
    X,T,B,x,y,b,v,u,t,a     // Variables
)char*d;{                   // K&R syntax to save lots of type decls
  for(x=X=0;++x<w;){        // Loop through each column of the image:
    for(y=b=h;y--;a=0)      //  Loop through pixels in column:
      d[(y*w+x)*3+1]&224||( //   If green < 32: (char could be signed or unsigned)
        b=0,                //    This is not a blank line
        X||(X=x,T=B=y),     //    Start a new character if not already in one
        T=y<T?y:T,          //    Record top of character
        B=y>B?y:B           //    Record bottom of character
      );
    if(X*b){                //  If we just found the end of a character:
      // Check cell grid & record bits into "a"
      for(B+=1-T,X=x-X,v=5;v--;)
        for(u=4;u--;a|=(b>X/4*(B/5)*.35)<<19-u*5-v)
          // Calculate coverage of current cell
          for(b=0,t=X/4;t--;)
            for(y=B/5;y--;)
              b+=!(d[((v*B/5+y+T)*w+x-X+u*X/4+t)*3+1]&224);

      // Look up meaning of "a" in table & print, reset X to 0
      X=!putchar(
        "g------a----mj---et-u--6----7--8s4-c-x--q--d9x"
        "y5-0v--n-2-hw-k-----3---bf-----t-r---pzn-1---l"
        [a%101-7]
      );
    }
  }
}

```
> 11 votes

# Answer
# Mathematica ~~1170 1270 1096 1059 650 528 570 551 525~~ 498 bytes

The latest version saves 27 bytes by not requiring that the plate be "trimmed" before it is parsed. The penultimate version saved 26 bytes by using only 10 of the original 24 sample points.

```
z=Partition;h@i_:=i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@z[{45,99,27,81,63,81,9,63,45,63,9,45,45,45,63,45,45,27,45,9},2];f@p_:=h/@SortBy[Select[p~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},100<Last@ImageDimensions@#[[2,1]]<120&],#[[2,2,1]]&][[All,2,1]]/.Thread[IntegerDigits[#,2,10]&/@(z[IntegerDigits[Subscript["ekqeuiv5pa5rsebjlic4i5886qsmvy34z5vu4e7nlg9qqe3g0p8hcioom6qrrkzv4k7c9fdc3shsm1cij7jrluo", "36"]],4]/.{a__Integer}:> FromDigits[{a}])-> Characters@"BD54TARP89Q0723Z6EFGCSWMNVYXHUJKL1"]

```

---

122 bytes saved through LegionMammal978's idea of packing the long list of base 10 numbers as a single, base 36 number. He pared another 20 bytes off the final code.

The jump from 528 to 570 bytes was due to additional code to ensure that the order of the letters returned corresponded to the order of the letters on the license plate. The centroid for each letter contains the x-coordinate, which reveals the relative positions of the letters along x.

---

**Ungolfed Code**

```
coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1];
h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :>  ⌈z⌉  & /@ coordinates, {6, 4}];
plateCrop[img_]:=ColorReplace[ImageTrim[img,{{100,53},{830,160}}],Yellow];
codes={{{15,13,15,13,13,15},"B"},{{15,8,8,8,9,15},"C"},{{15,13,13,13,13,15},"D"},{{15,8,14,8,8,15},"E"},{{15,8,14,8,8,8},"F"},{{15,8,8,11,9,15},"G"},{{6,6,6,6,15,9},"A"},{{9,9,15,15,9,9},"H"},{{8,8,8,8,8,15},"L"},{{9,15,15,15,13,9},"M"},{{15,9,9,9,9,15},"0"},{{9,10,12,14,10,9},"K"},{{9,13,13,11,11,9},"N"},{{8,8,8,8,8,8},"1"},{{1,1,1,1,9,15},"J"},{{15,9,15,14,8,8},"P"},{{15,9,9,9,15,15},"Q"},{{15,9,15,14,10,11},"R"},{{15,8,12,3,1,15},"S"},{{9,15,6,6,6,6},"V"},{{15,6,6,6,6,6},"T"},{{9,15,15,15,15,15},"W"},{{9,9,9,9,9,15},"U"},{{9,14,6,6,14,9},"X"},{{9,14,6,6,6,6},"Y"},{{15,3,2,4,12,15},"Z"},{{15,9,9,9,9,15},"0"},{{8,8,8,8,8,8},"1"},{{15,1,3,6,12,15},"2"},{{15,1,3,1,9,15},"3"},{{2,6,6,15,2,2},"4"},{{7,12,14,1,1,15},"5"},{{15,8,14,9,9,15},"6"},{{15,1,2,2,6,4},"7"},{{15,9,15,9,9,15},"8"},{{15,9,15,1,9,15},"9"}};
decryptRules=Rule@@@codes;
isolateLetters[img_]:=SortBy[Select[ComponentMeasurements[plateCrop[img],{"Image","Centroid"}],ImageDimensions[#[[2,1]]][[2]]>100&],#[[2,2,1]]&][[All,2,1]]
f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolateLetters[plate]/.decryptRules

```

**Overview**

The basic idea is to check whether a systematic sampling of pixels from the input image matches pixels from the same location on the bonafide images. Much of the code consists of the bit signatures for each character,

The diagram shows the pixels that are sampled from the letters "J", "P","Q", and "R".

The pixel values can be represented as matrices. The dark, bold `1`'s correspond to black cells. The `0`'s correspond to white cells.

These are the decryption replacement rules for J P Q R.

{1, 1, 1, 1, 9, 15} -\> "J",
{15, 9, 15, 14, 8, 8} -\> "P",
{15, 9, 9, 9, 15, 15} -\> "Q",
{15, 9, 15, 14, 10, 11} -\> "R"

It should be possible to understand why the rule for "0" is:

{15, 9, 9, 9, 9, 15} -\> "0"

and thus distinguishable from the letter "Q".

---

The following shows the 10 points used in the final version. These points are sufficient for identifying all of the characters.

---

**What the functions do**

`plateCrop[img]` removes the frame and left edge from the plate, makes the background white. I was able to eliminate this function from the final version by selecting image components, possible letters that were between 100 and 120 pixels high.

---

`isolateLetters[img]` removes the individual letters from the cropped image.

We can display how it works by showing where the cropped image, output from `plateCrop` goes as input for `isolateLetters`. The output is a *list* of individual characters.

---

`Coordinates` are 24 evenly distributed positions for checking the pixel color. The coordinates correspond to those in the first figure.

```
coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1];

```

{{9, 99}, {27, 99}, {45, 99}, {63, 99}, {9, 81}, {27, 81}, {45, 81}, {63, 81}, {9, 63}, {27, 63}, {45, 63}, {63, 63}, {9, 45}, {27, 45}, {45, 45}, {63, 45}, {9, 27}, {27, 27}, {45, 27}, {63, 27}, {9, 9}, {27, 9}, {45, 9}, {63, 9}}

---

`h` converts the pixels to binary.

```
h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :>  ⌈z⌉  & /@ coordinates, {6, 4}];

```

---

`codes` are the signature for each character. The decimal values are abbreviations of the binary code for black (0) and White (1) cells. In the golfed version, base 36 is used.

```
codes={{{15, 9, 9, 9, 9, 15}, "0"}, {{8, 8, 8, 8, 8, 8}, "1"}, {{15, 1, 3,6,12, 15}, "2"}, {{15, 1, 3, 1, 9, 15}, "3"}, {{2, 6, 6, 15, 2, 2}, "4"}, {{7, 12, 14, 1, 1, 15},"5"}, {{15, 8, 14, 9, 9, 15}, "6"}, {{15, 1, 2, 2, 6, 4},"7"}, {{15, 9, 15, 9, 9, 15}, "8"}, {{15, 9, 15, 1, 9, 15},"9"}, {{6, 6, 6, 6, 15, 9}, "A"}, {{15, 13, 15, 13, 13, 15}, "B"}, {{15, 8, 8, 8, 9, 15}, "C"}, {{15, 13, 13, 13, 13, 15}, "D"}, {{15, 8, 14, 8, 8, 15}, "E"}, {{15, 8, 14, 8, 8, 8},"F"}, {{15, 8, 8, 11, 9, 15}, "G"}, {{9, 9, 15, 15, 9, 9}, "H"}, {{1, 1, 1, 1, 9, 15}, "J"}, {{9, 10, 12, 14, 10, 9}, "K"}, {{8, 8, 8, 8, 8, 15}, "L"}, {{9, 15, 15, 15, 13, 9}, "M"}, {{9, 13, 13, 11, 11, 9}, "N"}, {{15, 9, 15, 14, 8, 8}, "P"}, {{15, 9, 9, 9, 15, 15}, "Q"}, {{15, 9, 15, 14, 10, 11}, "R"}, {{15, 8, 12, 3, 1, 15}, "S"}, {{15, 6, 6, 6, 6, 6}, "T"}, {{9, 9, 9, 9, 9, 15}, "U"}, {{9, 15, 6, 6, 6, 6}, "V"}, {{9, 15, 15, 15, 15, 15}, "W"}, {{9, 14, 6, 6, 14, 9}, "X"}, {{9, 14, 6, 6, 6, 6}, "Y"}, {{15, 3, 2, 4, 12, 15}, "Z"}};

```

(\* `decryptRules` are for replacing signatures with their respective character \*)

```
decryptRules=Rule@@@codes;

```

`f` is the function that takes an image of a license plate and returns a letter.

```
f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolate[plateCrop@plate]/.decryptRules;

```

{"A", "B", "C", "D", "E", "F", "G"}
{"H", "1", "J", "K", "L", "M", "N", "0"}
{"P", "Q", "R", "S", "T", "U", "V", "W"}
{"X", "Y", "Z", "0", "1", "2", "3", "4"}
{"5", "6", "7", "8", "9"}

---

## Golfed

The code is shortened by using a single decimal number to represent all 24 bits (white or black) for each character. For example, the letter "J" uses the following replacement rule: `1118623 -> "J"`.

1118623 corresponds to

```
IntegerDigits[1118623 , 2, 24]

```

{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1}

which can be repackaged as

```
ArrayReshape[{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1}, {6, 4}]

```

{{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {1, 0, 0, 1}, {1, 1, 1, 1}}

which is simply the matrix for "J" that we saw above.

```
%//MatrixForm

```

Another savings comes from representing the alphabet as `"0123456789ABCDEFGHJKLMNPQRSTUVWXYZ"` rather than as a list of letters.

Finally, all of the functions from the long version, except `h`, were integrated into the function `f` rather than defined separately.

---

```
h@i_:=ArrayReshape[i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@Join@@Table[{x,y},{y,99,0,-18},{x,9,72,18}],{6,4}];f@p_:=#~FromDigits~2&/@(Join@@@h/@SortBy[Select[p~ImageTrim~{{100,53},{830,160}}~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},Last@ImageDimensions@#[[2,1]]>100&],#[[2,2,1]]&][[;;,2,1]])/.Thread[IntegerDigits[36^^1c01agxiuxom9ds3c3cskcp0esglxf68g235g1d27jethy2e1lbttwk1xj6yf590oin0ny1r45wc1i6yu68zxnm2jnb8vkkjc5yu06t05l0xnqhw9oi2lwvzd5f6lsvsb4izs1kse3xvx694zwxz007pnj8f6n,8^8]->Characters@"J4A51LUHKNYXVMW732ZTCGSFE60Q98PRDB"]

```
> 11 votes

# Answer
## C#, ~~1040~~ 1027 bytes

```
using System;using System.Drawing;class _{static Bitmap i;static bool b(int x,int y)=>i.GetPixel(x,y).GetBrightness()<.4;static char l(int x,int y){if(y<45)return b(x+5,145)?((b(x+30,100)||b(x+30,50))?(b(x+68,94)?(b(x+40,50)?'D':b(x+40,120)?(b(x+45,80)?'M':'N'):'H'):b(x,97)?(b(x+30,140)?'E':b(x+60,70)?(b(x+50,140)?'R':'P'):'F'):b(x+65,45)?(b(x+5,100)?'K':b(x+30,145)?'Z':'X'):'B'):b(x+30,140)?'L':'1'):b(x+30,55)?(b(x+60,70)?'7':'T'):b(x+2,100)?'U':b(x+30,70)?'W':b(x+15,100)?'V':'Y';if(y<70)return b(x+50,110)?(b(x+50,70)?(b(x+10,110)?(b(x+30,100)?(b(x+55,80)?'8':'6'):b(x+55,80)?'0':'G'):b(x+10,70)?(b(x+60,80)?'9':'S'):b(x+60,120)?'3':'2'):'G'):b(x+30,125)?'Q':'C';if(y>150)return'A';if(y>120)return'J';else return b(x+10,135)?'5':'4';}static void Main(string[]z){i=new Bitmap(Console.ReadLine());bool s=true;int w=int.MinValue;for(int x=100;x<800;++x){for(int y=40;y<160;++y)if(s){if(b(x,y)){if(w>50)Console.Write(' ');Console.Write(l(x,y));s=false;goto e;}}else if(b(x,y))goto e;if(!s){s=true;w=0;}else++w;e:continue;}}}

```

Ungolfed:

```
using System;
using System.Drawing;

class _
{
    static Bitmap bmp;
    static bool b(int x, int y) => bmp.GetPixel(x, y).GetBrightness() < .4;
    static char l(int x, int y)
    {
        if (y < 45)
            return b(x + 5, 145) ? ((b(x + 30, 100) || b(x + 30, 50)) ? (b(x + 68, 94) ? (b(x + 40, 50) ? 'D' : b(x + 40, 120) ? (b(x + 45, 80) ? 'M' : 'N') : 'H') : b(x, 97) ? (b(x + 30, 140) ? 'E' : b(x + 60, 70) ? (b(x + 50, 140) ? 'R' : 'P') : 'F') : b(x + 65, 45) ? (b(x + 5, 100) ? 'K' : b(x + 30, 145) ? 'Z' : 'X') : 'B') : b(x + 30, 140) ? 'L' : '1') : b(x + 30, 55) ? (b(x + 60, 70) ? '7' : 'T') : b(x + 2, 100) ? 'U' : b(x + 30, 70) ? 'W' : b(x + 15, 100) ? 'V' : 'Y';
        if (y < 70)
            return b(x + 50, 110) ? (b(x + 50, 70) ? (b(x + 10, 110) ? (b(x + 30, 100) ? (b(x + 55, 80) ? '8' : '6') : b(x + 55, 80) ? '0' : 'G') : b(x + 10, 70) ? (b(x + 60, 80) ? '9' : 'S') : b(x + 60, 120) ? '3' : '2') : 'G') : b(x + 30, 125) ? 'Q' : 'C';
        if (y > 150)
            return 'A';
        if (y > 120)
            return 'J';
        if (y > 95)
            return b(x + 10, 135) ? '5' : '4';
        return '-';
    }
    static void Main(string[] args)
    {
        bmp = new Bitmap(Console.ReadLine());
        bool state = true;
        int space = int.MinValue;
        for (int x = 100; x < 800; ++x)
        {
            for (int y = 40; y < 160; ++y)
                if (state)
                {
                    if (b(x, y))
                    {
                        if (space > 50)
                            Console.Write(' ');
                        Console.Write(l(x, y));
                        state = false;
                        goto bad;
                    }
                }
                else if (b(x, y))
                    goto bad;
            if (!state)
            {
                state = true;
                space = 0;
            }
            else
                ++space;
            bad:
            continue;
        }
    }
}

```

Basically I found some specific reference points to check yellow/black to determine the identity of each character.
> 4 votes

# Answer
# PHP – ~~1741~~ ~~1674~~ 1143 bytes

It was first set up by learning the profiles of the characters from the first few examples, which then summarized each character into six numbers. I chose six because I originally had five, and it didn't work as great as I'd like, but six seems to work much better. Much of the optimization involves squeezing these profiles into smaller and smaller byte counts.

The first and second profile `*lhdfdn` and `|nnmmkk` are actually the blue blob with "GB" at the bottom `*`, and the right border `|`, which we're ignoring. It's safer to include them so that the blob and right border have something to match against.

Should handle any image format, any reasonable scaling provided the aspect ratio doesn't change too much, any dark on light color, and even a bit of noise and shading!

It does need the border, at least at the top and bottom, that's part of the profile.

```
<?php $X=[];foreach(str_split('*lhdfdn|nnmmkkA<njjk;BOnKB`^Chn::E7DHn?1X`EnkGGD4Fn_330!Gnj9G[IHnX!!XnJ%(##knKnX.EN6LnX!!!!Mn_<:bnNn^77_nPn^33@6QhfBDjnRn_8LaDSOlYYnUT$$nn$$Uh_##^nV9c][n;W_nWTlhXHnLTiCY4LhnM5ZJbnmaI0ng88lk1nnnnnn2C[__n`34B?Kna4+=Fnb"5NnUReX6gnKKaM7*4Xnb=8gkIIne9K`KKni',7)as$s){$t=[];foreach(str_split(substr($s,1))as$u)$t[]=ord($u)-11;$X[$s[0]]=$t;}echo m(r($argv[1]),$X)."\n";function r($u){$a=[];$i=imagecreatefromstring(file_get_contents($u));$w=imagesx($i);$h=imagesy($i);$s=[];for($x=0;$x<$w;$x++){$s[$x]=0;for($y=0;$y<$h;$y++){$p=imagecolorsforindex($i,imagecolorat($i,$x,$y));if(3*$p['red']+6*$p['green']+$p['blue']<1280)$s[$x]++;}}$j=0;$k=[];for($x=0;$x<$w;$x++){if($s[$x]>$h/10)for($o=0;$o<6;$o++)$k[]=$s[$x];elseif(count($k)){$a[]=$k;$j++;$k=[];}}$b=[];foreach($a as$v){$t=[];$u=array_chunk($v,intval(count($v)/6));foreach($u as$c)$t[]=array_sum($c)/count($c);$m=99/max($t);$e=[];foreach($t as$x)$e[]=intval($x*$m+0.5);$b[]=$e;}return$b;}function m($A,$X){$r='';foreach($A as$a){$s=INF;$c='';foreach($X as$k=>$x){$t=0;for($i=0;$i<6;$i++)$t+=pow($a[$i]-$x[$i],2);if($s>$t){$s=$t;$c=$k;}}$r.=$c;}return trim($r,'|*');}

```

Save as `ocr.php`, then run from the command line:

```
$ php ocr.php http://i.imgur.com/UfI63md.png
ABCDEFG

$ php ocr.php http://i.imgur.com/oSAK7dy.png
H1JKLMN0

$ php ocr.php http://i.imgur.com/inuIHjm.png
PQRSTUVW

$ php ocr.php http://i.imgur.com/Th0QkhT.png
XYZ01234

$ php ocr.php http://i.imgur.com/igH3ZPQ.png
56789

$ php ocr.php http://i.imgur.com/YfVwebo.png
10

$ php ocr.php http://i.imgur.com/3ibQARb.png
C0D3GLF

$ php ocr.php http://i.imgur.com/c7XZqhL.png
B3T4DCY

$ php ocr.php http://i.imgur.com/ysBgXhn.png
M1NUS15

```

For those that are interested, here is the learning code. Save as `learn.php` and run from the command line, no arguments.

```
<?php

define('BANDS', 6);

main();

function main()
{
    $glyphs = [];

    learn($glyphs, 'http://imgur.com/UfI63md.png', '*ABCDEFG|');
    learn($glyphs, 'http://imgur.com/oSAK7dy.png', '*H1JKLMN0|');
    learn($glyphs, 'http://imgur.com/inuIHjm.png', '*PQRSTUVW|');
    learn($glyphs, 'http://imgur.com/Th0QkhT.png', '*XYZ01234|');
    learn($glyphs, 'http://imgur.com/igH3ZPQ.png', '*56789|');

    $profiles = summarize($glyphs);

    foreach ($profiles as $glyph=>$profile)
    {
        print $glyph;
        foreach ($profile as $value)
            print chr($value + 11);
        print "\n";
    }
}

function learn(&$glyphs, $url, $answer)
{
    $image = imagecreatefromstring(file_get_contents($url));
    $width = imagesx($image);
    $height = imagesy($image);
    $counts = [];
    for ($x = 0; $x < $width; $x++)
    {
        $counts[$x] = 0;
        for ($y = 0; $y < $height; $y++)
        {
            $pixel = imagecolorsforindex($image, imagecolorat($image, $x, $y));
            if (3 * $pixel['red'] + 6 * $pixel['green'] + $pixel['blue'] < 1280)
                $counts[$x]++;
        }
    }

    $index = 0;
    $expanded = [];
    for ($x = 0; $x < $width; $x++)
    {
        if ($counts[$x] > $height / 10)
            for ($inner = 0; $inner < BANDS; $inner++)
                $expanded[] = $counts[$x];
        else if (count($expanded)) {
            $glyphs[$answer[$index]] = $expanded;
            $index++;
            $expanded = [];
        }
    }
}

function summarize($glyphs)
{
    $profiles = [];
    foreach ($glyphs as $glyph=>$expanded)
    {
        $averages = [];
        $bands = array_chunk($expanded, count($expanded) / BANDS);
        foreach ($bands as $band)
            $averages[] = array_sum($band) / count($band);
        $scaling = 99 / max($averages);
        $profile = [];
        foreach ($averages as $average)
            $profile[] = intval($average * $scaling + 0.5);
        $profiles[$glyph] = $profile;
    }
    return $profiles;
}

?>

```
> 2 votes

# Answer
# PHP, ~~971~~ 970 bytes

Draws heavily upon Yimin Rong's answer, which can be seriously golfed down, especially the array indices, and put into a Phar with gzip compression.

Download the phar

This is my improved base version at ~~1557~~ 1535 bytes, saved simply under the filename "o":

```
<?$X=[[99,92,45,45,97,96],[99,99,99,99,99,99],[56,80,84,84,99,85],[41,55,52,64,99,86],[32,50,59,99,87,23],[67,99,74,71,90,77],[92,99,64,64,86,66],[31,41,77,99,87,50],[92,96,62,62,99,90],[64,85,64,64,99,94],''=>[99,99,98,98,96,96],A=>[49,99,95,95,96,48],B=>[68,99,64,55,85,83],C=>[93,99,47,47,58,44],D=>[61,99,52,38,77,85],E=>[99,96,60,60,57,41],F=>[99,84,40,40,37,22],G=>[99,95,46,60,80,62],H=>[99,77,22,22,77,99],1=>[99,99,99,99,99,99],J=>[26,29,24,24,96,99],K=>[99,77,35,58,67,43],L=>[99,77,22,22,22,22],M=>[99,84,49,47,87,99],N=>[99,83,44,44,84,99],P=>[99,83,40,40,53,43],Q=>[93,91,55,57,95,99],R=>[99,84,45,65,86,57],S=>[68,97,78,78,99,74],T=>[25,25,99,99,25,25],U=>[93,84,24,24,83,99],V=>[46,88,82,80,99,48],W=>[84,99,76,73,97,93],X=>[61,99,65,73,94,56],Y=>[41,65,93,99,66,42],Z=>[63,87,99,98,86,62]];echo m(r($argv[1]),$X);function r($u){$a=[];$i=imagecreatefromstring(join('',file($u)));$w=imagesx($i);$h=imagesy($i);$s=[];for(;$x<$w;$x++){$s[$x]=0;for($y=0;$y<$h;$y++){$p=imagecolorsforindex($i,imagecolorat($i,$x,$y));if(3*$p[red]+6*$p[green]+$p[blue]<1280)$s[$x]++;}}$j=0;$k=[];for(;$z<$w;$z++){if($s[$z]>$h/10)for($o=0;$o<6;$o++)$k[]=$s[$z];elseif(count($k)){$a[]=$k;$j++;$k=[];}}$b=[];foreach($a as$v){$t=[];$u=array_chunk($v,~~(count($v)/6));foreach($u as$c)$t[]=array_sum($c)/count($c);$m=99/max($t);$e=[];foreach($t as$x)$e[]=~~($x*$m+.5);$b[]=$e;}return$b;}function m($A,$X){$r='';foreach($A as$a){$s=INF;$c='';foreach($X as$k=>$x){$t=0;for($i=0;$i<6;)$t+=($a[$i]-$x[$i++])**2;if($s>$t){$s=$t;$c=$k;}}$r.=$c;}return$r;}

```

## Improvements:

1st stage

* Numeric array indices removed and reordered the array, string indices as implicit constants

2nd stage

* Replaced `intval` with `~~` (saves 8 bytes, two occurences)
* for-loop initialization removed where unnecessary
* `file_get_contents($u)` replaced with `join('',file($u))` (saves 5 bytes)
* and a few others

Unfortunately, all the second stage improvements only translate into 1 byte less gzipped code. :-D

And this code was used to create the Phar:

```
<?php
$phar = new Phar('o.phar');
$phar->addFile('o');
$phar['o']->compress(Phar::GZ);
$phar->setStub('<?Phar::mapPhar(o.phar);include"phar://o.phar/o";__HALT_COMPILER();');

```

Test with `php ocr.phar http://i.imgur.com/i8jkCJu.png` or any other of the test case images.
> 0 votes

---
Tags: code-golf, image-processing, optical-char-recognition
---


# Question
Title: Javascript tips: 2 to the power of x multiplied by n
I'm new to ES6 and code-golfing. Here's the original function:

```
function puzzle(n, x) {
  return n * Math.pow(2, x);
}
```

And here's what I have so far:

```
let puzzle=(n,x)=>n*2<<(x-1)

```

But the solution requires lesser characters. I went through the 'Code Golfing with ES6' thread, but couldn't find a better way. Any help/links would be appreciated.

# Answer
> 11 votes
## 17 bytes:

```
puzzle=n=>x=>n<<x

```

This uses the fact that `2 * 2^n` = `2^(n + 1)`. Also, by our rules, using currying instead of taking multiple arguments the usual way is allowed. Also, I don't think the `let` is needed.

---
Tags: code-golf, tips, javascript
---


# Question
Title: Paint a still life (or a moving one) - draw an image in the Game of Life
You are given as input a greyscale image. Your task is to find a static or looping pattern in Conway's Game of Life that resembles the input image as closely as possible.

Your output can be *either* a still image or a looping animation in some format that can be converted to gif. The output image dimensions should be the same as the input, and it must contain only black and white pixels.

If the output is an animation, each frame must be generated from the previous one according to the Game of Life rules, with one cell per pixel. The animation must loop, with the first frame being generated from the last frame by the same rules.

If the output is a still image, applying the game-of-life rules to it must produce the same image. This means that no 'alive' cell may have more than three or less than two 'alive' neighbours, and no 'dead' cell may have exactly three 'alive' neighbours. (Note that this is basically the same as an animation as described above, but with only one frame.)

Extra rules and clarifications:

* You (or your program) may choose whether 'alive' cells are represented as white and 'dead' as black, or vice versa. That is, you can either hard-code this or your program can choose it based on the input image. (But it must be the same for every frame of the animation.)
* The boundary conditions should be periodic, meaning that cells on the rightmost column have neighbours on the leftmost column, etc.
* For animations, the frame rate is up to you (or your program); I imagine fast frame rates will work well for approximating grey pixels.
* Please post at least two results embedded in your answer. If you can post results from all of the input images below, it's preferable.
* It is acceptable to scale down the test images if this is necessary in order to achieve gifs with small enough file sizes. If you want to link to larger files as well, that's fine. If you want to show off, feel free to find some higher-resolution source files.
* Please try to avoid having too many controllable parameters in your code - it's best if your program's only input is the image. The exception is if you want to have a parameter for controlling the number of animation frames, since that will affect the file size.
* You may use external programs to change the format of the input and output files, and/or compile output frames into an animation if you want. (This is not a file-format-handling challenge.)
* This is , so the answer with the most votes wins.

Here is a selection of test images, mostly taken from other questions on this site. (It's possible that I will add additional "bonus" input images later.)

Just to get things started, here's a very dumb reference attempt in Python 2, which takes advantage of the fact that a block of four squares is a stable structure in the Game of Life. It just rescales the input image by a factor of 4, then draws a block if the corresponding pixel is darker than 0.5.

```
from skimage import io
from skimage import transform
import sys

img = io.imread(sys.argv[1],as_grey=True)

source = transform.resize(img, [i/4 for i in img.shape])

img[:]=1
for x in xrange(source.shape[0]):
    for y in xrange(source.shape[1]):
        if source[x,y]<0.5:
            img[x*4, y*4] = 0
            img[x*4+1, y*4] = 0
            img[x*4, y*4+1] = 0
            img[x*4+1, y*4+1] = 0

io.imsave(sys.argv[2], img)

```

Here are some outputs from the example code. I'm sure that *much* better results are possible.

# Answer
# Python

```
import sys, random, itertools
from PIL import Image

filename, cutoff = sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 128

# load command-line arg as image
src = Image.open(sys.argv[1]).convert("L") # grayscale
(w, h), src = src.size, src.load()
# flatten
src = bytearray(src[x, y] for y in range(h) for x in range(w))
size = len(src)
neighbour_offsets = (-w-1,-w,-w+1,-1,1,w-1,w,w+1)

shapes = set()
max_shape_x, max_shape_y = 0, 0
for shape in (((1, 1), (1, 1), "b"), # block
    ((0,1,1,0),(1,0,0,1),(0,1,1,0), "h"), # hive
    ((0,0,1,0),(0,1,0,1),(1,0,0,1),(0,1,1,0), "l"), # loaf
    ((0,1,0),(1,0,1),(0,1,0), "t"), # tub
    ((1,1,0),(1,0,1),(0,1,0), "B"), # boat
    ((1,1,0),(1,0,1),(0,1,1), "s"), # ship
    ((1,1,0,1,1),(0,1,0,1,0),(0,1,0,1,0),(1,1,0,1,1), "I"), # II
    ((0,0,0,1,1),(0,0,0,0,1),(0,0,0,1,0),(1,0,1,0,0),(1,1,0,0,0), "c"), # canoe sinking
    ((1,1,0,0),(1,0,0,1),(0,0,1,1), "a"), # aircraft carrier
    ((0,1,1,0,0),(1,0,0,1,0),(0,1,0,0,1),(0,0,1,1,0), "m"), # mango
    ((0,1,1,0),(1,0,0,1),(1,0,0,1),(0,1,1,0), "p"), # pond
    ((0,0,0,1,1),(0,0,1,0,1),(0,0,1,0,0),(1,0,1,0,0),(1,1,0,0,0), "i"), # integral
    ((1,1,0,1),(1,0,1,1), "S"), # snake
    ((1,1,0,0),(1,0,1,0),(0,0,1,0),(0,0,1,1), "f"), # fish hook
    ):
    X, Y = len(shape[0]), len(shape)-1
    max_shape_x, max_shape_y = max(X, max_shape_x), max(Y, max_shape_y)
    shapes.add(((X, Y), tuple(y*w+x for y in range(Y) for x in range(X) if shape[y][x]), shape[:-1], shape[-1]))
    shapes.add(((X, Y), tuple(y*w+x for y in range(Y) for x in range(X-1,-1,-1) if shape[y][x]), shape[:-1], shape[-1]))
    shapes.add(((X, Y), tuple(y*w+x for y in range(Y-1,-1,-1) for x in range(X) if shape[y][x]), shape[:-1], shape[-1]))
    shapes.add(((X, Y), tuple(y*w+x for y in range(Y-1,-1,-1) for x in range(X-1,-1,-1) if shape[y][x]), shape[:-1], shape[-1]))

def torus(i, *indices):
    if len(indices) == 1:
        return (i + indices[0]) % size
    return [(i + n) % size for n in indices]

def iter_neighbours(i):
    return torus(i, *neighbour_offsets)

def conway(src, dest):
    for i in range(size):
        alive = count_alive(src, i)
        dest[i] = (alive == 2 or alive == 3) if src[i] else (alive == 3)

def calc_score(i, set):
    return 255-src[i] if not set else src[i]

def count_alive(board, i, *also):
    alive = 0
    for j in iter_neighbours(i):
        if board[j] or (j in also):
            alive += 1
    return alive

def count_dead(board, i, *also):
    dead = 0
    for j in iter_neighbours(i):
        if (not board[j]) and (j not in also):
            dead += 1
    return dead

def iter_alive(board, i, *also):
    for j in iter_neighbours(i):
        if board[j] or (j in also):
            yield j

def iter_dead(board, i, *also):
    for j in iter_neighbours(i):
        if (not board[j]) and (j not in also):
            yield j

def check(board):
    for i in range(size):
        alive = count_alive(board, i)
        if board[i]:
            assert alive == 2 or alive == 3, "alive %d has %d neighbours %s" % (i, alive, list(iter_alive(board, i)))
        else:
            assert alive != 3, "dead %d has 3 neighbours %s" % (i, list(iter_alive(board, i)))

dest = bytearray(size)

if False:
    # turn into contrast
    for i in range(size):
        mx = max(src[i], max(src[j] for j in iter_neighbours(i)))
        mn = min(src[i], min(src[j] for j in iter_neighbours(i)))
        dest[i] = int((0.5 * src[i]) + (128 * (1 - float(src[i] - mn) / max(1, mx - mn))))
    src, dest = dest, bytearray(size)

try:
    checked, bad, score_cache = set(), set(), {}
    next = sorted((calc_score(i, True), i) for i in range(size))
    while next:
        best, best_score = None, sys.maxint
        current, next = next, []
        for at, (score, i) in enumerate(current):
            if score > cutoff:
                break
            if best and best_score < score:
                break
            if not dest[i] and not count_alive(dest, i):
                do_nothing_score = calc_score(i, False)
                clean = True
                for y in range(-max_shape_y-1, max_shape_y+2):
                    for x in range(-max_shape_x-1, max_shape_x+2):
                        if dest[torus(i, y*w+x)]:
                            clean = False
                            break
                    if not clean:
                        break
                any_ok = False
                for (X, Y), shape, mask, label in shapes:
                    for y in range(Y):
                        for x in range(X):
                            if mask[y][x]:
                                pos, ok = torus(i, -y*w-x), True
                                if (pos, label) in bad:
                                    continue
                                if clean and (pos, label) in score_cache:
                                    score = score_cache[pos, label]
                                else:
                                    paint = torus(pos, *shape)
                                    for j in paint:
                                        for k in iter_alive(dest, j, *paint):
                                            if count_alive(dest, k, *paint) not in (2, 3):
                                                ok = False
                                                break
                                        if not ok:
                                            break
                                        for k in iter_dead(dest, j, *paint):
                                            if count_alive(dest, k, *paint) == 3:
                                                ok = False
                                                break
                                        if not ok:
                                            break
                                    if ok:
                                        score = 0
                                        any_ok = True
                                        for x in range(X):
                                            for y in range(Y):
                                                score += calc_score(torus(pos, y*w+x), mask[y][x])
                                            score /= Y*X
                                        if clean:
                                            score_cache[pos, label] = score
                                    else:
                                        bad.add((pos, label))
                                if ok and best_score > score and do_nothing_score > score:
                                    best, best_score = (pos, shape, label), score
                if any_ok:
                    next.append((score, i))
        if best:
            pos, shape, label = best
            shape = torus(pos, *shape)
            sys.stdout.write(label)
            sys.stdout.flush()
            for j in shape:
                dest[j] = True
            check(dest)
            next += current[at+1:]
        else:
            break
except KeyboardInterrupt:
    pass
print

if True:
    check(dest)
    anim = False
    while dest != src:
        if anim:
            raise Exception("animation!")
        else:
            anim = True
        sys.stdout.write("x"); sys.stdout.flush()
        conway(dest, src)
        dest, src = src, dest
        check(dest)

# canvas
out = Image.new("1", (w, h))
out.putdata([not i for i in dest])

# tk UI
Tkinter = None
try:
    import Tkinter
    from PIL import ImageTk
    root = Tkinter.Tk()
    root.bind("<Button>", lambda event: event.widget.quit())
    root.geometry("%dx%d" % (w, h))
    show = ImageTk.PhotoImage(out)
    label = Tkinter.Label(root, image=show)
    label.pack()
    root.loop()
except Exception as e:
    print "(no Tkinter)", e
    Tkinter = False

if len(sys.argv) > 3:
    out.save(sys.argv[3])

if not Tkinter:
    out.show()

```

## Please squint:

The code stamps on the whitest pixels with the best-fitting standard still life. There's a cut-off argument so you get to decide were the rounding to black-white threshold goes. I've experimented with living-is-white and the outcome is much the same.
> 15 votes

# Answer
# Java

An edge-detection-based approach. Requires this text file in the running directory.

```
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

import javax.imageio.ImageIO;

public class StillLifer{
    private static List<boolean[][]>patterns=new ArrayList<>();
    private static boolean[][] copy(boolean[][]b,int x,int y){
        boolean[][]r=new boolean[6][6];
        for(int i=0;i<6;i++){
            for(int j=0;j<6;j++){
                r[i][j]=b[y+i][x+j];
            }
        }
        return r;
    }
    private static void paste(boolean[][]from,boolean[][]to,int x,int y){
        for(int i=0;i<from.length;i++)for(int j=0;j<from[0].length;j++){
            to[y+i][x+j]=from[i][j];
        }
    }
    private static boolean[][]findClosest(boolean[][]b){
        boolean[][]c=null;
        int d=999999;
        for(boolean[][]k:patterns){
            int d2=editDistance(b,k);
            if(d2<d){
                c=k;
                d=d2;
            }
        }
        return c;
    }
    private static boolean[][]decode(String s){
        char[]a=s.toCharArray();
        boolean[][]r=new boolean[6][6];
        int k=0;
        for(int i=0;i<6;i++){
            for(int j=0;j<6;j++){
                r[i][j]=a[k++]=='1';
            }
        }
        return r;
    }
    private static class EdgeDetectEntry{
        int l;
        int x;
        int y;
        public EdgeDetectEntry(int m,int x,int y){
            this.l=m;
            this.x=x;
            this.y=y;
        }
    }
    private static Random rand;
    private static int w,h;
    private static BufferedImage img;
    private static boolean[][]grid;
    private static File file;
    private static int editDistance(boolean[][]from,boolean[][]to){
        int w=from.length;
        int h=from[0].length;
        int k=0;
        for(int x=0;x<w;x++){
            for(int y=0;y<h;y++){
                k+=from[y][x]^to[y][x]?1:0;
            }
        }
        return k;
    }
    private static int colorDistance(Color from,Color to){
        return from.getRed()-to.getRed();
    }
    private static int edgeDetectWeight(int x,int y){
        int k=0;
        Color c=new Color(img.getRGB(x, y));
        for(int x2=Math.max(0,x-1);x2<Math.min(w,x+2);x2++){
            for(int y2=Math.max(0,y-1);y2<Math.min(h,y+2);y2++){
                int l=colorDistance(c,new Color(img.getRGB(x2, y2)));
                k+=l*l;
            }
        }
        return k;
    }
    private static void save() throws Exception{
        int bk=Color.BLACK.getRGB();
        int wt=Color.WHITE.getRGB();
        for(int x=0;x<w;x++){
            for(int y=0;y<h;y++){
                img.setRGB(x,y,grid[y][x]?wt:bk);
            }
        }
        String k=file.getName().split("\\.")[0];
        ImageIO.write(img,"png",new File(k="out_"+k+".png"));
    }
    private static String rle(boolean[][]grid){
        StringBuilder st=new StringBuilder();
        for(boolean[]row:grid){
            for(int j=0;j<row.length;j++){
                int k=1;
                for(;j<row.length-1&&row[j]==row[j+1];j++)k++;
                if(k!=1)st.append(Integer.toString(k,36));
                st.append(row[j]?'@':'-');
            }
        }
        return st.toString();
    }
    private static int getVal(boolean[][]grid,int x,int y){
        if(x<0)x+=w;
        if(y<0)y+=h;
        if(x==w)x=0;
        if(y==h)y=0;
        return grid[y][x]?1:0;
    }
    private static boolean newState(boolean[][]grid,int x,int y,String rule){
        String[]r=rule.split("/");
        int k=0;
        for(int a=-1;a<=1;a++)for(int b=-1;a<=1;a++)k+=(a|b)==0?0:getVal(grid,x+a,y+b);
        String s=Integer.toString(k);
        return grid[y][x]?r[1].contains(s):r[0].contains(s);
    }
    private static boolean[][] next(boolean[][]grid,String rule){
        boolean[][]r=new boolean[h][w];
        for(int x=0;x<w;x++){
            for(int y=0;y<h;y++){
                r[y][x]=newState(grid,x,y,rule);
            }
        }
        return r;
    }
    private static void loadPatterns() throws Exception{
        Scanner reader=new Scanner(new File("lib.txt"));
        while(reader.hasNext()){
            String line=reader.nextLine();
            if(line.startsWith("--"))continue;
            patterns.add(decode(line));
        }
        reader.close();
    }
    public static void main(String[]a) throws Exception{
        loadPatterns();
        Scanner in=new Scanner(System.in);
        img=ImageIO.read(file=new File(in.nextLine()));
        in.close();
        w=img.getWidth();
        h=img.getHeight();
        grid=new boolean[h][w];
        final int npix=w*h;
        rand=new Random(npix*(long)img.hashCode());
        List<EdgeDetectEntry> list=new ArrayList<>();
        for(int x=0;x<w;x++){
            for(int y=0;y<h;y++){
                list.add(new EdgeDetectEntry(edgeDetectWeight(x,y),x,y));
            }
        }
        list.sort((one,two)->{int k=two.l-one.l;if(k>0)return 1;if(k<0)return -1;return 0;});
        for(int i=Math.max(Math.min(3,npix),npix/5);i>0;i--){
            EdgeDetectEntry e=list.get(i);
            grid[e.y][e.x]=rand.nextDouble()<0.9;
        }
        grid=next(grid,"/2345678");
        boolean[][]d=new boolean[h][w];
        for(int i=0;i<w/6;i++){
            for(int j=0;j<h/6;j++){
                paste(findClosest(copy(grid,i*6,j*6)),d,i*6,j*6);
            }
        }
        grid=d;
        assert(rle(next(grid,"3/23")).equals(rle(grid)));
        save();
    }
}

```

Some results:
> 9 votes

# Answer
# C++

Straightforward pixelation approach using the average of each 8x8 grid to select an 8x8 output grid (a "color texture"). Each 8x8 output grid has a 2 cell separator at the top and right. Grids were designed ranging from 4 cell still lifes to 18 cell still lifes within the remaining 6x6 pixels.

The program acts as a filter from binary PGM to binary PBM. By default, images are "dark"; black is death and white is life; `-i` inverts this. `-g [value]` adds a gamma, which is used to pre-weight averages before selecting the color textures.

```
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cmath>

// colors 4 through 18 have 4 through 18 live cells
// colors 1-3 are repetitions of 0 or 4 used
// as artificially weighted bins
unsigned char gol_colors[]={
      0,  0,  0,  0,  0,  0,  0,  0 // Color  0
   ,  0,  0,  0,  0,  0,  0,  0,  0 // Color  1
   ,  0,  0,  0, 16, 40, 16,  0,  0 // Color  2
   ,  0,  0,  0, 16, 40, 16,  0,  0 // Color  3
   ,  0,  0,  0, 16, 40, 16,  0,  0 // Color  4
   ,  0,  0,  0, 24, 40, 16,  0,  0 // Color  5
   ,  0,  0,  0, 16, 40, 80, 32,  0 // Color  6
   ,  0,  0,  0, 48, 72, 40, 16,  0 // Color  7
   ,  0,  0,  8, 20,  8, 64,160, 64 // Color  8
   ,  0,  0,  8, 20,  8, 64,160, 96 // Color  9
   ,  0,  0, 12, 20,  8, 64,160, 96 // Color 10
   ,  0,  0, 12, 20,  8,192,160, 96 // Color 11
   ,  0,  0,204,204,  0,  0, 48, 48 // Color 12
   ,  0,  0,204,204,  0,192,160, 64 // Color 13
   ,  0,  0,  0,108,168,168,108,  0 // Color 14
   ,  0,  0, 96,144,104, 40,172,192 // Color 15
   ,  0,  0,204,204,  0,  0,204,204 // Color 16
   ,  0,  0,216,216,  0,216,212,  8 // Color 17
   ,  0,  0,204,164, 40, 80,148,204 // Color 18
};

enum { gol_bins = sizeof(gol_colors)/(sizeof(*gol_colors))/8 };

bool inverted=false;

bool applygamma=false;
double gammasetting=0.0;

unsigned int corrected(unsigned int i, unsigned int r) {
   return static_cast<unsigned int>(r*std::pow(i/static_cast<double>(r), gammasetting));
}

int main(int argc, char** argv) {
   std::vector<unsigned short> pgm_data;
   unsigned pgm_width;
   unsigned pgm_height;
   unsigned pgm_vpp;

   std::vector<unsigned char> pbm_data;
   unsigned pbm_width;
   unsigned pbm_height;

   unsigned int doublings=0;

   std::vector<std::string> args(argv+1, argv+argc);
   for (unsigned int i=0, e=args.size(); i<e; ++i) {
      if (args[i]=="-i") { inverted=true; continue; }
      if (args[i]=="-g") {
         if (i+1==e) continue;
         std::stringstream ss;
         ss << args[++i];
         if (ss >> gammasetting) applygamma = true;
         continue;
      }
   }

   std::string line;
   std::getline(std::cin, line);
   if (line!="P5") return 1;
   enum { nothing, have_w, have_h, have_bpp } readstate = nothing;
   while (std::cin) {
      std::getline(std::cin, line);
      if (line.empty()) continue;
      if (line[0]=='#') continue;
      std::stringstream ss; ss << line;
      for(;;) {
         switch (readstate) {
         case nothing: if (ss >> pgm_width) readstate = have_w; break;
         case have_w:  if (ss >> pgm_height) readstate = have_h; break;
         case have_h:  if (ss >> pgm_vpp) readstate = have_bpp; break;
         }
         if (readstate==have_bpp) break;
         if (ss) continue;
         break;
      }
      if (readstate==have_bpp) break;
   }
   if (readstate!=have_bpp) return 1;
   // Fill pgm data
   pgm_data.resize(pgm_width*pgm_height);
   for (unsigned i=0, e=pgm_width*pgm_height; i<e; ++i) {
      int v = std::cin.get();
      if (v==std::char_traits<char>::eof()) return 1;
      pgm_data[i] = static_cast<unsigned int>(std::char_traits<char>::to_char_type(v))&0xFFU;
   }
   pbm_width  = pgm_width/8*8;
   pbm_height = pgm_height/8*8;
   pbm_data.resize(pbm_width*pbm_height/8);
   for (unsigned x=0, xe=pbm_width/8; x<xe; ++x) {
      for (unsigned y=0, ye=pbm_height/8; y<ye; ++y) {
         // Calculate the average of this 8x8 area
         unsigned int total=0;
         for (unsigned int xd=0; xd<8; ++xd) {
            for (unsigned int yd=0; yd<8; ++yd) {
               unsigned int c = x+xd+(y+yd)*pgm_width;
               unsigned int pv = pgm_data[x*8+xd+(y*8+yd)*pgm_width];
               // Apply gamma prior to averaging
               if (applygamma) pv=corrected(pv, pgm_vpp);
               total += pv;
            }
         }
         total /= 64;
         // Invert average if inverting colors (white on black)
         if (inverted) total=pgm_vpp-total;
         total *= gol_bins;
         total /= (pgm_vpp+1);
         // Fill 8x8 areas with gol color texture
         for (unsigned int yd=0; yd<8; ++yd) {
            pbm_data[x+(y*8+yd)*pbm_width/8] = gol_colors[total*8+yd];
         }
      }
   }
   // Now, write a pbm
   std::cout
      << "P4\n"
      << "# generated by pgm2gol\n"
      << pbm_width << " " << pbm_height << "\n";
   for (unsigned i=0, e=pbm_data.size(); i<e; ++i) {
      unsigned char data=pbm_data[i];
      if (!inverted) { data=pbm_data[i]^0xFF; }
      std::cout.put(data);
   }
}

```

Selected results (note: all pbm's were converted to png's using a third party program for upload):

Escher, gamma 2.2

Mona Lisa, gamma 2.2

Ocean, gamma 2.2 inverted

Puppy, gamma 2.2

Treachery of Images, gamma 2.2 inverted

Mona Lisa gamma 2.2, inverted, for comparison
> 9 votes

---
Tags: popularity-contest, graphical-output, image-processing, game-of-life
---


title: Number Plate Golf: Parsing

text:
# Question
Title: Number Plate Golf: Parsing
**See Also: Recognition**

## Introduction

You've now been taken off the speed camera development team (let's face it, your code is nowhere near production code standards) and are now working on a program to extract information about the car from the number plates. Of course, you've caught the code golf bug and want to write the program in as few bytes as possible.

## Challenge

Given a valid, British number plate, display information about the car's registration.

You only have to support number plates registered between 2001 and 2051 (inclusive).

Internet access is disallowed.

*The input will be given as a string.*

## Number Plates

British number plates are ordered like so:

### Area code

A table with all of the area code mnemonics which you need to support can be found here.

For the letter X, you only need to output *Personal Export* due to multiple areas being covered by the same mnemonic.

You must output the DVLA office name.

### Age Identifier

Similarly, a table with all of the age identifiers which you need to support can be found here.

If the identifier is in the range `Y to 50` inclusive, you must output:

```
1/3/[Year] to 31/8/[Year]

```

Likewise, if the identifier is in the range `51 to 00` inclusive, you must output:

```
1/9/[Year] to [28/29]/2/[Year + 1]

```

You should support leap years.

## Examples

### WK94 FRS

```
Truro, 1/9/2044 to 28/2/2045

```

### CB16 BTD

```
Bangor, 1/3/2016 to 31/8/2016

```

### BD51 SMR

```
Birmingham, 1/9/2011 to 29/2/2012

```

### XAY EEA

```
Personal Export, 1/3/2001 to 31/8/2001

```

## Scoring

The shortest code in bytes wins

# Answer
# Ruby, 629 bytes

```
s=gets
p=c=0
'PETeRborOuGh
NORWich
IPSwicH
BIRMiNGHam
CARdiff
SWANsea
BAngOr
CHEsTer
SHREWsbURY
CHELmSFOrd
NOTTInGHAm
LInCOlN
MAIDStone
BRIgHtON
BOURNEMoUth
PORTSMoUth
ISLE OF WIGHt
PORtSmOUtH
BOREHAMwoOD
NORTHAmPton
WIMBLeDoN
BOREHAMwOoD
SIdcup
MANChESTer
NEWCAstle
STOcKtON
oXFOrd
PReStON
CArlISlE
ReADIng
GLAsGoW
EDINBUrGh
DUNdEe
ABERDEen
INvErNEsS
WORcESTer
EXeTeR
TRUro
BRiStoL
PERSONAL eXPOrt
LeEds
SHEFFiElD
BEVERLEY'.split($/).map{|w|c<s[0,2].to_i(35)&&p=w;d=0;w.bytes{|b|d+=d+b/95};c+=d}
y=(?1+s[2,9]).to_i-1
puts p.capitalize+", 1/%d/20%02d to %d/%d/20%02d"%[z=3+y%100/50*6,1+y%=50,z<4?31:y%4==2?29:28,(z+5)%12,1+y+z/9]

```

The first two letters are interpreted as a base 35 number and then looked up to find the correct town. The quantity of addresses assigned to each town is encoded (run-length encoding) in the captialization of each town in binary, where uppercase=0 and lowercase=1.

In order to handle the Y age indicator for the first half of 2001, a 1 is prepended to the age. Thus `1` `Y` is interpreted by `.to_i` as 1, and `1` `02` is interpreted as 102. 1 is subtracted (to handle the wraparound for 2050) and taken modulo 100 to decide which half of the year we are in. It is then taken modulo 50 (and the 1 added on again) to find the year.
> 4 votes

# Answer
# PHP, ~~1044~~ ~~800~~ 757 bytes

The script is added to a PHAR (PHP archive) and compressed with gzip to shrink it from 1044 to 800 bytes. Further optimization took the original code down to 994 bytes, which then as a Phar is 757 bytes. Takes the license plate string as the first argument like `php u.phar BD51 SMR` (actually the latter part is read as "second argument", but useless garbage anyway for this challenge).

Download the uklic.phar file for this answer

This is the script before compression:

```
<?$o=[X=>'Personal export',B=>Birmingham,E=>Chelmsford,M=>Manchester,O=>Oxford,R=>Reading,V=>Worcester,A=>['A-N'=>Peterborough,'O-U'=>Norwich,'V-Y'=>Ipswich],C=>['A-O'=>Cardiff,'P-V'=>Swansea,WXY=>Bangor],D=>['A-K'=>Chester,'L-Y'=>Shrewsbury],F=>['A-P'=>Nottingham,'R-Y'=>Lincoln],G=>['A-O'=>Maidstone,'P-Y'=>Brighton],H=>['A-J'=>Bournemouth,'K-Y'=>Portsmouth,W=>'Isle of Wight'],K=>['A-L'=>Borehamwood,'M-Y'=>Northampton],L=>['A-J'=>Wimbledon,'K-T'=>Borehamwood,'U-Y'=>Sidcup],N=>['A-O'=>Newcastle,'P-Y'=>Stockton],P=>['A-T'=>Preston,'U-Y'=>Carlisle],S=>['A-J'=>Glasgow,'K-O'=>Edinburgh,'P-T'=>Dundee,UVW=>Aberdeen,XY=>Inverness],W=>['A-J'=>Exeter,KL=>Truro,'M-Y'=>Bristol],Y=>['A-K'=>Leeds,'L-U'=>Sheffield,'V-Y'=>Beverley]];$p=$argv[1];$a=$o[$p{0}];$z=$a;if(count($a)>1){foreach($a as$r=>$d){if(preg_match("/[$r]/",$p{1})){$z=$d;}}}$n=$p{2}.$p{3};$y=$n+($n==Y);if($y==0)$y=50;$h=$y&&$n<51;$y%=50;$x=$y+1;printf('%s, 1/%s/20%02d to %s/20%02d',$z,$h?3:9,$y,$h?'31/8':28+!($x%4).'/2',$h?$y:$x);

```

The DVLA Office lookup is a simple map with a string if the first character of the license plate is enough to identify the office and an array if we need the second character. The character range is then matched with a simple regexp.

The code for the date range is quite easy except for the two edge cases "Y" and "00"~~, which can't be calculated~~. Y is cast to integer and added a 1, in case the input is an integer. That's how we get 2001 for Y. 00 is accounted for by modulo arithmetic.

This is the slightly better readable version:

```
<?
$o = [
  X => 'Personal export',
  B => Birmingham,
  E => Chelmsford,
  M => Manchester,
  O => Oxford,
  R => Reading,
  V => Worcester,
  A => ['A-N' => Peterborough, 'O-U' => Norwich, 'V-Y' => Ipswich],
  C => ['A-O' => Cardiff, 'P-V' => Swansea, WXY => Bangor],
  D => ['A-K' => Chester, 'L-Y' => Shrewsbury],
  F => ['A-P' => Nottingham, 'R-Y' => Lincoln],
  G => ['A-O' => Maidstone, 'P-Y' => Brighton],
  H => ['A-J' => Bournemouth, 'K-Y' => Portsmouth, W => 'Isle of Wight'],
  K => ['A-L' => Borehamwood, 'M-Y' => Northampton],
  L => ['A-J' => Wimbledon, 'K-T' => Borehamwood, 'U-Y' => Sidcup],
  N => ['A-O' => Newcastle, 'P-Y' => Stockton],
  P => ['A-T' => Preston, 'U-Y' => Carlisle],
  S => ['A-J' => Glasgow, 'K-O' => Edinburgh, 'P-T' => Dundee, UVW => Aberdeen, XY => Inverness],
  W => ['A-J' => Exeter, 'KL' => Truro, 'M-Y' => Bristol],
  Y => ['A-K' => Leeds, 'L-U' => Sheffield, 'V-Y' => Beverley]
];
$p=$argv[1];

$a=$o[$p{0}];
$z=$a;
if (count($a)-1) {
    foreach($a as $r => $d) {
        if (preg_match('/['.$r.']/', $p{1})) {$z=$d; }
    }
}
$n=$p{2}.$p{3};
$y=$n+($n==Y);
if ($y==0) {
    $y=50;
}
$h=$y&&$n<51;
$y%=50;
$x=$y+1;
printf('%s, 1/%s/20%02d to %s/20%02d',$z,$h?3:9,$y,$h?'31/8':28+!($x%4).'/2',$h?$y:$x);

```

Updates:

1. Seriously trimmed down the date calculation section and made use of printf, replaced `is_array($a)` with \`count($a)\>1
2. Optimized the Phar bootstrapping
> 3 votes

---
Tags: code-golf, parsing
---


title: What's on the TV?

text:
# Question
Title: What's on the TV?
## Challenge

Write a program which, using the XML data from the site here, display the name of the programme which is currently showing on BBC 1.

## Information

All times are given at London time (GMT+1 at the time of posting and GMT+0 after the 30th October). Therefore, you should convert your local time to London time.

Each programme is given a start and end time. If the current time is after the start time and before the end time of a programme, that programme is currently showing. Your programme may handle overlaps in anyway you wish.

Your output must be the programme title, like so:

```
BBC News

```

However, if the programme has a subtitle (shown by the presence of the subtitle tag), the output should be like so:

```
Steptoe and Son: The Piano

```

Where *Steptoe and Son* is the title and *The Piano* is the subtitle. An example programme with a subtitle is as follows:

```
<programme>
    <subtitle>Newcastle</subtitle>
    <title>Flog It!</title>
    <end>1710</end>
    <start>1610</start>
    <desc>
      Antiques series. Paul Martin presents from the Discovery Museum in Newcastle. The items uncovered include a book of autographs with a local connection. Also in HD. [S]
    </desc>
</programme>

```

URL shorteners are disallowed but XML parsing libraries are allowed.

## Winning

The shortest code in bytes wins.

# Answer
# Bash + curl + XMLStarlet, 166 characters

```
d=`TZ=Europe/London date +%H%M`
curl -s bleb.org/tv/data/listings/0/bbc1.xml|xmlstarlet sel -t -m "//programme[start<=$d and end>$d]" -v title -m subtitle -o :\  -v .

```

Sample run:

```
bash-4.3$ date
Mon Aug 22 14:17:07 EEST 2016

bash-4.3$ bash bbc.sh
Bargain Hunt: Carmarthen

```
> 2 votes

# Answer
# Python, ~~440~~ ~~428~~ ~~426~~ ~~398~~ 395 Bytes

*-31 Bytes thanks to @Loovjo*

Throws an error when it found the date.

```
import re,pytz,urllib
from datetime import*
x=urllib.urlopen("http://www.bleb.org/tv/data/listings/0/bbc1.xml").read().split("</p")[:-1]
for m,n in enumerate(re.search("\d*</s",i).group()for i in x):
 if n>datetime.strftime(datetime.now(pytz.utc).astimezone(pytz.timezone('Europe/London')),"%H%M"):print re.search(">.*?</t",x[m-1]).group()[1:-3],": "+re.search("e>.*?</s",x[m-1]).group()[2:-3],_

```

*Please don't hurt me for parsing xml with regex.*

### version using a xml parser, 398 Bytes

```
import re,pytz,urllib
import xml.etree.ElementTree as ET
from datetime import*
x=list(ET.parse(urllib.urlretrieve("http://www.bleb.org/tv/data/listings/0/bbc1.xml")[0]).getroot())
for m,n in enumerate(i.find("start").text for i in x):
 if n>datetime.strftime(datetime.now(pytz.utc).astimezone(pytz.timezone('Europe/London')),"%H%M"):print x[m-1].find("title").text,": "+x[0].find("subtitle").text,_

```
> 5 votes

---
Tags: code-golf, parsing, internet
---


title: shortest code to encrypt a string

text:
# Question
Title: shortest code to encrypt a string
Using a language of your choice write a program that takes a string as an input, and returns the string encrypted.

# Algorithm:

You should assume that each character is always encoded in a byte and is ASCII-based. The extended ASCII codes are mapped to whatever is the default code page in use by the system.

You should encrypt the code in the following way: code of first character +1, code of second character +2, code of third character +3 .....

Extended ASCII codes are based on this table: http://www.asciitable.com/

Shortest code wins.

# Answer
## GolfScript ~~20~~ ~~19~~ ~~15~~ 12

```
{0)255%:0+}%

```

This assigns a variable to the character `0`, which allows us to not define it on the first iteration of the mapping. I love that you can do that in GolfScript! Each iteration of the mapping increments the `0` variable, and adds it to subsequent characters of the string (which is treated like an array).

This alternate 20-character GolfScript solution using `zip` encounters an interesting issue:

```
.,,]zip{~)255%+}%''+

```

Try it here. This standard online interpreter, however, treats `zip` differently for an array containing a string and an array. See this vs this. I'm not sure if an alternate version of Ruby or GolfScript is being used, or which one is considered canonical, but the second interpreter can be resolved with 2 characters:

```
.,,[\]zip{~)255%+}%''+

```

I also like a different solution for 23 characters:

```
1\{(@.@255%+\)@.}do]''+

```
> 4 votes

# Answer
# BrainFuck: 21

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

```

Assumes EOF=zero

```
echo -n 'My secret password is 123456!' | beef encrypt.bf
==> N{#wjiym}*{mv36HJLNPR>

```
> 15 votes

# Answer
# C — ~~67~~ ~~56~~ 49 characters

During compilation it might warn that `q` is missing a type...

```
q;main(p){for(;p=~getchar();)putchar(q++%255-p);}

```

Thanks to Josh for the significantly shorter rewrites!

```
$ echo 'My secret password is 123456!' | ./_encrypt
N{#wjiym}*{m����v3}�6HJLNPR>(

```

Confirm it handles the rollover from 255 to 1 correctly by encrypting 343 `x`s and checking for no `x`s in the output:

```
$ echo xxxxxxx | sed -e 's/x/xxxxxxx/g' -e 's/x/xxxxxxx/g' | ./_encrypt | grep -o x | wc -l
0

```
> 7 votes

# Answer
# Befunge 98 - 15 bytes

```
:~+'U3*%1+,1+#@

```

Keeps a counter (starting at 0) and adds that to the `~` input. Then, computes `255` (as `85 * 3` in the form of `'U3*`), then mods (`%`). Then, it adds `1` and prints it, then adds one to the counter, then uses `#` to skip over the `@`. At the end of the input, the IP goes the other way and hits the `@`, ending the program.

Alternatively, if your interpreter supports unicode, this 14 byte (13 char) solution works:

```
:~+'ÿ%1+,1+#@

```

Sample run (in command prompt, so some of the unicode characters are actually some ascii value):

```
This string will be encrypted using the predetermined method!2.7182818284590452353602874713526624

```

Output:

```
Ujlw%y{zrxr,äw{|1tx4zäzèÆèÅüü>öôèÉèDÖÄîHÖ£ÉÉÆóöó₧¢íÖÖVñ¥¡ó¬á^pmwrzu|v~yÇ}⌂ä|üâüâåàëäçÄÄîÉïÄæÅöòÆò

```
> 5 votes

# Answer
## J, 21 characters

```
a.{~1+256|(+i.@#)a.i.

```

Usage (borrowing Yimin's test text):

```
   a.{~1+256|(+i.@#)a.i.'My secret password is 123456!'
N{#wjiym}*{m????v3}?6HJLNPR>

```
> 4 votes

# Answer
## JavaScript, 90c

```
~~`t.split("").map(function(c,a){return String.fromCharCode(c.charCodeAt(0)+a+1)}).join("")`~~
```

```
[].map.call(t,function(c,a){return String.fromCharCode(c.charCodeAt(0)+a%255+1)}).join("")

```

Fiddledee
> 3 votes

# Answer
# Python2.7 (67 chars)

```
import sys;print''.join([chr((ord(x)+1)%256)for x in sys.argv[1]])

```
> 3 votes

# Answer
# **Javascript/JScript: 72 to 105 chars**

Here is a Javascript/JScript attempt at making a version of this code.

I'm aware that there is another Javascript code, but that one relies on recent Javascript implementations.

That is a bad thing!!!

That code is invalid in ie8\< without polyfills.

Here is my version:

```
function $(c){for(var i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));return o;}
//function call, 105 chars, absolutely valid!

function $(c){for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));return o;}
//function call, no var keyword, 101 chars, completely valid!

function $(c){for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i));return o;}
//function call, 97 chars, most likely invalid!

c='';//here goes input, output is in var `o`, dont count this line
for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i&255));
//no function call, input goes to var c, 77 chars of pure working code! valid for sure!

c='';//here goes input, output is in var `o`, dont count this line
for(i=0,l=c.length,o='';i<l;o+=String.fromCharCode(c.charCodeAt(i++)+i));
//no function call, input goes to var c, no char wrapping after 255, 73 chars of probably invalid code

```

---

@toothbrush gave me this answer:

```
i=0;while(i<c.length)c[i]=String.fromCharCode(c.charCodeAt(i++)+i%255+1)

```

It changes the original string and is only **72** bytes!

I don't know why he has `%255+1` in the end when `&255` does the same job, is faster and shorter.

But I will keep the original answer intact.

---

Consider this and test it with a Javascript/JScript interpreter.

I know that the 73 char version and the 97 char function call version will be invalid, but its still here!

If you will be using the code in a production environment (website), use the 105 chars long and consider changing the function name to something else (or you might have problems with jQuery and MooTools).
> 3 votes

# Answer
# Python3 (99 chars)

```
e=''
i=0
for c in __import__("sys").argv[1]:
        i=(i+1)%255
        e+=chr(ord(c)+i)
print(e)

```

## Example

`python encrypt.py password` outputs `qcvw|uyl`
> 2 votes

# Answer
## CoffeeScript, ~~73~~ 64 chars

`t.replace /./g,(c,a)->String.fromCharCode c.charCodeAt()+a%255+1`

~~`[].map.call(t,(c,a)->String.fromCharCode c.charCodeAt(0)+a%255+1).join ""`~~

Example: `"Test string".replace /./g,(c,a)->String.fromCharCode c.charCodeAt()+a%255+1` outputs `Ugvx%y{zrxr`

Coffee to Javascript converter (paste in right box): http://js2coffee.org/

As per Ismael Miguel's comments, this method should work in IE 5.5+.
> 2 votes

# Answer
## Ruby functional, 67

```
puts ARGV[0].bytes.map.with_index(1){|b,i|b+i%255}.map(&:chr).join

```

Example:

```
$ ruby encrypt.rb password
=> qcvw|uyl

```
> 2 votes

# Answer
# Julia 51 (-4 if in place is allowed)

```
g(s)=([s.data[i]+=(i-1)%255+1 for i=1:length(s)];s)
g(s)=[s.data[i]+=(i-1)%255+1 for i=1:length(s)] # in place version
julia> g("a"^256) # ^ operator repeats strings
"bcdefghijklmnopqrstuvwxyz{|}~\x7f��������������������������������������������������������������������������������������������������������������������������������\0\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\e\x1c\x1d\x1e\x1f !\"#\$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`b"

```
> 1 votes

# Answer
## Haskell, ~~77C~~ 59C

```
import Data.Char
e s=h s 1
h""_=""
h(x:s)i=(chr(mod((ord x)+i)128)):h s(i+1)

```

v2

```
import Data.Char
e s = map chr(zipWith(+)(map ord s)[1..])

```

I am assuming that input doesn't need to be on STDIN.

Example run:

```
*Main> e "hello"
"igopt"

```
> 1 votes

# Answer
## GolfScript, 27 characters

```
[.,,\]zip[{{+}*255%1+}/]''+

```

Hmmm...seems a bit long. Maybe I should stick to J.
> 1 votes

# Answer
# Ruby, ~~45~~ 39 bytes

```
gets.chars{|c|putc(c.ord+$.)%256;$.+=1}

```
> 1 votes

# Answer
# Erlang: 60C

Not the smallest or prettiest, but this one can be run standalone in the command line. Set T to your text.

```
{S,_}=lists:mapfoldl(fun(C,I)->{C+I,(I+1)rem 255}end,1,T),S.

```

Yields: "qcvw|uyl"
> 1 votes

# Answer
# Rebol, 58 chars

```
s: input forall s[s/1: mod(index? s)+(to-integer s/1)256]s

```
> 1 votes

# Answer
**Groovy, 53 Characters**

```
i=0;args[0].chars.collect{(char)it+(++i%255)}.join()

```
> 1 votes

# Answer
# Dart, 68

```
f(s,{i=1})=>new String.fromCharCodes(s.runes.map((c)=>(c+i++)%255));

```

Example:

```
f('My secret password is 123456!');
> N{#wjiym}*{mv3}6HJLNPR>

```
> 0 votes

# Answer
# Perl, 54 char

```
$i=1;print map{chr((ord()+$i++)%256)}split//,$ARGV[0];

```

Example:

```
perl encrypt.pl password
> qcvw|uyl

```
> 0 votes

---
Tags: code-golf
---


title: The Piggyback Sequence

text:
# Question
Title: The Piggyback Sequence
I made my own sequence recently (called the Piggyback sequence), and it works like this:

`P(1)`, `P(2)` and `P(3)` = `1`.

For all `P(n)` where `n>3`, the sequence works like this:

```
P(n) = P(n-3) + P(n-2)/P(n-1)

```

So, continuing the sequence:

`P(4)` = `1 + 1/1` = `2`

`P(5)` = `1 + 1/2` = `3/2` = `1.5`

`P(6)` = `1 + 2/(3/2)` = `7/3` = `2.33333...`

`P(7)` = `2 + (3/2)/(7/3)` = `37/14` = `2.6428571428...`

`P(8)` = `3/2 + (7/3)/(37/14)` = `529/222` = `2.3828828828...`

Your task is, when given `n`, calculate `P(n)` either as a floating point number or an (im)proper fraction.

This is , so shortest code in bytes wins.

*If anyone can find the name of the sequence, please edit the post accordingly.*

## Current leaders: MATL and Jelly (both at 15 bytes).

# Answer
# Python 2, 40 39 bytes.

```
f=lambda x:x<4or.0+f(x-3)+f(x-2)/f(x-1)

```

Gives `True` instead of 1, if this isn't allowed we can have this for 42 bytes:

```
f=lambda x:.0+(x<4or f(x-3)+f(x-2)/f(x-1))

```

The way it works is pretty straightforward, the only trick is using `.0+` to cast the result to a float.
> 6 votes

# Answer
## Haskel, 32 bytes

```
(a#b)c=a:(b#c)(a+b/c)
((0#1)1!!)

```

Usage example: `((0#1)1!!) 7` -\> `2.642857142857143`. I start the sequence with `0, 1, 1` to fix `!!`'s 0-based indexing.

Edit: @xnor found a way to switch from 0-based to 1-based index, without changing the byte count.
> 5 votes

# Answer
# Ruby, 34 bytes

Since Ruby uses integer division by default, it turns out that it's shorter to use fractions instead. Golfing suggestions welcome.

```
f=->n{n<4?1r:f[n-3]+f[n-2]/f[n-1]}

```
> 4 votes

# Answer
# Perl 6,  ~~25~~  23 bytes

~~```
{(0,1,1,1,*+*/*...*)[$_]}

```~~
```
{(0,1,1,*+*/*...*)[$_]}

```

## Explanation:

```
# bare block lambda with implicit parameter ｢$_｣
{
  (
    # initial set-up
    # the ｢0｣ is for P(0) which isn't defined
    0, 1, 1, 1,

    # Whatever lambda implementing the algorithm
    * + * / *
    # { $^a + $^b / $^c }

    # keep using the lambda to generate new values until
    ...

    # Whatever (Forever)
    *

   # get the value indexed by the argument
  )[ $_ ]
}

```

This returns a Rat (Rational) for inputs starting with 3 up until the result would start having a denominator bigger than can fit in a 64 bit integer, at which point it starts returning Nums (floating point).
The last Rat it will return is `P(11) == 8832072277617 / 2586200337022`

If you want it to return Rational numbers rather than floats you can swap it for the following which will return a FatRat instead.

```
{(0.FatRat,1,1,*+*/*...*)[$_]}

```

## Test:

```
#! /usr/bin/env perl6
use v6.c;
use Test;

my &piggyback = {(0,1,1,*+*/*...*)[$_]}
# */ # stupid highlighter no Perl will ever have C/C++ comments

my @test = (
  1, 1, 1, 2,
  3/2, 7/3, 37/14,
  529 / 222,
  38242 / 11109,
  66065507 / 19809356,
  8832072277617 / 2586200337022,
);

plan +@test;

for 1..* Z @test -> ($input,$expected) {
  cmp-ok piggyback($input), &[==], $expected, $expected.perl;
}

```
> 4 votes

# Answer
## C, 46 bytes

```
float P(n){return n<4?1:P(n-3)+P(n-2)/P(n-1);}

```

Ideone
> 3 votes

# Answer
# MATL, 15 bytes

```
llli3-:"3$t/+]&

```

Try it online!

### Explanation

```
lll       % Push 1, 1, 1
i         % Take input n
3-:       % Pop n and push range [1 2 ... n-3] (empty if n<4)
"         % For each
  3$t     %    Duplicate the top three numbers in the stack
  /       %    Pop the top two numbers and push their division
  +       %    Pop the top two numbers and push their addition
]         % End
&         % Specify that the next function, which is implicit display, will take
          % only one input. So the top of the stack is displayed

```
> 3 votes

# Answer
# Cheddar, 31 bytes

```
n P->n<4?1:P(n-3)+P(n-2)/P(n-1)

```

The ungolfed version is so clear imo you don't need explanation:

```
n P->
  n < 4 ? 1 : P(n-3) + P(n-2) / P(n-1)

```

basically after the function arguments you can specify the variable to use which will be set to the function itself. Why? because this function will be tail-call-optimized, or at least should be.
> 2 votes

# Answer
# 05AB1E, ~~18~~ 17 bytes

```
3Ld                # push list [1,1,1]
   ¹ÍG         }   # input-3 times do
      D3£          # duplicate list and take first 3 elements of the copy
         R`        # reverse and flatten
           /+      # divide then add
             ¸ì    # wrap in list and prepend to full list
                ¬  # get first element and implicitly print

```

Try it online!

Saved 1 byte thanks to Luis Mendo
> 2 votes

# Answer
# Javascript (ES6), 31 bytes

```
P=n=>n<4?1:P(n-3)+P(n-2)/P(n-1)

```

A simple function.

```
P=n=>n<4?1:P(n-3)+P(n-2)/P(n-1)

var out = '';

for (var i=1;i <= 20;i++) {
out +='<strong>'+i+':</strong> '+P(i)+'<br/>';
}

document.getElementById('text').innerHTML = out;
```

```
div {
font-family: Arial
}
```

```
<div id="text"></div>
```
> 2 votes

# Answer
# Pyth, 20 bytes

```
L?<b4h0+y-b3cy-b2ytb

```

Try it online!
> 1 votes

# Answer
# Jelly, 15 bytes

```
ạ2,1,3ß€÷2/SµḊ¡

```

Try it online! or verify all test cases.

### How it works

```
ạ2,1,3ß€÷2/SµḊ¡  Main link. Argument: n (integer)

             Ḋ   Dequeue; yield [2, ..., n].
            µ ¡  If the range is non-empty (i.e., if n > 1), execute the chain to
                 the left. If n is 0 or 1, return n.
                 Note that P(3) = P(0) + P(2)/P(1) if we define P(0) := 0.
ạ2,1,3           Take the absolute difference of n and 2, 1, and 3.
                 This gives [0, 1, 1] if n = 2, and P(0) + P(1)/P(1) = 0 + 1/1 = 1.
      ß€         Recursively apply the main each to each difference.
        ÷2/      Perform pairwise division.
                 This maps [P(n-2), P(n-1), P(n-3)] to [P(n-2)/P(n-1), P(n-3)].
           S     Sum, yielding P(n-2)/P(n-1) + P(n-3).

```
> 1 votes

# Answer
# Mathematica, 36 bytes

```
P@n_:=If[n<4,1,P[n-3]+P[n-2]/P[n-1]]

```

Here are the first few terms:

```
P /@ Range[10]
{1, 1, 1, 2, 3/2, 7/3, 37/14, 529/222, 38242/11109, 66065507/19809356}

```
> 1 votes

# Answer
# R, ~~53~~ 47 bytes

```
f=function(N)ifelse(N>3,f(N-3)+f(N-2)/f(N-1),1)

```

This answer made use of the pretty neat function `ifelse` : `ifelse(Condition, WhatToDoIfTrue, WhatToDoIfNot)`
> 1 votes

# Answer
# Dyalog APL, 25 bytes

`⊃{1↓⍵,⍎⍕' +÷',¨⍵}⍣⎕⊢0 1 1`
> 0 votes

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