# Question
Title: Counting creatures on a hexagonal tiling
This challenge will have you count "creatures" in the tile game Palago.

> A creature is any closed shape that can be formed by Palago tiles of matching colour in a hexagonal grid.

The game Palago consists of tiles like this:

These tiles can be rotated \\$120^\circ\\$, \\$240^\circ\\$, or not at all and placed anywhere on a hexagonal grid. For example, here is a (red) creature that requires 12 tiles.

# Challenge

The goal of this challenge is to write a program that takes an integer `n` as an input and computes the number of creatures (up to rotation and reflection) that require `n` tiles. The program should be able to handle up to `n=10` on TIO. This is , so fewest bytes wins.

# Example data

The values should match the data found in the "Creature Counts and Estimates" section of the creator's website. Namely

```
 n | output
---+-------
 1 | 0
 2 | 0
 3 | 1
 4 | 0
 5 | 1
 6 | 1
 7 | 2
 8 | 2
 9 | 9
10 | 13
11 | 37
12 | 81

```

# Answer
> 5 votes
# JavaScript (Node.js), 480 417 bytes

-63 bytes thanks to @Arnauld. Wow.

```
n=>(E=(x,y,d,k,h)=>V[k=[x+=1-(d%=3),y+=~d%3+1,d]]?0:(V[k]=1,h=H.find(h=>h[0]==x&h[1]==y))?(d^(t=2-h[2])?E(x,y,t)||E(x,y,h[2]*2):E(x,y,t+2)):[x,y,0],I=c=>c.map(([x,y,t])=>[x-g(0),y-g(1),t],g=p=>Math.min(...c.map(h=>h[p]))).sort(),S=e=>(V={},e=E(0,0,0))?(--n&&H.pop(H.push(e),S(),S(e[2]=1),S(e[2]=2)),++n):n-1||E[I(c=H)]||[0,0,0,++N,0,0].map(r=>E[I(c=c.map(([x,y,t])=>[-x-y,r?y:x,(r?t*2:t+1)%3]))]=1))(H=[[N=0,0,1]])&&N

```

Try it online!

Firstly, repect to Arnauld whose answer gave me the inspiration to dig deeper. I have tried hard to be original with my algorithms, although I intentionally changed some of my code to use the same variables as Arnauld so that the code could be more easily compared.

### Searching for empty hexes

The search for creatures is:

* Initialize list of tiles with tile 1 at 0,0
* Recursively:
    + Search for an empty hex that is needed to complete creature
    + If empty hex found
        - Add each type of tile 0,1,2 to empty hex and recurse
    + If empty hex not found
        - If creature is of correct size and is not already in zoo
            * Increment number of distinct creatures found by one
            * Add all rotations and reflections of creature to zoo

The search for empty hexes uncovered an interesting symmetry. Arnauld discovered that one of the six directions could be ignored, but in fact three out of six can be ignored!

Here is Arnauld's original direction and tile key:

Imagine we start at tile A of type 1 at the blue dot. It seems that we have to recurse out in d=0 and d=5. However, whichever tile is placed in d=0, it will certainly have an exit in d=4, which will visit the same hex as exiting tile A in d=5. That is Arnauld's discovery, and it's what started me thinking.

Notice that:

* Every tile that has an exit in d=0 has an exit in d=5
* Every tile that has an exit in d=2 has an exit in d=1
* Every tile that has an exit in d=4 has an exit in d=3
* Every tile that can be entered from d=0 has an exit in d=4
* Every tile that can be entered from d=2 has an exit in d=0
* Every tile that can be entered from d=4 has an exit in d=2

This means that we only need to consider directions 0,2,4. Any exits in directions 1,3,5 can be ignored because the hexes reachable in directions 1,3,5 can instead be reached from an adjacent hex using directions 0,2 or 4.

How cool is that!?

### Relabelled Directions

So I relabel the directions and tiles like this (Arnauld's image edited):

Now we have the following relationship between tiles, entries and exits:

```
    |  t=0  |  t=1  |  t=2
----+-------+-------+-------
d=0 |  0,2  |  1,2  |    2
d=1 |  0,2  |    0  |  0,1
d=2 |    1  |  1,2  |  0,1

```

So exits are: d+t==2 ? (4-t)%3 : 2-t and 2\*t%3

### Hexagonal Rotations and Reflections

For rotations and reflections, I decided to try x,y hexagonal axial coordinates instead of the x,y,z cube coordinates.

```
-1,2   0,2   1,2   2,2
    0,1   1,1   2,1
 0,0   1,0   2,0   3,0

```

In this system, the rotation and reflection were simpler than I expected:

```
120 Rotation:   x=-x-y   y=x   t=(t+1)%3
Reflection:     x=-x-y   y=y   t=(t*2)%3

```

To get all the combinations I performed : rot,rot,rot,reflect,rot,rot

### Code (Original 480 byte)

```
f=n=>(
    // H:list of filled hexes [x,y,tile] during search for a complete creature
    // N:number of distinct creatures of size n
    // B:record of all orientations of all creatures already found
    H=[[0,0,1]],N=0,B={},

// E: find an empty hex required to complete creature starting in direction d from x,y
    E=(x,y,d,k,h)=>(
        x+=1-d,
        y+=1-(d+1)%3,
        // V: list of visited hexes during this search in E
        V[k=[x,y,d]] ?
            0
        : (V[k]=1, h=H.find(h=>h[0]==x&&h[1]==y)) ?
            // this hex is filled, so continue search in 1 or 2 directions
            (d==2-h[2] ? E(x,y,(4-h[2])%3) : (E(x,y,2-h[2]) || E(x,y,h[2]*2%3)))
        : [x,y,0] // return the empty hex
    ),

    // I: construct unique identifier for creature c by moving it so x>=0 and y>=0
    I=c=>(
        M=[0,1].map(p=>Math.min(...c.map(h=>h[p]))),
        c.map(([x,y,t])=>[x-M[0],y-M[1],t]).sort()
    ),

    // A: add complete creature c to B
    A=c=>{
        n==1&&!B[I(c)]&&(
            // creature is correct size and is not already in B
            N++,
            [0,0,0,1,0,0].map(
                // Add all rotations and reflections of creature into B
                // '0' marks a rotation, '1' marks a (vertical) reflection
                // rotation:   x=-x-y   y=x   t=(t+1)%3
                // reflection: x=-x-y   y=y   t=(t*2)%3
                r=>B[I(c=c.map(([x,y,t])=>[-x-y,r?y:x,(r?t*2:t+1)%3]))]=1)
        )
    },

    // S: recursively search for complete creatures starting with hexes H
    S=e=>{
        V={};
        (e=E(0,0,0)) ?
            // e is a required empty hex, so try filling it with tiles 0,1,2
            (--n && (H.push(e),S(),S(e[2]=1),S(e[2]=2),H.pop()), ++n)
        : A(H) // creature is complete, so add it to B
    },

    S(),
    N
)

```

### Code (Arnauld 417 byte)

Arnauld kindly submitted a 63 byte saving that used tricks that took me quite some time to wrap my head around. Since it has many interesting edits, I thought I'd put his code below (I've added my comments) so that it can be contrasted with my version.

```
f=n=>(
    // E:find an empty hex required to complete creature starting in direction d from x,y
    E=(x,y,d,k,h)=>
      V[k=[x+=1-(d%=3),y+=~d%3+1,d]] ?
        0
      :(V[k]=1,h=H.find(h=>h[0]==x&h[1]==y)) ?
        (d^(t=2-h[2]) ? E(x,y,t) || E(x,y,h[2]*2) : E(x,y,t+2))
      :[x,y,0],

    // I: construct unique identifier for creature c by moving it so x>=0 and y>=0
    I=c=>c.map(([x,y,t])=>[x-g(0),y-g(1),t],g=p=>Math.min(...c.map(h=>h[p]))).sort(),

    // S: recursively search for complete creatures starting with hexes H
    S=e=>
      (V={},e=E(0,0,0)) ?
        (--n&&H.pop(H.push(e),S(),S(e[2]=1),S(e[2]=2)),++n)
      :n-1
        ||E[I(c=H)]
        // creature is the correct size and has not been seen before
        // so record all rotations and reflections of creature in E[]
        ||[0,0,0,++N,0,0].map(r=>E[I(c=c.map(([x,y,t])=>[-x-y,r?y:x,(r?t*2:t+1)%3]))]=1)
)
// This wonderfully confusing syntax initializes globals and calls S()
(H=[[N=0,0,1]]) && N

```

# Answer
> 20 votes
# JavaScript (Node.js),  ~~578 ... 433~~  431 bytes

```
f=(n,T=[B=[N=0,0,0,1,1]])=>!n||T.some(([x,y,q,m])=>B.some((p,d)=>m>>d&1&&((p=x+~-s[d],q=y+~-s[d+2],t=T.find(([X,Y])=>X==p&Y==q))?(q=t[3])&(p=D[d*3+t[4]])^p?t[f(n,T,t[3]|=p),3]=q:0:[0,1,2].map(t=>f(n-1,[...T,[p,q,-p-q,D[d*3+t],t]])))),s="2100122",D=Buffer("160).(9!'8 &$<%"))|n>1||[0,1,2,1,2,0].some((_,d,A)=>B[k=T.map(a=>[(h=n=>Math.min(...T.map(R=a=>a[A[(d+n)%6]]))-R(a))(0),h(3),(x=(a[4]+d*2)%3,d>2)*x?3-x:x]).sort()])?N:B[k]=++N

```

Try it online! (\\$n=1\\$ to \\$n=13\\$)

## How?

### Directions and tiles

We use the following codes for the 6-direction compass and the tiles:

We assume that the creature is blue.

### Connections

We need a table to know which parts of the creature need to be connected to other tiles when we enter a given tile in a given direction:

```
     |  T=0  |  T=1  |  T=2
-----+-------+-------+-------
 d=0 | 0,4,5 | 1,2,4 |   4
 d=1 | 0,3,5 | 1,2,3 |   3
 d=2 | 0,3,4 |   0   | 0,1,2
 d=3 | 3,4,5 |   5   | 1,2,5
 d=4 |   2   | 2,3,4 | 0,2,5
 d=5 |   1   | 1,3,4 | 0,1,5

```

*Example:*

If we enter a tile of type \\$1\\$ with direction \\$5\\$, we need to connect in directions \\$1\\$, \\$3\\$ and \\$4\\$:

But the way the tiles are designed, there can't possibly be a single missing connection in a single direction. A consequence of that is that we can ignore one direction entirely and still be able to detect if the path is closed or not. By convention, we are going to ignore direction \\$5\\$.

```
     |  T=0  |  T=1  |  T=2
-----+-------+-------+-------
 d=0 |  0,4  | 1,2,4 |   4
 d=1 |  0,3  | 1,2,3 |   3
 d=2 | 0,3,4 |   0   | 0,1,2
 d=3 |  3,4  |   -   |  1,2
 d=4 |   2   | 2,3,4 |  0,2

```

These updated sets of directions are first re-encoded as 5-bit integers, and then as ASCII characters with a fixed offset of \\$+32\\$:

```
     |  T=0  |  T=1  |  T=2              |  T=0  |  T=1  |  T=2
-----+-------+-------+-------       -----+-------+-------+-------
 d=0 |   17  |   22  |   16          d=0 |  "1"  |  "6"  |  "0"
 d=1 |    9  |   14  |    8          d=1 |  ")"  |  "."  |  "("
 d=2 |   25  |    1  |    7    -->   d=2 |  "9"  |  "!"  |  "'"
 d=3 |   24  |    0  |    6          d=3 |  "8"  |  " "  |  "&"
 d=4 |    4  |   28  |    5          d=4 |  "$"  |  "<"  |  "%"

```

Once flattened, this gives:

```
D = Buffer("160).(9!'8 &$<%")

```

### Coordinates

To describe the positions of the tiles, we use cube coordinates with \\$x+y+z=0\\$:

*Credits: www.redblobgames.com*

It will make it easier to process rotations and reflections in the final step of the algorithm.

### Tile encoding

The tiles are stored in a list, with no specific order. It means that we don't have to worry about some dynamic 2D allocation and we can easily iterate on the existing tiles. The downside is that, given specific coordinates, we need to `find()` the corresponding tile in the list.

Each tile is stored as \\$(x, y, z, m, t)\\$ where:

* \\$(x, y, z)\\$ are the cube coordinates of the tile as described above
* \\$m\\$ is the 5-bit mask of directions that need to be connected
* \\$t\\$ is its type (\\$0\\$, \\$1\\$ or \\$2\\$)

### Algorithm

We start with a single tile of type \\$1\\$ at \\$(0,0,0)\\$, with a required connection in direction \\$0\\$:

Therefore, this tile is encoded as `[0,0,0,1,1]`.

At each iteration, we look for:

* Tiles with missing connections: in this case, we successively try to complete the connection with each type of tile.
* Tiles that are already connected but for which new connections need to be added because they have been reached in a different direction: in this case, we update the direction mask (with a bitwise OR) and force a new iteration.

If all connections are valid *and* we have reached the requested number of tiles, we still need to test whether it is a new creature or just a modified version of an existing one:

1. We apply the following transformations:

* We perform the 3 possible rotations by replacing \\$(x,y)\\$ with \\$(x,y)\\$ (no rotation), \\$(y,z)\\$ (120°) or \\$(z,x)\\$ (240°), and updating the types of the tiles accordingly.
    * We perform the 3 corresponding reflections by replacing \\$(x,y)\\$ with \\$(y,x)\\$, \\$(z,y)\\$ or \\$(x,z)\\$, and updating the types of the tiles accordingly.
2. For each transformation, we translate all tiles such that the bottom-right corner is always located at \\$(0,0)\\$. (The signs of the coordinates are inverted in the process, which technically leads to another reflection, but this is harmless.)
3. We sort the tiles according to their coordinates and types. (This sort is processed in lexicographical order, which is fine.)
4. We finally coerce the resulting list to a key string which can be compared with the other keys.
5. We abort as soon as a known key is matched, or store the new key and increment the final result if none of the transformations lead to a known key.

## Commented

```
f = (n, T = [B = [N = 0, 0, 0, 1, 1]]) =>
  // abort if n = 0
  !n ||
  // for each tile in T
  T.some(([x, y, q, m]) =>
    // for d = 0 to d = 4
    B.some((p, d) =>
      // if this tile requires a connection in this direction
      m >> d & 1 && (
        // look for a connected tile t at the corresponding position (p, q)
        (
          p = x + ~-s[d],
          q = y + ~-s[d + 2],
          t = T.find(([X, Y]) => X == p & Y == q)
        ) ?
          // if t exists, make sure that its direction mask is up-to-date
          (q = t[3]) & (p = D[d * 3 + t[4]]) ^ p ?
            // if it's not, update it and force a new iteration
            t[f(n, T, t[3] |= p), 3] = q
          :
            0
        :
          // if t does not exist, try each type of tile at this position
          [0, 1, 2].map(t => f(n - 1, [...T, [p, q, -p - q, D[d * 3 + t], t]]))
      )
    ),
    // s is used to apply (dx, dy)
    s = "2100122",
    // D holds the direction masks for the connections
    D = Buffer("160).(9!'8 &$<%")
  ) |
  // stop here if the above some() was truthy or we have more tiles to add
  n > 1 ||
  // otherwise, apply the transformations
  [0, 1, 2, 1, 2, 0].some((_, d, A) =>
    B[
      // compute the key k
      k =
        // by generating the updated tuples [x, y, type] and sorting them
        T.map(a =>
          [
            // transform the 1st coordinate
            (h = n => Math.min(...T.map(R = a => a[A[(d + n) % 6]])) - R(a))(0),
            // transform the 2nd coordinate
            h(3),
            // update the type
            (x = (a[4] + d * 2) % 3, d > 2) * x ? 3 - x : x
          ]
        ).sort()
    ]
  ) ?
    // if the key was found, just return N
    N
  :
    // if this is a new creature, store its key and increment N
    B[k] = ++N

```

---
Tags: code-golf, sequence, hexagonal-grid, restricted-time
---


title: BLUEREDGOLDEGGSFEATHERSFEATHERS

text:
# Question
Title: BLUEREDGOLDEGGSFEATHERSFEATHERS
There's a little-known secret in Banjo-Kazooie that you can interleave the three Cheato codes on the Treasure Trove Cove Sandcastle floor and it will still recognize all of them. So you could, for instance, enter `BLUREEGOLDDFFEEGEAATHTHEEGSRSRS`, activating `BLUEEGGS`, `REDFEATHERS`, and `GOLDFEATHERS` all at once.

# Challenge

Your task is to take a list of cheat codes and a code entry and determine which of the codes are activated.

A code entry is valid if and only if some substring of the entry can spell out a subset of the cheat codes by assigning letters one at a time to exactly one word in order until all codes are exactly filled in. For example, applying this to the above code entry:

```
BLUREEGOLDDFFEEGEAATHTHEEGSRSRS

BLU_E________E_G_________GS____
___R_E___D_F__E__A_TH__E___RS__
______GOL_D_F___E_A__TH_E____RS

```

## Other Assumptions

* Both cheats and entries will contain only uppercase letters A-Z.
* Each code in the input list will appear only once.
* If two cheat codes share a prefix or a suffix, their shared letters must still appear twice to be counted, thus `REDGOLDFEATHERS` would, for the purposes of this challenge, only return `GOLDFEATHERS`.
* Each code entry can only contain one matching substring.
* If it is ambigous how a code-matching substring could be chosen, choose the one that starts the earliest and is the longest match for that particular starting point.
* The order of matched codes returned does not matter.
* If it is ambiguous which code could be used, prefer cheat codes that appear earlier in the code list.
* A substring *does not* match if some of the letters inside it cannot be assigned to a cheat code. For instance `BLUEXEGGS` does not match any cheat codes.
* If no codes are matched, you may return an empty list or any falsy value.

*Note that this may not necessarily be consistent with the nuances of the game\`s implementation*

# Example Test Cases

```
Codes:
  BLUEEGGS

Entry: BLUEEGGS

Result:
  BLUEEGGS

```

```
Codes:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Entry: BANJOGOLDBLUREEDFEATHEERGGSSKAZOOIE

Result:
  BLUEEGGS
  REDFEATHERS

```

```
Codes:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Entry: KAZOOIEBLUREEGOLDDFFEEGEAATHTHEEGSRSRSBANJO

Result:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

```

```
Codes:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Entry: BANJOKAZOOIE

Result: <falsy>

```

```
Codes:
  CAT
  DOG

Entry: CCADOGATT

Result:
  DOG
(The substring may not contain the same code twice)

```

```
Codes:
  COG
  ATE
  CAT
  DOG

Entry: CDCOAGTE

Result:
  DOG
  CAT
(Match the earliest and longest substring)

```

```
Codes:
  ACE
  BDF
  ABC
  DEF

Entry: ABCDEF

Result:
  ACE
  BDF
(Prefer matching codes earlier in the list)

```

# Rules/Scoring

Standard procedure for code golf applies. I/O can use any convenient format. Fewest bytes wins.

# Answer
# Brachylog, 25 bytes

```
hsS&t⊇.g;Sz{∋ʰ}ᵐhᵍ{tᵐc}ᵐp

```

Try some of the faster test cases online!

Extremely slow brute force, that I haven't verified on the longer test cases yet. It wouldn't surprise me if a clever implementation of a smarter algorithm turns out considerably shorter. Takes input as a list `[entry,codes]` through the input variable and outputs through the output variable if it succeeds. Seems to comply fully with the spec to the extent to which I've tested it at all.

The exact nature of the brute force is that for every substring of the entry (until there's a match), it tries every subset of the codes until it's possible to assign one code to each letter of the substring such that the letters assigned to each code taken in order form that code. The worst case complexity, where the worst case is failure, is something vaguely along the lines of \\$O(x^22^yy^x)\\$ with \\$x\\$ the length of the entry and \\$y\\$ the number of codes.
> 6 votes

# Answer
# Python 2, ~~419~~ 416 bytes

```
def f(a,s):
 V=[]
 for u,c in((u,c)for z in product(*[g(c,s)for c in a])for u,c in zip(S(z),S(a))):A=set(sum(u,[]));L=sum(map(len,u));V+=A and(len(A)==L>max(A)-min(A))*[(min(A),-L,c)]
 return V and sorted(V)[0][2]
S=lambda A:A and[u+[A[0]]for u in S(A[1:])]+S(A[1:])or[[]]
def g(c,s,i=0):
 r=[[]]*(c=='')
 while c and c[0]in s[i:]:i=s.find(c[0],i)+1;r+=[u+[i-1]for u in g(c[1:],s,i)]
 return r
from itertools import*

```

Try it online!

After some trivial spaces being removed, still pretty long!

The function `S` returns the power set of a collection. The function `g(c,s)` return a list whose elements are a list of indexes of a potential embedding of the code `c` in the entry string `s`.

The function `f(a,s)` then looks at all possible combinations of embeddings of some or all of the codewords in s, selecting those which end up being a continuous sub-string of `s` (the bit about `A` and `L` first ensures that the particular choice of embeddings are pairwise disjoint, and then that there are no gaps).

By nature of the use of `product` and the action of `S`, the unsorted results will "prefer cheat codes that appear earlier"; we then further sort by first the starting index of such a substring, and then by length in case of a tie; so that in case of a tie for both starting index and length, the original ordering will prevail as I think was demanded.

If no embeddings are found, the empty list is returned.

I'm guessing the `g` can be golfed a bit more, at the expense of a much longer running time...
> 2 votes

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


title: Postman Delivery

text:
# Question
Title: Postman Delivery
I just got a job as a postman and I need your help to keep it. I have to order a lot of mails before I go out to deliver them.

Streets are numbered strictly sequentially, starting with 1 at the start of the street, and continuing in order skipping no numbers until the end, with odd numbers on the left side and evens on the right side. Plus houses were added later so we may also have letters appended to the civic number.

The chest contains all mail of the city so I have to choose only mails of my street.

I need your help to order the mails faster. What I ask you is to write a function or full program taking:
\- A street name.
\- A list of civic numbers ordered following my path.
\- A list of addresses (representing the mail chest).

And output a list of addresses containing only the ones of my street, ordered following the list of civic numbers.

An address has the form :

```
 Person Name/n
 CivicN Street Name

```

Where *CivicN* is a number that can be followed by a '/' and an UPPERCASE LETTER (10 10/B). If you prefer, lowercase is acceptable.

If Streets Names overlaps they are considered different streets:

```
Church Road  != Saint Lorenz Church Road

```

We omit the rest of the address for simplicity (assuming it is the same for every mail)

Letters must be delivered fast so shortest answer wins.

**EXAMPLE:**

Layout :

```
 1 1/B     3 5 7      9 11 13
 ==============================
       2 4       4/B 6

```

Input :

```
"Tea Avenue"
["1","1/B","2","4","3","5","7","4/B","6","9","11","13"]
["Mrs. Pie O. Pinky\n6 Tea Avenue","Ms. Kita I. Omeeha\n6 Tea Avenue","Mr. Raile A. Lee\n26 Uea Grove","Odd O. Nic\n76 Mira Road","Mrs. Fuel Tee\n78 Uea Grove","Ny O. Ondip\n55 Uea Grove","Mrs. Black\n67 Uea Grove","Ollie E.\n11 Tea Avenue","Mr. Urna Li\n75 Mira Road","Ms. Polly\n2 Tea Avenue"]

```

Output :

```
Ms. Polly
2 Tea Avenue

Mrs. Pie O. Pinky
6 Tea Avenue

Ms. Kita I. Omeeha
6 Tea Avenue

Ollie E.
11 Tea Avenue

```

Input :

```
"Church Road"
["1","3","5","5/B","2","4","7","7/B","6","9","9/B","11","11/B"]
["Billy Ray V.\n5 Church Roadside East","Ms. Mia\n5 Church Road","Mrs. Dadeos\n9/B Church Road","Dr. Ymin U.\n3 Church Road","Atty. Nerou\n3 Church Road","Ollie A. Chaim\n6 Saint Lorenz Church Road","Ms. Rose\n5 Church Road","Alf Taohy\n79 Berry Road","Ms. Ootr E.\n5 Saint Lorenz Church Road","Lol E.\n21 Berry Road","Ms. Norton\n2 Church Road"]

```

Output :

```
Dr. Ymin U.
3 Church Road

Atty. Nerou
3 Church Road

Ms. Mia
5 Church Road

Ms. Rose
5 Church Road

Ms. Norton
2 Church Road"

Mrs. Dadeos
9/B Church Road

```

Test generator: Try it online! Change string\_wrapper\_left/right and separator to modify formatting.

Rules :
\- Standard loopholes are forbidden.
\- Standard input/output methods.
\- Shortest answer in bytes wins.

# Answer
# 05AB1E, ~~15~~ ~~13~~ 12 bytes

```
ε²ðýUʒ¶¡Xk]˜

```

-2 bytes by porting *@JonathanAllan*'s Jelly answer, so make sure to upvote him!
-1 byte thanks to *@Grimy*.

Inputs are in the order: \[list of civic numbers\], street name, \[list of addresses\].

Try it online.

**Explanation:**

```
ε       # Map over the (implicit) input-list of civic numbers
 ²      #  Push the second street-input
  ðý    #  And join the two values by a space
    U   #  Pop and store this street + num string in variable `X`
 ʒ      #  Filter the (implicit) input-list of addresses by:
  ¶¡    #   Split on newlines
    Xk  #   Get the index of string `X` (street + num) in this list,
        #   which will be either -1 (not found), 0 (first address-line), or
        #   1 (second address-line), and only 1 is truthy in 05AB1E
]       # After both the inner filter and outer map:
 ˜      # Flatten the array to remove any empty inner lists
        # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Jelly, 13 bytes

```
,⁵KỴṪ⁼ɗƇ@ɗ€ẎY

```

A full program accepting three arguments - a list of civic numbers on your named street, a list of the addresses in the mail chest, and your street name - which prints the addresses to which you need to deliver in the order of the given civic numbers.

**Try it online!**

### How?

```
,⁵KỴṪ⁼ɗƇ@ɗ€ẎY - Main link: civic numbers, addresses
          €   - for each (civic number):
         ɗ    -   last three links as a dyad - i.e. f(civic number, addresses):
,⁵            -     pair (the civic number) with 3rd program input (the street name)
  K           -     join (that) with a space -- i.e. X=civic number+' '+street name
        @     -     with swapped arguments i.e. f(addresses, X):
       Ƈ      -       filter (the addresses) keeping those for which:
      ɗ       -         last three links as a dyad - i.e. f(address, X):
   Ỵ          -           split (address) at newlines
    Ṫ         -           tail (get the second line)
     ⁼        -           equals (X)?
           Ẏ  - tighten (the list of lists to a single list)
            Y - join with newlines

```
> 4 votes

# Answer
# JavaScript (Node.js), 58 bytes

```
(s,n,a)=>n.flatMap(n=>a.filter(x=>x.split`
`[1]==n+' '+s))

```

Try it online!

### Commented

```
(s, n, a) =>          // s = street name, n[] = civic numbers, a[] = addresses
  n.flatMap(n =>      // for each civic number n in n[]:
    a.filter(x =>     //   for each address x in a[]:
      x.split`\n`[1]  //     keep it if the 2nd part is equal to
      == n + ' ' + s  //     n + space + expected street name
    )                 //   end of filter()
  )                   // end of flatMap() (empty entries are discarded)

```
> 2 votes

# Answer
# Perl 5, 51 bytes

```
sub{my($r,$a,@B)=@_;map{$n=$_;grep/
$n $r$/,@B}@$a}

```

Try it online!
> 2 votes

# Answer
# Ruby, 65 bytes

```
->s,o,n{n.grep(/\d\S* #{s}$/).sort_by{|i|o.index i[/\d+(\/.)?/]}}

```

Try it online!
> 2 votes

# Answer
# Python 3, 65 bytes

```
lambda s,n,m:[a for i in n for a in m if a.endswith('\n%s '%i+s)]

```

Try it online!

Also works in Python 2.

For each number `i` in the list of civic numbers `n`, the function will iterate over *all* addresses `a` in the list of mail `m` and keep the ones where the combination of the civic number `i` and the street name `s` matches with `a`. This results in a sorted and filtered list.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 63 bytes

```
(a,b,c)=>b.SelectMany(x=>c.Where(l=>l.Split('\n')[1]==x+" "+a))

```

Try it online!
> 1 votes

# Answer
# Python 3, **79** ~~85~~ bytes (thanks to squid)

```
d=lambda s,n,a:n and[k for k in a if k.split('\n')[1]==n[0]+' '+s]+d(s,n[1:],a)

```

### old:

```
d=lambda s,n,a:[k for k in a if k.split('\n')[1]==n[0]+' '+s]+d(s,n[1:],a)if n else[]

```
> 1 votes

# Answer
# Kotlin, 145 bytes

```
fun p(s:String,o:List<String>,m:List<String>):List<String>
=if(o.size<1)List(0){""}
else
m.filter{it.split("\n")[1]==o[0]+" "+s}+p(s,o.drop(1),m)

```

Try it online!
> 1 votes

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


title: The reversible reverser

text:
# Question
Title: The reversible reverser
Your task is simple. The program reads in a line of text from the standard input, and it prints out the same text in a character-reversed form. It is not allowed to print anything else.

For example:

input: "Hello!", output: "!olleH"

**The catch is**, your program has to be able to do the exact same thing if the source code itself is character-reversed!

Scoring: standard code-golf scoring applies, with the following modification to limit the boring

```
//margorp
program//

```

style answers: any solution which is a palindrome will incur a +25% penalty to the score, rounded up. This penalty still applies, if you, for example, insert characters into the program which do not have any useful effects, just to break the palindrome.

# Answer
> 14 votes
## APL, 5

```
⌽⍞⍝⍞⊖

```

This reverses (, along the last axis) the input (), and is followed by a comment ( marks a line comment). Reversed, the program reverses (, along the first axis) the input, and is followed by a comment. Because the input is always going to be one dimensional, in this case  and  are functionally equivalent. It is perhaps even sneakier than the GolfScript solution, so here's a cleaner solution (no comments), which scores **9**.

```
⍬,⌽,⍞,⊖,⍬

```

This first grabs an empty vector (), flattens it (monadic `,`), and reverses it (, along the first axis). This still leaves an empty vector. Then it concatenates (dyadic `,`) to the input (), leaving the input untouched. It then flattens (monadic `,`) the already-flat input and reverses it (, along the last axis). Then it concatenates (dyadic `,`) another empty vector () to the reversed input. This does nothing, and leaves the reversed input behind. Reversed, this program does the same thing, based again on the fact that  and  are functionally equivalent with one-dimesional arguments.

You really couldn't say I'm adding useless characters to break the palindrome (the two different reverse functions are different with two-or-more-dimensional input; I'm just taking advantage of the fact they act the same with one-dimensional input)

# Answer
> 14 votes
# Unix shell - 8 + 25% = 10

```
rev||ver

```

Previous answer of `cat|tac` didn't actually work, `tac` reverses the order of lines, not the order of characters in a line.

# Answer
> 11 votes
# Haskell, 53

```
main=niam
niam=interact reverse
esrever tcaretni=main

```

Technically not a palindrome, but, since function declaration order doesn't matter, once reversed you have exactly the same program.

# Answer
> 10 votes
# **Ruby, 37**

```
eval <<1.reverse#
esrever.steg stup
1

```

Reversed:

```
1
puts gets.reverse
#esrever.1<< lave

```

# Answer
> 7 votes
## Tcl, 78

```
puts [string rev [gets stdin]];#\
]]nidts steg[ ver gnirts[ stup;# tixe emaner

```

Not a palindrome.

# Answer
> 6 votes
# gs2, 2

~~(Yes, this language was made before the challenge. No, it isn't a joke or a loophole. ASCII space (`0x20`) is reverse.)~~

EDIT: aw, man, this question is super old? If only I'd commited sooner. :\< I'll leave this answer up just because it's too good to pass up, though.

# Answer
> 3 votes
### Golfscript, 9 (7 * 1.25 = 8.75)

```
-1%#%1-

```

dirty, dirty, dirty, but extremely short. `-1%` means "select each element (character), backwards" and `#` means "line comment". The rest is just a bit of GolfScript's I/O magic.

This is the shortest "clean" (no comments) solution I've found (**14 * 1.25 = 17.5**):

```
'';-1%..%1-;''

```

meaning: push an empty string, drop it, reverse the input, clone it twice, split it by itself (consuming two copies and producing an empty array), remove all ones from the empty array, drop the emtpy array, push an empty string and (implicitly) print the stack.

# Answer
> 3 votes
## Ruby, 44

```
puts gets.reverse#esrever.steg stup

```

Just a comment at the end of a normal program :P

35 characters, +25% = 44

# Answer
> 2 votes
## Tcl, 75.25

This time a palindrome.

```
puts [string rev [gets stdin]]]]nidts steg[ ver gnirts[ stup

```

# Answer
> 2 votes
# Python 3, 42

```
print(input()[::-1]);#)]1-::[)(tupni(tnirp

```

## Credits

* Initial version with score of 49 + 25% = 61.25 created by me
* Thanks to arshajii for improving the score from 61.25 to 51.25
* New version with score of 42 (`:-)`) created by me

# Answer
> 2 votes
### Rebmu: 9 (w/penalty) or 13 (without)

The boring Rebmu solution is 9 and bears the palindromic penalty. I'll show it anyway "just because":

```
rnRVaVRnr

```

Using the unmushing trick of noticing capital runs of letters are separate words, and the lack of a leading capital run means we're not making a set-word, we produce five ordinary words:

```
rn rv a vr nr

```

Which is a shorthand for the equivalent code (also legal Rebmu):

```
return reverse a vr nr

```

The fact that vr and nr are meaningless doesn't matter, because despite not being assigned to anything they are valid words. So the evaluator only runs the `return reverse a`...it works both ways. But this is analogous in a sense to the boring cheat: the code isn't commented out, but it's dead and not executed on one path.

For something more exciting that doesn't incur the penalty, how about this 13 character solution:

```
a VR :rv AvrA

```

Let's look at how this is processed on its forward and reverse paths, when expanded. Forward:

```
a               ; evaluate a, as it is a string it has no side effects
vr: :reverse    ; "set" vr to mean what a "get" of reverse means now
a: vr a         ; assign a to calling "vr" on a, effectively reversing
                ;   ^-- result of assign is last expression, the answer!

```

Backwards as `ArvA vr: RV a`:

```
a: reverse a    ; assign A to its reversal
vr: rv: a       ; make the abbreviation vr equal to assignment of a to rv
                ;   ^-- result of assign is last expression, the answer!

```

On the downside, the backwards variant is overwriting the abbreviation for reverse. But hey, it's not a palindrome, and it's a mere 13 characters. :-)

*(Note: This assumes you're running Rebmu in the /args mode, where a is the default argument to the program passed to the interpreter on the command line and you accept the result. If reading from standard input is actually a requirement, things grow e.g. from 9 to 11 characters for the simple solution: `rnRVrArVRnr`. And if you have to print to standard output from within the program instead of accepting the expression output of the interpreter that would add a couple characters too.)*

# Answer
> 2 votes
## JavaScript, 62 * 1.25 = 78

```
i.split('').reverse().join('')//)''(nioj.)(esrever.)''(tilps.i

```

Not too creative, but the best I could come up with. (assumes that the input is stored in variable `i`)

I did get this:

## 63 chars, no palindrome

```
i.split('').reverse().join('')//)a(nioj.)(esrever.)''=a(tilps.i

```

but it felt too much like cheating. :P I could do many more trivial changes (such as using `i['split']` instead of `i.split`), but all those still feel like cheating :P

# Answer
> 2 votes
## Pyke, 2 (+25%), non-competing

```
_

```

Pyke takes input implicitly and outputs implicitly.

`_` is the reverse function.

# Answer
> 1 votes
## Tcl, 99

```
proc unknown args {puts "Hello World!"}
}"!dlroW olleH" stup{ sgra nwonknu corp

```

If a command that does not exist is called, a special `unknown` command is called that could load the command. Or do other funny stuff.

# Answer
> 1 votes
## T-SQL, 86\*1.25=108

Here's a boring palindromic entry for SQL Server 2008 (and newer) just to show that it's possible.

```
DECLARE @ VARCHAR(MAX)='Hi'PRINT REVERSE(@)--)@(ESREVER TNIRP''=)XAM(RAHCRAV @ ERALCED

```

@ holds the input text, the example string being "Hi". This entry's char count is for a two-char input string.

# Answer
> 1 votes
## Keg, ceil(1+0.25)=2 bytes

```
?

```

This takes input and reverses, and implicit output outputs it literally. TIO

# Answer
> 1 votes
# Befunge-98 (PyFunge), 17 bytes

```
#[~   #<
 [:!k@,v

```

Try it online!

Try it online! (Reversed)

# Answer
> 0 votes
## QBIC, 14 + 25% = 18 bytes

```
;?_fA|#|Af_?;

```

Employs a palindromic source code. Using two distinct ways to do this takes somewhat longer (34 bytes):

```
;[_lA|,1,-1|Z=Z+mid$(A,a,1)#|Af_?;

```

Explanation:

```
Read the input string from the command line as A$
;

FOR len(A$); a >= 1; a--
[        Starts a FOR loop
_l...|   returns the length the argument(here, A$); sets the starting point of the loop
,1       set the end point of the loop
,-1      FOR loop incrementer (or decrementer in this case)
|        Ends the argument list for the FOR loop

On each FOR iteration, add the right-most character of the input to Z$
Z=Z+mid$(A,a,1)

The cheat:
# starts a string literal, hiding the flipped source.
    The literal is closed implicitly at the end-of-file.
    The FOR loop is closed implicitly at the end-of-file.
    Z$ gets printed implicitly at the end of the program if it's non-empty

The flipped source is the same as my palindrome-code:
;       reads in A$ from the cmd line
 ?      PRINT
  _fA|  The reversed version of A$
      # And hide the rest of our source in a literal

```

# Answer
> 0 votes
# Pushy, 7 bytes (5 + 25%)

```
@"i"@

```

**Try it online!**

This incurs the 25% penalty as it's a palindrome, but it's the best I could do. No matter which way around the program is run, it does these 3 commands:

```
@     \ Reverse the input
 "    \ Print
  i   \ Exit

```

Substituting `i` for `c` (clear stack) or `\` (comment) has the same effect.

# Answer
> 0 votes
# 05AB1E, 1 + 25% = 2 bytes

```
R

```

Try it online!

# Answer
> 0 votes
# , 65 bytes

### EDIT: Ditched the 25% penalty thanks to a trivial, yet unseen to me, change by Grimy.

```
stringi::stri_reverse(scan(,""))#))'',(nacs(esrever_irts::ignirts

```

Try it online!

Say hello to R's abysmal ability to handle strings, even when you use packages designed for strings like `stringi` ... **barf**

---
Tags: code-golf, source-layout
---


title: Sample a random non-decreasing sequence

text:
# Question
Title: Sample a random non-decreasing sequence
**Input:** Two integers n and k given in any form that is convenient for your code

**Output** A random non-decreasing sequence of k integers, each in the range 1 to n. The sample should be chosen uniformly from all non-decreasing sequences of k integers with integers in the range 1 to n.

The output can be in any reasonable format you find convenient.

You can use whatever pseudo-random generator your favorite library/language provides.

We can assume that the integers n,k \> 0.

**Example**

Say n,k = 2. The non-decreasing sequences are

```
1,1
1,2
2,2

```

Each sequence should have probability 1/3 of being outputted.

**Restriction**

Your code should run in no more than a few seconds for k = 20 and n = 100.

**What doesn't work**

If you just sample each integer randomly from the range 1 to n and then sort the list you won't get a uniform distribution.

# Answer
> 1 votes
# Actually, ~~14~~ 12 bytes

This answer is based on Emigna's 05AB1E answer and the answers on this Math.SE question. Golfing suggestions welcome! Try it online!

```
;;ra+DR╚HS♀-

```

**Ungolfing**

```
      Implicit input n, then k.
;;    Duplicate k twice.
r     Push range [0...k] for later.
a     Invert the stack. Stack: n, k, k, [0...k]
+DR   Push the range [1..n+k-1].
╚     Shuffle the range. Stack: shuffled_range, k, [0...k]
H     Push the first k elements of shuffled_range. Call this increasing.
S     Sort increasing so the elements are actually increasing.
♀-    Subtract each element of [0...k] from each element of increasing.
      This gives us our non-decreasing sequence.
      Implicit return.

```

# Answer
> 15 votes
## Python, 89 bytes

```
from random import*
lambda n,k:[x-i for i,x in enumerate(sorted(sample(range(1,n+k),k)))]

```

Generating an *increasing* sequence rather than a *non-decreasing* one would be straightforward: this is just a random subset of `k` numbers between `1` and `n`, sorted.

But, we can convert an increasing sequence to a non-decreasing one by shrinking each gap between consecutive numbers by 1. So, a gap of 1 becomes a gap of 0, making equal numbers. To do so, decrease the `i`'th largest value by `i`

```
r[0], r[1], ..., r[n-1]  =>  r[0]-0, r[1]-1, ..., r[n-1]-(n-1)

```

For the result to be from `1` to `n`, the input must be from `1` to `n+k-1`. This gives a bijection between non-decreasing sequences of numbers between `1` and `n`, to increasing sequences between `1` and `n+k-1`. The same bijection is used in the stars and bars argument for counting such sequences.

The code uses the python function `random.sample`, which takes `k` samples without replacement from the input list. Sorting it gives the increasing sequence.

# Answer
> 7 votes
# 05AB1E, 13 bytes

```
+<L.r¹£{¹L<-Ä

```

Try it online!

**Explanation**

```
+<L            # range [1 ... n+k-1]
   .r          # scramble order
     ¹£        # take k numbers
       {       # sort
        ¹L<-   # subtract from their 0-based index
            Ä  # absolute value

```

# Answer
> 7 votes
## Python, 87 bytes

```
from random import*
f=lambda n,k:k>random()*(n+k-1)and f(n,k-1)+[n]or k*[7]and f(n-1,k)

```

The probability that the maximum possible value `n` is included equals `k/(n+k-1)`. To include it, put it at the end of the list, and decrement the needed numbers remaining `k`. To exclude it, decrement the upper bound `n`. Then, recurse until no more values are needed (`k==0`).

Python's `random` doesn't seem to have a built-in for a Bernoulli variable: 1 with some probability, and 0 otherwise. So, this checks if a random value between 0 and 1 generated by `random` falls below `k/(n+k-1)`. Python 2 would the ratio as float division, so we instead multiply by the denominator: `k>random()*(n+k-1)`.

# Answer
> 5 votes
## JavaScript (Firefox 30+), 74 bytes

```
(n,k,i=0,j=k)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)i-j+k--]

```

### Explanation

xnor's excellent Python answer contains a very good summary of how/why the technique used here works. The first step is to create the range **\[1, 2, ..., n + k - 1\]**:

```
(n,k,i=0)=>[for(_ of Array(q=k+n-1))++i]

```

Next we need to take **k** random items from this range. To do this, we need to select each item with probability **s / q**, where **s** is the number of items still needed and **q** is the number of items left in the range. Since we're using an array comprehension, this is fairly easy:

```
(n,k,i=0)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)k--&&i]

```

This gives us a uniformly distributed *increasing* sequence of numbers. This can be fixed by subtracting the number of items **j** that we have previously found:

```
(n,k,i=0,j=0)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)k--&&i-j++]

```

Finally, by storing **k** in **j**, we can incorporate `k--` into the expression and save a few bytes:

```
(n,k,i=0,j=k)=>[for(_ of Array(q=k+n-1))if(Math.random(++i)<k/q--)i-j+k--]

```

# Answer
> 2 votes
# TI-BASIC, 53 Bytes

```
Prompt N,K
K→dim(L1
While K
If rand<K/(N+K-1
Then
N→L1(K
K-1→K
Else
N-1→N
End
End
L1

```

Follow's xnor's logic, with a small caveat. We could theoretically shave a byte by doing something like this:

```
K>rand(N+K-1

```

But rand( is reserved to create a list of random numbers, so we wouldn't be able to do the desired implicit multiplication to save a byte.

This should run decently fast on an 84+ per the restriction but I'll check to make sure when I can.

# Answer
> 1 votes
# PHP, ~~77~~ ~~75~~ 73 bytes

```
foreach(array_rand(range(2,$argv[1]+$k=$argv[2]),$k)as$v)echo$v+1-$i++,_;

```

Run like this:

```
php -r 'foreach(array_rand(range(2,$argv[1]+$k=$argv[2]),$k)as$v)echo$v+1-$i++,_;' -- 10 5 2>/dev/null;echo
> 1_4_6_9_9_

```

# Explanation

```
foreach(                    # Iterate over...
  array_rand(               #   a (sorted) random number of items from...
    range(                  #     an array with items...
      2,                    #       from 2
      $argv[1]+$k=$argv[2]  #       to n + k (set arg 2 to $k)
    ),
    $k                      #     Take k number of items (their keys)
  )
  as $v
)
  echo $v +1 - $i++,"_";    # Print the value subtracted by the index.
                            # Need to add 1, because keys are 0-indexed.

```

# Tweaks

* Saved 2 bytes by removing `end()` call and set `$argv[2]` to `$k` instead to shorten access to arguments
* Saved 2 bytes by removing the index from the foreach, since it's simply an incrementing number. Just increment `$i` each iteration instead

---
Tags: code-golf, random, probability-theory
---


title: Super Mario in Colors :)

text:
# Question
Title: Super Mario in Colors :)
Here is continuation of this question, this time lets compress/generate Mario in colors!

Image size is 64x64 (above one is zoomed). The required output is valid `<img ...>` tag with exact same image in dataURI form, working on chrome, firefox and safari (and IE4 - joke ;). In snippet below you can find example tag in required form and all needed data.

```
bmpHeader="424d760a00000000000078000000280000004000000040000000010004000000000000000000c40e0000c40e00000000000000000000000000002b81fc00081fcd00085a7200fcfafc005e5e5e001139b90008930b00ababab0000ff000000ff000000fffc00fcffab00abff000000ff000000ff00000000";

bmpPixels="[encoded data, 4096 characters]" //pixels

dataURI='data:image/bmp,%'+(bmpHeader+bmpPixels).match(/../g).join('%');
msg.innerText=`<img alt src=${dataURI}>`
pic.src = dataURI
```

```
pre {white-space: pre-line;word-break: break-all}
```

```
<img id="pic">
<pre id="msg"></pre>
```

You can use any dataURI image format supported by chrome, firefox and safari (e.g bmp, png, gif etc...). However my proposition is to use dataURI BMP format without base64 which is very simple and which is presented in snippet above - we have there `bmpPixels` string - each character in that string represents one pixel (colors from `0` to `f`) starting from left bottom pixel, line by line. In dataURI we join bmpHeader and bmpPixels and put char `%` between each two characters (hex num) - and thats all. In snippet below I also include bmp+base64 valid example (`img` tag to be valid need to have 'alt' attribute)

```
<img alt src=data:image/bmp;base64,Qk12CgAAAAAAAHgAAAAoAAAAQAAAAEAAAAABAAQAAAAAAAAAAADEDgAAxA4AAAAAAAAAAAAAAAAAACuB/AAIH80ACFpyAPz6/ABeXl4AETm5AAiTCwCrq6sAAP8AAAD/AAAA//wA/P+rAKv/AAAA/wAAAP8AAAAAVSVVJVUlVSVVJVUlVSVVJVUlVSVVJVVVUFVVVVBVVVVVJVUlVSVVJVUlVSVVJVUlVSVVJVUlVYhQSIiIUEiIiFUFVQVVBVUFVQVVBVUFVQVVBVUFVQVViFBIiIhQSIiIRAREBEQERAREBEQERAREBEQERAREBESIUEiIiFBIiIhEBEQERAREBEQERAREBEQERAREBEQERIhQSIiIUEiIiEQERAREBEQERAREBEQERAREBEQERAREiFBIiIhQSIiIRAREAREREUREBEQERAREBEQERAREBEREUERERFBEREQBERREFEQRRAAAAAAAAACIAAAAAAAAAAAAAAAAAAAAAABEFEEUQREQAAAAAAAAAECAAAAAAAAAVVVVUFVVVVBVBEREERF3EQAAAAAAAAAABIAAAAAAAABIiIhQSIiIUEgEREREd3d3AAAAAAAAAAAACIAAAAAAAEiIiFBIiIhQSAB3d0REd3dwAAAAAAAAAAAEgAAAAAAASIiIUEiIiFBIAHd3d3RHd3cAAAAAAAAAAAAIgAAAAABIiIhQSIiIUEgAcXcXd0R3d3AAAAAAAAAAAAQIAAAAAEiIiFBIiIhQSAARdEd3dHd3cBEUAAAAAAAAAEgAAAAAREREUERERFBEBER3d3d0R3dxEREEAAAAAAAAAIgAAAAAAAAAAAAAAAAARHcRd3RHd3EREQAQAAAAAAAAQIAAAFVQVVVVUFVVVQAHdxRHdEd0ERERBBAAAAAAAAAEgAAAiFBIiIhQSIiIBBd3REd3R3ABERABEAAAAAAAAAAIgACIUEiIiFBIiIgAR3d3d3dHEUAREEEQAAAAAAAAAASAAIhQSIiIUEiIiAABF3d3d0QREEABEQAAAAAAAAAAAAiAiFBIiIhQSIiIAAFEd3EXdEERdwAAAAAAAAAAAAAABAiIUEiIiFBIiIgABER3cUR3REREdwARAAAAAAAAAAAASERQREREUERERAAAd3d0RHd3d0RHcRFAAAAAAAAAAAAAAAAABlAAAAAAAABHd3d3d3d3REdxEAAAAAAAAAAAAAAAAAAFUAAAAAAAAEcRd3d3d3REdxFAAAAAAAAAAAAAAAAAAAZQAAAAAAAAABRHcRR3REd3EXAAQAAAAAAAAAAAAAAABVAAAAAAAAAAREcRREdEd3cUd0dEBAAAAAAAAAAAAAAGUAAAAAAAAAAAAHFEd0R3dxd3EREEAAAAAAAAAAAQAAVQAAEAAAAAAAAAAEd3RHd3F0EXcRFAAAAAAAAAAFEQBlAAEBAAAAAAAAAAAAAAd3cRF3dBERAAAAAAAAABUREWUREQEAAAAAAAAAAAAAB3d3F3dEQREAAAAAAAABURERZREREBAAAAAAAAAAAAAHd3d3dEdxAQAAAAAAAAFRERFlEREQEAAAAAAAAAAAAAB3d3d0RwAQAAAAAAAAAVEREWURERAQAAAAAAAAAAAAAHEXd3RAAAAAAAAAAAABURERZREREBAAAAAAAAAAAAAAEUR3cAAAAAAAAAAAAAFRERFlEREQEAAAAAAAAAAAAAAURHcAAAAAAAAAAAAAABUREVUREQEAAAAAAAAAAAAABEQAAAAAAAAAAAAAAAAAFREAZQARAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAIiIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzMiIiIgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMzIiIiIiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEDIiIiIiIzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERAiMiEiEjMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARMzMzIiIgAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMzMzMjMyADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADMzMjMyMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARERETAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMxERMzMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxMxETERMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADExETETMwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAzMRMQMzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACIiIiIhEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAiIiABEQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==>
```

You can presents you results in answer using codegolf snippets and include this CSS rule: `img {image-rendering: pixelated;width:256px;height:256px}` to zoom image.

UPDATE

I see that unconsciously I made 2 separate competitions in this question: first for programs (codes written in some programming language which produce result `img` tag), and second for `img` tags which contains results from compression tools. Both are interesting but main competition is for programs. Although I hope that someone shows that hand written program can achieve better results than 'compressed `img` tags' - but may be it is impossible?

# Answer
> 2 votes
## ~~800~~ 791 bytes (for the img tag)

```
img {image-rendering: pixelated;width:256px;height:256px}
```

```
<img alt src=data:;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAG1BMVEUAAAD8gSvNHwhyWgj8+vxeXl65ORELkwirq6tQs3kTAAAB3UlEQVRIx92VwW6jMBCGTUO6PfrfuOWaZbX3Jn6BII3kHsmB9wAJaa455rF3bGEwaeI97KFSx7IQ9sdvzz+WUeqrokButq73WeCplsgBG4vDxmaAwwGHXRaw2GGXASxg7XsuCyAvYI/2+J7Lwdrfdr95rC+AOJUBdH38Vf98nGax8UbWGR/s0QO5Tcr0PlcJlfv824UOtqYjdFo5ftbPbaF1OkSuTwG8nrEGjOPl7RV4OwPpGj/ATFmABeiLxwB7gOOqd4GBR0IOQMVNBCSLtzQLJ+pcNdWA6Ib3Qc3AQAFgoFyc3LbRSXIgJ4BhR+WypihMYdxgmByjV6nd2wg4+AxHYqyqsSg4DkFu0CtgVghfB2AtERVKYp8EEavlYvqgVkZ892XmoRobJKVU5cu1/biGLkDl9aFPydX3ckmAsEeHE3QTN1le1AKUlbfA9QV0oWeBBJBzYNzoRrmYSj0LpIAYxKPjAVATcBKga7sudJ8lT0Csw/XmzpHZkbmHiR6EAtLkhJRayiwq/eJBoK7TLsJZFA1OPPgE0ErgotZA6avwSWANAIwbgXQJMo2ZD3PwwMfkQtvJ78uQIdB9D3zCJRViM8kzbct5uJmIbanF/wPd9m5LgD932z+B+Tz8BfZ10E4lHGFMAAAAAElFTkSuQmCC>
```

Simply ran the image through OptiPNG.

*Thanks to Night2 and Jonathan Frech for helping save 9 bytes.*

# Answer
> 2 votes
# 755 bytes (img tag)

```
img {image-rendering: pixelated;width:256px;height:256px}
```

```
<img alt src=data:;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAG1BMVEUAAAD8gSvNHwhyWgj8+vxeXl65ORELkwirq6tQs3kTAAABwklEQVR4AcRPRwHFIBRjGPj5GKCpAODFv7YOAeTaXLPTZ8hwLNmtoPCBE1RhVRnBWljNCoSGZgQCpOleAD5AoZjug3Sq132+JNIJfoyD//3NXPlCZmS8AjeSZE9GkJz91rADAL7IYLV1GAqiV6C+dqkBtf6dGAZul84i/2GDYbZZ5rOfKmJLojQH7ionk/g41azWwctQ/Jr+LSElawT62gv4vGIUsstOPoGvKxCs8Q6JLwVJXMPfggpUSi+ETTvxSsCkGel8iq/+KVyUpnnacNT46WCnsLEKAmIr+bYcJemgU8pyRjspC0+yb1l0YbU+99shOFTYKbSPhwVXhb618sNC/XYVholzIVIbRVIGO/jmQtYzC0WY9hmyRvx4LN+PekWYJBHpEtrAx70TXAXHBWlOx8DdmhAn0eVrQArpHOgEe1f23XcAMZ0DvUBBu2sD7ClcinBbbrd6FilVob2ohw1gd+3Sinw0sAL5LGG2aRKL0BpU6/H8F2aqv6CuwS+Bw8DdRiGS1DDwWwCEYWAQjHnOM5KdDSq1ws9ZQGYm2DUYYWQAwP8D0sgQkR7AXEyIiAvKFYSyYoVIClSxQcIK4OkBAPZ10E6zEPFIAAAAAElFTkSuQmCC>
```

Ran Lewis's image through 200 iterations of zopflipng with all possible filter combinations enabled.

# Answer
> 1 votes
# Bash, 1447 ~~1565~~ bytes

Too much time on this one already. :)

```
N="1q/4xt/5E3S9n/3YWDwhfwblbew5x/4P/5Cw
1/va
1/oEw.Q/16p7/2X4
1s/2Z.Wc.Wc.Wc8.Z2/1bfhM.QLb/108dQ.Qc/2Kw
1/2V.W/b5/10/10
1/dO/10/10/10/40
1/ap/88w
1@4g/5S.Qx/2y.Qx
23
1/1k
3D4
2/5_/45wu2u2s/24/2cx41id1iv1/2d1r41q/5p
1/1e/3K11r5wt12/2r8w1p61u11vu2u4tAwT8wqE1xs4a3j9.R.R.Yde.R.Ys3/6kw/1z11u1w2uwzww
1/qK
1/sK_2v
1/5q2u2/36/1p/4w3B/3_
1/hLwwwwz
1/hiwwwww
1/8r/2u.Qz/3Cw2v
8_
1/pd/21w/3_
1/qI
1/oG1v11v111s1111s3v1/3@111t1
1/rI
2/1V.Wc.W
3e
3W
5/se.Q
1/tGw12w
1/pG.Q/1w2
1/p9wCwq11u112s12@31tAs4
6/1f
7i4/5N/44/1lx/1A_y/1y/3W
1/5X2/5CY/45y
10
2/3o.W2a.W2a.W2a251.Z221.T.T422qw1v11w1.QO11.T22w/12/13sw3.Te.T.T64wwvr326o2w/16vwwZv
3/7Z@zwu2u2r5/24o8oy5r36V/35w
1/2N4.S/1W44o44o44o44o44j/1D4.Sp
51
3/2g4.S.X@4.S.XW4.S.Xvwwwwww/40
1/gMw3wwwwwt3t
4/1U.W21.T.T1.W2a.W2/3111.T2/3U.T.T
5/13
4/1a11
i/7v.Qw/1_/45/3y/1u
1/8p/17w/2swDwW/10FZ
1/14
2/7Y@3www2/1_@/14/35
22
1/6tv11r.R1.R221t21r113r23rw3t111u11u6q34o.Y1r11111s1113t3v12r212r21v13s12t1112s11v1w
1a
8/68wxwx/22wxwx
1/X
7/2L3.U.U.YM/19.R.R.R.R.YS/143.U.U.Y
b/1j
o/1m11g2
e/1g
bC4
9/10
J/17
2Ya2s2
3/1r444444"
R=(/11 .Yr .X.X 211 .V.V .Yo3 .Z.Z 4s4s 131 22222)
for x in {Q..Z};{ N=${N//.$x/${R[i]}};i=$[i+1]; }
U=($N)
for((j=0;$j<62;j++)){
for((i=0;$i<${#U[j]};i++)){ c=${U[j]:i:1};[ "$c" = '/' ]&&c=${U[j]:i+1:2}&&i=$[i+2];T[$j]+=" $[64#$c]"; }
read p x t<<<${T[j]}
P=$[P+p]
S[$x]=$P
for n in $t;{ x=$[x+n];S[$x]=$P; }
}
echo "<img alt src=data:image,`for((j=0;$j<4096;j++)){ printf %%%02x ${S[j]}; }`>"

```

Try it online!

```
img {width:256px;height:256px}
```

```
<img alt src=data:image,%42%4d%76%0a%00%00%00%00%00%00%78%00%00%00%28%00%00%00%40%00%00%00%40%00%00%00%01%00%04%00%00%00%00%00%00%00%00%00%c4%0e%00%00%c4%0e%00%00%00%00%00%00%00%00%00%00%00%00%00%00%2b%81%fc%00%08%1f%cd%00%08%5a%72%00%fc%fa%fc%00%5e%5e%5e%00%11%39%b9%00%08%93%0b%00%ab%ab%ab%00%00%ff%00%00%00%ff%00%00%00%ff%fc%00%fc%ff%ab%00%ab%ff%00%00%00%ff%00%00%00%ff%00%00%00%00%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%55%50%55%55%55%50%55%55%55%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%25%55%88%00%48%88%88%50%48%88%88%55%48%55%05%55%05%55%05%55%05%55%05%55%05%55%05%55%05%55%05%55%05%55%88%00%00%88%88%50%48%88%88%50%48%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%88%00%00%88%88%50%48%88%88%50%48%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%88%00%00%88%88%50%48%88%88%50%48%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%88%00%00%88%88%50%48%88%88%50%04%44%01%11%11%11%44%44%04%44%04%44%04%44%04%44%04%44%04%44%04%44%44%00%44%44%44%50%44%44%44%01%11%14%44%14%44%11%44%00%00%00%00%00%00%00%88%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%44%14%41%14%41%11%10%00%00%00%00%00%00%00%40%80%00%00%00%00%00%00%55%55%55%50%55%55%55%50%55%04%44%50%11%11%77%11%00%00%00%00%00%00%00%00%04%80%00%00%00%00%00%00%48%88%88%00%48%88%88%50%48%04%44%50%44%77%77%77%00%00%00%00%00%00%00%00%00%08%80%00%00%00%00%00%48%88%88%00%48%88%88%50%48%00%77%77%44%44%77%77%70%00%00%00%00%00%00%00%00%04%80%00%00%00%00%00%48%88%88%00%48%88%88%50%48%00%77%77%77%74%47%77%77%00%00%00%00%00%00%00%00%00%08%80%00%00%00%00%48%88%88%00%48%88%88%50%48%00%71%77%17%77%44%77%77%70%00%00%00%00%00%00%00%00%04%08%00%00%00%00%48%88%88%00%48%88%88%50%48%00%11%74%47%77%74%77%77%70%11%14%00%00%00%00%00%00%00%48%00%00%00%00%44%44%44%00%44%44%44%50%44%04%44%77%77%77%74%47%77%71%11%11%04%00%00%00%00%00%00%00%88%00%00%00%00%00%00%00%00%00%00%00%00%00%44%77%11%77%74%47%77%71%11%11%00%10%00%00%00%00%00%00%40%80%00%00%55%50%55%55%55%50%55%55%55%50%07%77%14%47%74%47%74%11%11%11%04%10%00%00%00%00%00%00%04%80%00%00%88%00%48%88%88%50%48%88%88%50%48%77%44%47%77%47%70%01%11%10%01%10%00%00%00%00%00%00%00%08%80%00%88%00%00%88%88%50%48%88%88%50%48%77%77%77%77%47%11%40%11%10%41%10%00%00%00%00%00%00%00%04%80%00%88%00%00%88%88%50%48%88%88%50%48%17%77%77%77%44%11%10%40%01%11%00%00%00%00%00%00%00%00%00%08%80%88%00%00%88%88%50%48%88%88%50%48%44%77%71%17%74%41%11%77%00%00%00%00%00%00%00%00%00%00%00%04%08%88%00%00%88%88%50%48%88%88%50%04%44%77%71%44%77%44%44%44%77%00%11%00%00%00%00%00%00%00%00%00%48%44%00%44%44%44%50%44%44%44%00%00%77%77%74%44%77%77%77%44%47%71%11%40%00%00%00%00%00%00%00%00%00%00%00%00%06%50%00%00%00%00%00%00%47%77%77%77%77%77%77%44%47%71%10%00%00%00%00%00%00%00%00%00%00%00%00%00%05%50%00%00%00%00%00%00%47%11%77%77%77%77%74%44%77%11%40%00%00%00%00%00%00%00%00%00%00%00%00%00%06%50%00%00%00%00%00%00%00%14%47%71%14%77%44%47%77%11%70%00%40%00%00%00%00%00%00%00%00%00%00%00%05%50%00%00%00%00%00%00%00%44%47%11%44%47%44%77%77%14%77%47%44%04%00%00%00%00%00%00%00%00%00%00%06%50%00%00%00%00%00%00%00%00%00%71%44%77%44%77%77%17%77%11%11%04%00%00%00%00%00%00%00%00%10%00%05%50%00%01%00%00%00%00%00%00%00%00%47%77%44%77%77%17%41%17%71%11%40%00%00%00%00%00%00%00%51%10%06%50%00%10%10%00%00%00%00%00%00%00%00%00%00%77%77%11%17%77%41%11%10%00%00%00%00%00%00%01%51%11%16%51%11%10%10%00%00%00%00%00%00%00%00%00%00%77%77%71%77%74%44%11%10%00%00%00%00%00%00%15%11%11%16%51%11%11%01%00%00%00%00%00%00%00%00%00%00%77%77%77%77%44%77%10%10%00%00%00%00%00%00%15%11%11%16%51%11%11%01%00%00%00%00%00%00%00%00%00%00%07%77%77%77%44%70%01%00%00%00%00%00%00%00%15%11%11%16%51%11%11%01%00%00%00%00%00%00%00%00%00%00%07%11%77%77%44%00%00%00%00%00%00%00%00%00%15%11%11%16%51%11%11%01%00%00%00%00%00%00%00%00%00%00%01%14%47%77%00%00%00%00%00%00%00%00%00%00%15%11%11%16%51%11%11%01%00%00%00%00%00%00%00%00%00%00%01%44%47%70%00%00%00%00%00%00%00%00%00%00%01%51%11%15%51%11%10%10%00%00%00%00%00%00%00%00%00%00%44%40%00%00%00%00%00%00%00%00%00%00%00%00%01%51%10%06%50%01%10%10%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%10%00%00%00%00%01%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%03%00%22%22%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%03%33%22%22%22%20%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%33%32%22%22%22%22%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%01%03%22%22%22%22%22%33%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%11%10%22%32%21%22%12%33%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%11%33%33%33%22%22%20%03%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%03%33%33%33%23%33%20%03%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%33%33%32%33%32%30%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%11%11%11%13%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%33%11%11%33%33%30%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%31%33%11%13%11%13%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%31%31%11%31%13%33%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%03%33%11%31%03%33%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%02%22%22%22%22%11%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%22%22%20%01%11%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%01%11%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00>
```

---
Tags: code-golf
---


title: Tower of hanoi solver

text:
# Question
Title: Tower of hanoi solver
For reference as to what the tower of Hanoi is, either Google it or look on the Wikipedia page.

Your code should be able to do 2 things, and they are the following:

* Accept user input that specifies the number of discs at the starting point of the Hanoi tower
* Create output in a fashion of your choosing (so long as it is somehow logical) to show the solution to the tower puzzle.

An example of logical output would be the following (using a 4 disc start):

`L1L2C1L1R-2R-1L1L2C1C-1R-2C1L1L2C1`

`L` represents the left peg, `C` represents the center peg and `R` represents the right peg and the numbers are how far to move the disk on that peg and in what direction. Positive numbers represent the number of pegs moving towards the rightmost peg (because the disks start on the leftmost peg).

The rules to tower of Hanoi are simple:

* Only one disk may be moved at a time.
* Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg.
* No disk may be placed on top of a smaller disk.

The disks start on the leftmost peg, largest on the bottom, smallest on the top, naturally.

# Answer
# Husk, 5 bytes

```
↑≠⁰İr

```

Try it online!
Each `n` in the output represents moving disk `n` to the next available peg (wrapping cyclically).

### Explanation

```
   İr   The ruler sequence [0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, ...]
↑       Take while...
 ≠⁰     ... not equal to the input.

```
> 4 votes

# Answer
## Python, 76 chars

```
def S(n,a,b):
 if n:S(n-1,a,6-a-b);print n,a,b;S(n-1,6-a-b,b)
S(input(),1,3)

```

For instance, for N=3 it returns:

```
1 1 3  (move disk 1 from peg 1 to peg 3)
2 1 2  (move disk 2 from peg 1 to peg 2)
1 3 2  (move disk 1 from peg 3 to peg 2)
3 1 3  ...
1 2 1
2 2 3
1 1 3

```
> 7 votes

# Answer
## Perl - 54 chars

```
for(2..1<<<>){$_--;$x=$_&-$_;say(($_-$x)%3,($_+$x)%3)}

```

Run with `perl -M5.010` and enter the number of discs on stdin.

Output format:

One line per move, first digit is from peg, second digit is to peg (starting from 0)

Example:

```
02 -- move from peg 0 to peg 2
01
21
02
10
12
02

```
> 6 votes

# Answer
## GolfScript (31 25 24 chars)

```
])~{{~3%}%.{)3%}%2,@++}*

```

With thanks to Ilmari Karonen for pointing out that my original `tr`s/permutations could be shortened by 6 chars. By decomposing them as a product of two permutations I managed to save one more.

Note that factoring out the `3%` increases length by one character:

```
])~{{~}%.{)}%2,@++}*{3%}%

```

---

Some people have really complicated output formats. This outputs the peg moved from (numbered 0, 1, 2) and the peg moved to. The spec doesn't say to which peg to move, so it moves to peg 1.

E.g.

```
$ golfscript hanoi.gs <<<"3"
01021201202101

```
> 5 votes

# Answer
## Perl, 75 79 chars

Totally stealing Keith Randall's output format:

```
sub h{my($n,$p,$q)=@_;h($n,$p^$q^h($n,$p,$p^$q),$q*say"@_")if$n--}h pop,1,3

```

Invoke with `-M5.010` for the `say`.

(I think this can be improved if you can find a way to make use of the function's return value instead of just suppressing it.)
> 3 votes

# Answer
# SML, 63

```
fun f(0,_,_)=[]|f(n,s,t)=f(n-1,s,6-s-t)@[n,s,t]@f(n-1,6-s-t,t);

```

call function `f(n,s,t)` with:

* n number of disks
* s starting point
* t goal point
> 3 votes

# Answer
# Scala,~~92~~ ~~88~~ 87 chars

```
def?(n:Int,a:Int,b:Int){if(n>0){?(n-1,a,a^b)
print(n,a,b);?(n-1,a^b,b)}};?(readInt,1,3)

```

**Output format**

Say number of disk=3 then,

```
(1,1,3)(2,1,2)(1,3,2)(3,1,3)(1,2,1)(2,2,3)(1,1,3) (disk number,from peg, to peg)
                                                   \---------------------------/
                                                            Move 1              ... Move n

```
> 2 votes

# Answer
## Bash (64 chars)

```
t(){ tr 2$1 $12 <<<$s;};for((i=$1;i--;))do s=`t 1`01`t 0`;done;t

```

Posting this one despite being more than twice the length of the GolfScript one because I like the reuse of `t` to serve as `echo $s`.
> 2 votes

# Answer
## C, 98 92 87 chars

Implements the most trivial algorithm.
Output is in the form `ab ab ab` where each pair means "move the top disc from peg a to peg b".
**EDIT**: Moves are now encoded in hex - 0x12 means move from peg 1 to peg 2. Saved some characeters.
**EDIT**: Reads the number from stdin, rather than parameter. Shorter.
Example:
`% echo 3 | ./hanoi`
`13 12 32 13 21 23 13`

```
n;
h(d){n--&&h(d^d%16*16,printf("%02x ",d,h(d^d/16))),n++;}
main(){scanf("%d",&n);h(19);}

```
> 2 votes

# Answer
# Jelly, 5 bytes

```
2*Ṗọ2

```

Try it online!

`0` move the smallest disk one space to the right (wrapping back to the start if necessary)
`1` move the second-smallest disk to the only other legal column
`2` move the third-smallest disk to the only other legal column
etc.

## Algorithm

We can see the solution of the Towers of Hanoi problem recursively; to move a stack of size *n* from *A* to *B*, move a stack of size *n*-1 from *A* to *C*, then the disk of size *n* from *A* to *B*, then move a stack of size *n*-1 from *B* to *C*. This produces a pattern of the following form (in the output format used by this program):

```
0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2 …

```

We can observe that this sequence is A007814 on the OEIS. Another possible definition of the sequence is "the *k*th (1-based) element of the sequence is the number of zeroes at the end of the number *k* when it's written in binary". And that's what the program here is calculating.

## Explanation

First, we calculate the number of moves in the solution, 2*n*-1. It turns out to be shortest to actually calculate one extra move and discard it later, so this is `2*`, i.e. 2 to the power of something. (The only input we've taken so far is the command line argument, so that gets used by default.)

Next, we use Jelly's builtin for calculating the number of zeroes at the end of a number in base *b*; that's `*b*`. As we're calculating in binary, it's `ọ2`. All we need to do is to apply this builtin to the numbers from 1 to 2*n*-1 inclusive.

There are two simple ways to iterate over a range of numbers in Jelly,  and `R`, and my earlier attempts at this problem used one of these. However, in this case, it's possible to go slightly shorter: , when given a number as input, will let you do an iteration that stops one element short (in general,  is a builtin used to process all but one element of something). That's exactly what we want in this case (because `2*` generates one too many elments), so using it to link `2*` and `ọ2` into `2*Ṗọ2` gives us a 5-byte solution to the problem.
> 2 votes

# Answer
## Awk, 72 chars

```
function t(n,a,b){if(n){t(n-1,a,a^b);print n,a,b;t(n-1,a^b,b)}}t($0,1,3)

```

Output format is same as Keith Randall's one.

```
awk -f tower.awk <<< "3"
1 1 1
2 1 1
1 1 1
3 1 3
1 1 1
2 1 3
1 1 3

```
> 1 votes

# Answer
### Bash script, ~~100~~ 96 chars

```
t(){ [[ $1<1 ]] && return
t $(($1-1)) $2 $(($2^$3))
echo $@
t $(($1-1)) $(($2^$3)) $3
}
t $1 1 3

```

Output format is same as Keith Randall's one.

```
1 1 3
2 1 2
1 3 2
3 1 3
1 2 1
2 2 3
1 1 3

```

**Edit**: Saved 4 chars by peter's comment.
> 1 votes

# Answer
# J, 23 bytes

## binary numbers solution

```
2&(+/@:~:/\)@#:@i.@^~&2

```

This solution uses the binary counting method described in this video.

Which is to say, I generate the binary digits from `1` up to `2^n`, then take infixes of length 2 and compare each bit to the corresponding bit of the previous number, and check if they're unequal. The number of unequal bits is the output for that move.

Output, eg, for 3 disks, where smallest disk is labeled 1:

```
1 2 1 3 1 2 1

```

`1` means "move the smallest disk one peg right, looping back to the first peg if needed"

`n`, for all other `n`, means "move disk `n` to a legal peg" (there will always be exactly one)

Try it online!

## recursive solution

```
((],[,])$:@<:)`]@.(1=])

```

Same output as the above solution, but the logic here makes the recursive nature of the problem clearer.

Visualizing it as a tree also emphasizes this point:

```
              4
             / \
            /   \
           /     \
          /       \
         /         \
        /           \
       /             \
      3               3
     / \             / \
    /   \           /   \
   /     \         /     \
  2       2       2       2
 / \     / \     / \     / \
1   1   1   1   1   1   1   1

```

Try it online!
> 1 votes

# Answer
# , 73 bytes

Putting R on the map. Inspired by \[Keith Randall's answer\]\[1\] with simplified input, print only end and start peg to save 2 bytes. Also 0-indexed pegs.

```
f=function(n,s=0,e=2){if(n){f(n-1,s,3-s-e)
print(c(s,e))
f(n-1,3-s-e,e)}}

```

Try it online!
> 1 votes

# Answer
# APL (Dyalog Classic), 19 bytes

```
3|(-⍪0 1⍪2∘-)⍣⎕,⍨⍪⍬

```

Try it online!

output is a 2-column matrix of ints in {0,1,2} - from peg, to peg
> 0 votes

# Answer
# K (ngn/k), 23 bytes

```
{3!x{-x,(,0 2),1+x}/()}

```

Try it online!
> 0 votes

# Answer
# JavaScript (ES6), 45b

```
h=(n,f,a,t)=>n?h(--n,f,t,a)+f+t+h(n,a,f,t):''

```

e.g. calling `h(4, 'A', 'B', 'C')` (move 4 discs from peg A to peg C using auxiliary peg B)

returns `'ABACBCABCACBABACBCBACABCABACBC'` (move a disc from peg A to peg B, move a disc from peg A to peg C, move a disc from peg B to peg C, etc.)
> 0 votes

---
Tags: code-golf, stack
---


title: Shortest way to get an EOF Error

text:
# Question
Title: Shortest way to get an EOF Error
It's simple, simply output text to STDERR containing the string `EOF`.

## Input/Output

Your input will be none; however, you should output the message to STDERR.

## Rules

* Since this is , the shortest answer wins.
* No standard loopholes please.
* Any method approved by Standard I/O is allowed.
* Your code may not contain the "EOF" that you will output as-is in your error.
* Outputting "EOI" is technically allowed, because the input can also be considered as a separate file.

# Answer
> 23 votes
# APL (Dyalog Unicode) 17.0, 0 bytes

Dyalog 17.0 expects programs to terminate themselves cleanly and will throw an `EOF INTERRUPT` (and exit with a code 2) if they don't: Try it online!

In contrast, here is the minimal program which does terminate itself cleanly, causing no error (and code 0 upon exit): Try it online!

# Answer
> 9 votes
# Python 3, 1 byte

```
(

```

Try it online!

A plain opening bracket is interpreted as the start of a tuple. Just having one bracket is enough to raise an EOF error. Also works with `[` and `{`.

# Answer
> 7 votes
# Keg, 1 byte

```
?

```

Try it online!

When there's no input, an EOF is raised:

```
Traceback (most recent call last):
 File "/opt/keg/Keg.py", line 500, in <module>
   exec(header + code + footer)
 File "<string>", line 6, in <module>
 File "/opt/keg/KegLib.py", line 119, in Input
   item = input()
 EOFError: EOF when reading a line

```

Also works with `¿`

# Answer
> 4 votes
# JavaScript, 1 byte / 7 solutions

The following tokens trigger `SyntaxError: Unexpected end of input`, or a similar message depending on the JS engine.

```
!
(
+
-
[
{
~

```

Or to summarize:

* unary operators
* opening parenthesis / bracket / brace

### Exhaustive test on all ASCII characters

```
for(n = 0; n < 127; n++) {
  code = String.fromCharCode(n);
  res = false;

  try {
    eval(code);
  }
  catch(e) {
    res = e.toString() == 'SyntaxError: Unexpected end of input';
  }
  if(res) {
    console.log(code);
  }
}

```

Try it online!

# Answer
> 4 votes
## Turbo Assembler, 0 bytes

Borland Turbo Assembler will print an "Unexpected end of file" when assembling a zero-byte file.

# Answer
> 4 votes
For the python users; the ones posting one character code, technically that is a `SyntaxError` which happens to read as an `EOFERROR`. *(FYI, here's an example of all printable single characters that would cause this same error I'm getting a total of `34`:)*

```
from string import printable

chars = []
for c in printable:
    try: eval(c)
    except Exception as e:
        if 'EOF' in str(e):
            chars += [c]
print(chars)

```

This prints:

```
['!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', ']', '^', '`', '{', '|', '}', '~', ' ','\t', '\n', '\r', '\x0b', '\x0c']

```

I'm not sure if `raise EOFError` would be considered an answer as unfortunately that's the shortest code I can think of to raise a legitimate `EOFError` in Python 3:

---

# Python 3, 14 bytes

```
raise EOFError

```

Try it online!

# OR

**Without implicitly raising the error in Python 2 you could use this at the expense of an extra byte:**

---

# Python 2, 15 bytes

```
input('\u0004')

```

Try it online!

# Answer
> 3 votes
# PHP, 1 byte

```
1

```

Try it online!

Run like this: `php -r 1`

Error: `PHP Parse error: syntax error, unexpected end of file in ...`

Any other characters apart from `;`, `#`, space and new line should cause a similar error. So PHP probably has `ASCII characters count - 4` single byte solutions.

# Answer
> 3 votes
## Haskell using hugs, 1 byte

```
{

```

The error message contains `unexpected end of input`.

Try it online!

# Answer
> 3 votes
# Japt v2.0a0, 1 byte

Each throws: `SyntaxError: Unexpected end of input`

```
´
¥
¶
ª
©
«
§
¨
±
µ
÷
Á
Â
Ò
Ó

```

Test it (Errors are displayed below the output field)

There are also a number of other possibilities, not specific to Japt, that are covered in Arnauld's JS solution, such as:

```
!
&
|
~
^

```

# Answer
> 3 votes
# R, 1 byte, 10 solutions

Any of these characters alone will trigger `Error: unexpected end of input`.

```
"
'
`
(
{
+
-
!
?
~

```

# Answer
> 2 votes
# Python 3, 1 byte

Sorry for the edit, misunderstood the question at first :P. We can do \[ or ( or { to get unexpected EOF error. In first case, it expects a list, in second a tuple and so on.

```
[

```

Try it online!

# Answer
> 2 votes
**Perl, 1 byte**

`(`

Try it with

```
 perl -e "("
 syntax error at -e line 1, at EOF
 Execution of -e aborted due to compilation errors.

```

# Answer
> 2 votes
# Java, 1 byte

```
e

```

Try it online!

---

Old method that's more fun :\]

```
void a()throws Exception{new java.io.DataInputStream(System.in).readInt();}

```

Try it online!

# Answer
> 2 votes
# T-SQL, 21 bytes

```
RAISERROR('EOF',11,1)

```

# Answer
> 1 votes
# Bash, 1

```
"

```

### Output

```
.code.tio: line 1: unexpected EOF while looking for matching `"'
.code.tio: line 2: syntax error: unexpected end of file

```

Try it online!

# Answer
> 1 votes
# Ruby, 1 byte

```
!

```

Try it online!

Any of `["!", "(", "*", "+", "-", ":", "[", "{", "~"]` will work depending on the environment.

# Answer
> 1 votes
# Ruby, 1 byte

```
/

```

Outputs `unterminated regexp meets end of file`

Try it online!

# Answer
> 1 votes
# Perl 5, 1 byte

```
"

```

Try it online!

Not very inspired, but it *is* the shortest possible in the language.

Outputs `Can't find string terminator '"' anywhere before EOF at .code.tio line 1.`

# Answer
> 1 votes
# Go, 0 bytes

All Go files must begin with `package [identifier]`. The error message is:

```
can't load package: package main:
src/test.go:1:1: expected 'package', found 'EOF'

```

---
Tags: code-golf, error-message
---


title: What's the current zodiac?

text:
# Question
Title: What's the current zodiac?
Display the emoji of the eastern zodiac of given time, according to given country.

The eastern zodiac is a classification scheme that assigns an animal and its reputed attributes to each year in a repeating 12-year cycle. It is also assigned to hours.

**Rules:**

1. The country must be given as ISO 3166-1 alpha-3 code. The list is here.
2. The input format must be like this: `<ISO code> HH:MM`. The input must be a single string. Any input that doesn't fit this format falls in *don't care* situation.
3. If the given time lies in boundary of the chart given below, you can output either zodiac.
4. As this is a code golf, the shortest code in bytes wins.

**The zodiacs:**

The zodiacs without specified country are defaults.

* The first zodiac (23:00 – 01:00):

+ Rat (U+1F400)
    + Mouse (U+1F401) in Persia (IRN)
* The second zodiac (01:00 – 03:00):

+ Ox (U+1F402)
    + Water Buffalo (U+1F403) in Vietnam (VNM)
    + Cow (U+1F404) in Persia
* The third zodiac (03:00 – 05:00):

+ Tiger (U+1F405)
    + Leopard (U+1F406) in Persia
* The fourth zodiac (05:00 – 07:00):

+ Rabbit (U+1F407)
    + Cat (U+1F408) in Vietnam
* The fifth zodiac (07:00 – 09:00):

+ Dragon (U+1F409)
    + Crocodile (U+1F40A) / Whale (U+1F40B) in Persia (you can output either)
    + Snail (U+1F40C) in Kazakhstan (KAZ)
* The sixth zodiac (09:00 – 11:00):

+ Snake (U+1F40D)
* The seventh zodiac (11:00 – 13:00):

+ Horse (U+1F40E)
* The eighth zodiac (13:00 – 15:00):

+ Ram (U+1F40F)
    + Goat (U+1F410) in Vietnam
    + Sheep (U+1F411) in Persia
* The ninth zodiac (15:00 – 17:00):

+ Monkey (U+1F412)
* The tenth zodiac (17:00 – 19:00):

+ Rooster (U+1F413)
    + Chicken (U+1F414) in Persia
* The eleventh zodiac (19:00 – 21:00):

+ Dog (U+1F415)
* The twelfth zodiac (21:00 – 23:00):

+ Pig (U+1F416)
    + Boar (U+1F417) in Japan (JPN)
    + Elephant (U+1F418) in Thailand (THA)

The code points are from here.

**Example:**

Given the following input:

```
KOR 19:42

```

The output must be:

```

```

# Answer
> 8 votes
# 05AB1E, ~~66~~ ~~64~~ 63 bytes

```
þт÷;ò12%Ð•kÄ$ó·;@è₂Èαвλã…7q¼#∍o•5в6ä.•xиʒaàÒ¾Äλ•u3ôIákèsèžy₄*Oç

```

Try it online!

# Answer
> 10 votes
# JavaScript (ES6),  ~~168 165 160 157~~  155 bytes

*Saved 4 bytes thanks to @Neil*

Returns the crocodile for the 5th zodiac in Persia.

```
([a,b,c,,d,e])=>String.fromCodePoint(127998-~'00111321211'[k=-~(d+e)%24>>1]+k*2-~(1e12+{IRN:121010020100,VNM:1010001e4,KAZ:3e7,JPN:1,THA:2}[a+b+c]+a)[k+1])

```

Try it online!

### How?

We define \\$k\\$ as the 0-based index of the zodiac, which can be deduced from the hour \\$h\\$ with:

$$k=\lfloor ((h+1)\bmod 24)/2\rfloor$$

We define \\$x\_k\\$ such that the base offset \\$b\_k\\$ of the code point for a given zodiac is:

$$b\_k = 2k+x\_k$$

The final code point is \\$128000+b\_k+c\_k\\$, where \\$c\_k\\$ is the country offset.

This is summarized in the following table:

```
   k =  |   0 |   1 |   2 |   3 |   4 |   5 |   6 |   7 |   8 |   9 |  10 |  11
--------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
  b(k)  |  +0 |  +2 |  +5 |  +7 |  +9 | +13 | +14 | +15 | +18 | +19 | +21 | +22
  = 2k  |   0 |   2 |   4 |   6 |   8 |  10 |  12 |  14 |  16 |  18 |  20 |  22
  +x(k) |   0 |   0 |   1 |   1 |   1 |   3 |   2 |   1 |   2 |   1 |   1 |   0
--------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----
   IRN  |  +1 |  +2 |  +1 |     |  +1 |     |     |  +2 |     |  +1 |     |
   VNM  |     |  +1 |     |  +1 |     |     |     |  +1 |     |     |     |
   KAZ  |     |     |     |     |  +3 |     |     |     |     |     |     |
   JPN  |     |     |     |     |     |     |     |     |     |     |     |  +1
   THA  |     |     |     |     |     |     |     |     |     |     |     |  +2

```

### Commented

```
( [ a, b, c,               // a,b,c = country code
    ,                      // the space is ignored
    d, e ] ) =>            // d,e = hour (minutes are ignored)
  String.fromCodePoint(    // return the character whose code point is:
    127998                 //   127998
    -~'00111321211'[       //   + 1 + x(k)
      k = -~(d + e)        //   where k is defined as:
          % 24 >> 1        //     floor(((hour + 1) mod 24) / 2)
    ] +                    //
    k * 2                  //   + 2k
    -~(                    //   + 1 + the country offset
      1e12 +               //     each pattern being encoded as 10**12
      {                    //     + a specific value, leading to:
        IRN: 121010020100, //       IRN -> 1121010020100
        VNM: 1010001e4,    //       VNM -> 1010100010000
        KAZ: 3e7,          //       KAZ -> 1000030000000
        JPN: 1,            //       JPN -> 1000000000001
        THA: 2             //       THA -> 1000000000002
      }[a + b + c]         //     according to the country code
      + a                  //     coerced to a string
    )[k + 1]               //   extract the correct offset for this zodiac
  )                        //   (gives something NaN-ish for the other countries)

```

# Answer
> 4 votes
# PHP, 185 chars, 263 bytes

Thanks to Dannyu NDos for bug fix.

```
fn($i)=>strlen($b=[[,],[,,],[,],[,,],[,,,],,,[,,],,[,],,[,4=>,5=>]][(($t=$i[4].$i[5])%2?$t+1:$t)%24/2])?$b:$b[strpos(____IRN_VNM_KAZ_JPN_THA,substr($i,0,3))/4]

```

Try it online!

Just a simple array mapping, there should be better ways to golf this. Hour part of input time is converted to an even number (0-22) and then it is divided by 2 to get array index 0 to 11 in the mapping. Time periods with special cases are a sub-array with index 0 mapped to default sign and 1-5 mapped to the special sign for IRN, VNM, KAZ, JPN and THA in same order.

# Answer
> 4 votes
# Charcoal, 73 bytes

```
℅⁺×¹²⁸φΣＥ⮌…⪪”＆↖∨∧h↘Ｘ⁷↘H⪫³Ｊºρ⁷s,⟲⌈3A‖Cc>χ§₂25:×” ⊕﹪÷⊕Ｉ…η²¦²¦¹²⊕⎇κ÷Ｌι³⌕⪪ι³θ

```

Try it online! Link is to verbose version of code. Explantion:

```
℅⁺×¹²⁸φ

```

`0x1F400` = 128,000 (`φ` is predefined to 1,000). This is added to the sum of the rest of the expression and converted to a character for implicit print.

```
⊕﹪÷⊕Ｉ…η²¦²¦¹²

```

The hour is extracted and converted to a zodiac index.

```
…⪪”＆↖∨∧h↘Ｘ⁷↘H⪫³Ｊºρ⁷s,⟲⌈3A‖Cc>χ§₂25:×” ...

```

The compressed string `IRN VNMIRN IRN VNM IRNIRNKAZ VNMIRN IRN JPNTHA` is split on spaces and truncated to the length given by that index.

```
ΣＥ⮌...

```

The array is then reversed, mapped over, and summed.

```
⊕⎇κ÷Ｌι³⌕⪪ι³θ

```

For the first element, the string is split into groups of three characters and the country index is taken, otherwise the number of countries is counted. For the first element, the index needs to be converted from 0-indexing to 1-indexing while for the other elements the result needs to be incremented for the default country, so this is done outside of the ternary.

# Answer
> 3 votes
# Python 3, 168 bytes

```
lambda s,a='BA EDC GF HIH KJMJ N O RQP S UT V WWWXYW'.split():chr(ord(a[(int(s[4:6])+1)//2][min('IRNVNMKAZJPNTHA'.find(s[:3])//3,len(a[(int(s[4:6])+1)//2])-1)])+127935)

```

Try it online!

---
Tags: code-golf, string, date, unicode
---