title: Program compressor

text:
# Question
Title: Program compressor
Choose a language and write a program in the language that:

* Take a valid program of the language as input,
* Output a string(bytearray, etc.). It needn't be a valid program.
* Only finite valid inputs result in longer/same-length(in bytes) output.
* Different valid input, even if behave same, lead to different output.

Let length of your code as \\$L\\$ and number of inputs with longer/equal-length output as \\$n\\$. To win, you should be lowest on at least one of:

* \\$L\\$,
* \\$N\\$,
* \\$L+N\\$,
* \\$L+\log\_2(N+1)\\$.

# Notes

# Answer
> 3 votes
# Python 3.8 (pre-release), \\$L=79\\$, \\$N\approx255^{1500}\\$

<sup>-3 bytes thanks to @Jonathan Allan</sup>

```
f=lambda b,s=0,l=0:b and f(b[1:],255*s+b[0],l+1)or s.to_bytes(l-(l>1500),"big")

```

Try it online!

Python source code can't contain null bytes. This converts the input (bytestring) to base 255 and then back to bytes. After 1500 removes a redundant byte.

---
Tags: code-golf, code-challenge, compression
---


# Question
Title: Represent any integer with an expression that uses no digit besides '4'
# Fourward (Introduction)

I have an unhealthy obsession with the number 4. I love it so much, in fact, that seeing any other digit is frustrating to me. I therefour wish to create a 'Fourier Transformation': a way to represent any integer value with an expression that uses only the digit 4.

# Fourmat (Challenge)

I wish to automate this process so I can use it everywhere. Your code must take any integer and output an expression that evaluates to that integer but which uses no digit other than '4'.

Four example, you might render the natural numbers as follows:

```
(4-4)
(4/4)
((4/4) + (4/4))
((4) - (4/4))
(4)
((4) + (4/4))
etc.

```

Any mathematical operation is allowed: you may use addition, multiplication, exponents, roots, logs, or even logical expressions such as AND or bitmasking--so long as no digit other than 4 appears in the output!

The parentheses aren't necessary; you may fourmat the output in whatever way you like, so long as it's readable. Also, because I'm not all that intelligent, the end result must be in base ten (or as I like to call it, base `4+4+(4/4)+(4/4)`.

# Perfourmance (Criteria)

It is vitally important that the expressions each be as efficient as possible; I love the number 4, but I don't want to get sick of it. Submissions will thus be judged on the following, in order:

* Efficiency of expressions (i.e. that the expression produced is as short as possible while still following the rules)
* Efficiency of code (i.e. that your code is as short as possible)
* Beauty of code (this is a tiebreaker; I won't be seeing the code itself so I don't mind non-four digits in there, but between two otherwise equal answers, I will prefer the code that uses the fewest non-four digits)

# Answer
> 2 votes
# JavaScript (Node.js), 26 bytes

```
f=n=>n?f(--n)+'+4/4':'4-4'

```

Try it online!

Quite simple and self explanatory. uses \\$2n+2\\$ 4's for any number \\$n\\$

---
Tags: math, number, code-challenge, integer, expression-building
---


title: Shrink ASCII art

text:
# Question
Title: Shrink ASCII art
The inverse of this question.

Your challenge is to, given a piece of ASCII art generated by the above question and its enlargement factor, shrink it down to its original size.

## The enlargement process

Or look at this

ASCII art within a limited character set can be enlarged to a certain (odd) size by replacing certain characters with larger versions of themselves, like so:

```
-\
 |
_/
, 3 =>

   \
--- \
     \
    |
    |
    |
     /
    /
___/

```

Because each character is enlarged to a 3x3 square.

Only those six characters (`\/|-_` ) can be enlarged, and only those will be in your input. For a more detailed explanation, see the linked challenge.

I/O may be as a char matrix, ascii art, list of rows, etc.

## Testcases

```

\
 \
  \
, 3 =>
\

---------

, 3 =>
---

 |
 |
 |
 |
 |
 |
 |
 |
 | , 3 =>
|
|
|

 | \       / |
 |  \     /  |
 |   \___/   |
 |           |
 |           |
 |           |
   \       /
    \     /
     \___/
, 3 =>
|\_/|
|   |
 \_/

_______________
\             /
 \           /
  \         /
  /         \
 /           \
/             \
\             /
 \           /
  \_________/  , 3 =>
_____
\   /
/   \
\___/

        /\
       /  \
      /    \
     /      \
    /        \
   /          \
  /            \
 /              \
/  ____________  \
       |  |
       |  |
       |  |
       |  |
       |  |
       |  |
     /      \
    /        \
___/  ______  \___, 3 =>
  /\
 /  \
/____\
  ||
  ||
_/__\_

\        /
 \      /
  \    /
   \  /
    \/
\        /
 \      /
  \    /
   \  /
    \/    , 5 =>
\/
\/

      /             /
     /             /
    /             /
   /   -------   /
  /             /
 /             /
/             /
\             \
 \             \
  \             \
   \   -------   \
    \             \
     \             \
      \             \, 7 =>
/-/
\-\

```

# Answer
> 4 votes
# Jelly, 7 bytes

```
»/⁹ÐƤ⁺€

```

A monadic Link accepting a list of lines that yields a list of lines.

**Try it online!**

### How?

```
»/⁹ÐƤ⁺€ - Link: list of lists of characters, Lines; pixel size, N
   ÐƤ   - for non-overlapping infixes
  ⁹     - ...of length: chain's right argument, N
 /      - ...yield: reduce by:
        -             maximum (vectorises)
                      (Note: space is less than any other character used)
      € - for each:
     ⁺  -   repeat the last link - i.e. do Ṁ⁹ÐƤ

```

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

```
x=>n=>x.replace(/.+\n.+\n.+/g,y=>[...(z=y.split`
`)[~-n/2]].map((w,i)=>i%3-1?"":w<"!"?z[n-1][i]:w).join``)

```

Now actually works!

# Answer
> 2 votes
# , 20 bytes

```
{.@-.&' '@,;.3~2 2&$

```

Try it online!

With `(y x,:h w) u;.3 a` we can split `a` into tiles of size `h w` while sliding the window by `y x`. Because we don't want overlapping tiles, we can simply build a 2x2 matrix of the input, e.g. `3 3,:3 3`. On these tiles `u` gets applied, which flattens `,` the tile into a list, removes any whitespace `-.&' '` and then reduces the tile to the first remaining element `{.`.

# Answer
> 1 votes
# Charcoal, 25 bytes

```
ＮθＷＳ⊞υ⭆⪪ιθ⌈κＥ⪪υθ⭆⌈ι⌈Ｅι§νμ

```

Try it online! Link is to verbose version of code. Takes the enlargement factor followed by a list of newline-terminated strings. Explanation:

```
Ｎθ

```

Input the enlargement factor.

```
ＷＳ⊞υ⭆⪪ιθ⌈κ

```

Input the strings, but split them into substrings of length equal to the enlargement factor and take the maximum character of each substring.

```
Ｅ⪪υθ⭆⌈ι⌈Ｅι§νμ

```

Split the list of strings into sublists of length equal to the enlargement factor, then transpose the sublists and take the maximum character of each, joined back into a string, and print each sublist's string on its own line.

# Answer
> 1 votes
# JavaScript, 84 bytes

```
a=>n=>a.map((r,i)=>r.map((c,j)=>(d=b[i/n|0]||=[])[x=j/n|0]=d[x]?.trim()||c),b=[])&&b

```

```
f=
a=>n=>a.map((r,i)=>r.map((c,j)=>(d=b[i/n|0]||=[])[x=j/n|0]=d[x]?.trim()||c),b=[])&&b

str2mat = str => str.split('\n').map(r => [...r]);
mat2str = mat => mat.map(r => r.join('')).join('\n');
test = (s, n) => console.log(mat2str(f(str2mat(s.slice(1, -1)))(n)));

test(String.raw`
\
 \
  \
`, 3);

test(String.raw`
---------
`, 3);

test(String.raw`
 |
 |
 |
 |
 |
 |
 |
 |
 |
`, 3);

test(String.raw`
 | \       / |
 |  \     /  |
 |   \___/   |
 |           |
 |           |
 |           |
   \       /
    \     /
     \___/
`, 3);

test(String.raw`
_______________
\             /
 \           /
  \         /
  /         \
 /           \
/             \
\             /
 \           /
  \_________/
`, 3);

test(String.raw`
        /\
       /  \
      /    \
     /      \
    /        \
   /          \
  /            \
 /              \
/  ____________  \
       |  |
       |  |
       |  |
       |  |
       |  |
       |  |
     /      \
    /        \
___/  ______  \___
`, 3);

test(String.raw`
\        /
 \      /
  \    /
   \  /
    \/
\        /
 \      /
  \    /
   \  /
    \/
`, 5);

test(String.raw`
      /             /
     /             /
    /             /
   /   -------   /
  /             /
 /             /
/             /
\             \
 \             \
  \             \
   \   -------   \
    \             \
     \             \
      \             \
`, 7);
```

# Answer
> 1 votes
# Haskell, 56 bytes

```
f n|let g[]=[];g x=maximum(take n x):g(drop n x)=g.map g

```

Try it online!

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


title: Is this even a word?

text:
# Question
Title: Is this even a word?
Your should write a program or function that takes a 4-character string as input and outputs a value indicating if the string is an English word or not. You are allowed to make mistakes in 15% of the provided testcases.

## Input details:

Input is a 4-character string containing only the lowercase English letters (a-z).

## Output details:

If the input **is** an English word you should output a boolean `true` or an integer `1`.

If the input **isn't** an English word you should output a boolean `false` or an integer `0`.

## Word lists

list of 4-letter English words (2236 words)

list of 4-letter non-word strings (2236 strings)

The non-word list contains uniformly randomly generated letter sequences with the real words removed from them.

## Testing

Your program or function should make no more than 15% mistakes on the given word lists together. That means you can give wrong output for 670 of the 4472 provided inputs.

You should post the testing program or function too so others could check your answer. The length of your testing program doesn't count into your submissions score.

Standard loopholes are disallowed.

Your program shouldn't use any external sources e.g. accessing web or reading from file.

This is code-golf so the shortest program or function wins.

# Answer
# Ruby, 29 bytes

```
->s{!s[/[^aeiou]{3}|[jqxz]/]}

```

Hopefully I've got this right - it's my first time programming in Ruby. I actually did all my testing in Python, but `import re` was far too long for me.

This is an anonymous function which takes in a string and outputs `true/false` accordingly. It uses a regex which looks for one of the following two things:

* Three consonants in a row
* Contains one of `jqxz`

If either of these are present, we classify the input as not a word.

The function matches 2030 words (incorrectly failing on 206) and fails on 1782 non-words (incorrectly matching 454), for a total of 660 misclassifications. Tested on ideone.

Thanks to @MartinBüttner for the Ruby help. Martin also points out that a full program takes the same number of bytes:

```
p !gets[/[^aeiou]{3}|[jqxz]/]

```

Also thanks to user20150203 for simplifying the regex.

---

# Ruby, ~~1586~~ ~~1488~~ ~~1349~~ ~~1288~~ 1203 bytes

For a bonus, here's a function with a much longer regex:

```
->s{!s[/[^aeiouyhs]{3}|[^aeiouy]{4}|q[^u]|^x|^[bdf][^aeioulry]|^[cgkprtwy][mfdsbktjgxpc]|^a[aoz]|^e[hf]|^i[ea]|^o[ecy]|^u[^ltnspgr]|[bdgktyz][cgmpw]$|[fhpvx][^aieoflnrsty]$|eh$|i[iyh]|[wkybp]z|[dghz]t|[fjzsv]y.|h[ns].|ae.|y.?[yifj]|[ejo]..[iuw]|[inv]..[gpuvz]|[eu].[jqwx]|[vyz][^t][fhmpqy]|i[^ae][fjqrv]|[ospen].?j|[ceg][iuy][ghkoux]|[bcpx]f|[hnuy]w|[ghnw]b|[txz]n|[jk]r|.[fjuyz]u|[hnt]ia|lsy|.p.o|.l.l|.tas|zal|f.p|eeb|wei|.sc.|.pl|yat|hov|hab|aug|v.re|aba|ohu|ned|s.dd|uc$|nux|oo$|dgo|lix|wua|v.o|vo$|ryo|wue|dk|oic|yol|.tr|yrb|oba|ruh|c.ls|idd|chn|doy|ekh|tk|lke|asl|cir|eez|asc|uil|iou|m..p|awt|irp|zaa|td|swk|ors|phe|aro|yps|q.e|ati|ibt|e.mo|we.y|p.de|ley|eq|tui|e..g|sps|akh|dny|swr|iul|.t.t|.tao|rcy|.p.y|idi|j.o|.kl|oms|ogi|jat|.lis|mye|uza|rsi|.ala|ibo|ipi|yaa|eun|ruy|wog|mm$|oex|koi|uyn|.hid|osc|ofe|w.op|auc|uzy|yme|aab|slm|oza|.fi|bys|z.e|nse|faf|l.h|f.va|nay|hag|opo|lal|seck|z.b|kt|agl|epo|roch|ix.|pys|oez|h.zi|nan|jor|c.ey|dui|ry.d|.sn|sek|w.no|iaz|ieb|irb|tz.|ilz|oib|cd|bye|ded|f.b|if$|mig|kue|ki.w|yew|dab|kh.|grs|no.t|cs.|.n.m|iea|y.na|vev|eag|el[uz]|eo[dkr]|e[hlsu]e|e[dho]l|eov|e[adp]y|r[grt]u|yn[klo]|.[^ilv].v|s[bdgqrz]|m[dfghrz]|[vpcwx]{2}|^[hjlmnvz][^aeiouy]|^[drw]l|l[hnr]/]}

```

I wanted to show that regex can still beat compression, so this one classifies every given case correctly. The regex itself is a bit like exponential decay — the first bits match a lot of non-words, then every bit after matches fewer and fewer until I gave up and just concatenated the rest (about 200 or so) at the end. Some of the ones that were left looked surprisingly like real words (such as `chia` which *is* a word).

I threw the regex at my regex golf cleaner which I wrote for another challenge — it golfed about 300 bytes before I had to try shuffling things around manually. There's still a fair bit to be golfed though.
> 62 votes

# Answer
# Groovy, ~~77~~ 74

```
x={it==~/^(?!.+[jq]|[^aeiou][^aeiouhlr]|.[^aeiouy]{3}|.[x-z])|^s[cknptw]/}

```

I wrote the test program in Java, which you can find in this Gist on Github. Here is the output from my test program:

```
Good: 2135 1708
Bad: 101 528

```

(Failed 629 test cases)

P.S. I think this is going to end up a regex golf problem extremely soon...

If Sp3000's answer (the function) is to be converted to Groovy, it will end up with the same character count. As named function:

```
x={it!=~/[^aeiou]{3}|[jqxz]/}

```

or unnamed function:

```
{i->i!=~/[^aeiou]{3}|[jqxz]/}

```
> 13 votes

# Answer
# Javascript, 1626 bytes:

I wanted to go for a solution which for each character has a clue of which one might come after. Not that short, but no regex and a fairly good result (words: 101 mistakes, non-words, 228 mistakes)

```
v=function(w){var g={a:{b:3,c:4,d:4,m:6,f:1,r:14,g:4,i:6,x:2,k:2,l:10,n:12,s:6,p:4,t:7,u:2,v:3,w:3,y:3,h:1,z:1},b:{b:3,a:19,e:19,y:3,l:6,o:17,u:12,i:9,s:9,r:6},e:{d:7,l:8,t:4,s:10,n:11,e:10,r:10,c:2,x:2,w:4,a:13,f:1,p:2,g:2,v:1,b:1,m:3,u:1,i:1,k:1,y:2},l:{e:16,y:5,a:16,b:1,f:2,l:12,m:2,o:14,p:1,s:2,u:8,d:4,i:10,k:3,t:5},o:{s:7,g:3,e:3,k:3,n:10,m:4,p:5,w:6,b:3,c:2,t:6,a:5,d:5,h:1,i:2,l:8,o:9,r:8,u:4,y:2,v:2,z:1,f:2,x:1},u:{t:8,e:5,m:7,s:11,a:2,n:13,r:15,d:6,c:4,f:1,g:5,l:9,y:1,z:1,b:5,j:1,x:1,p:2,k:1,i:2},c:{e:9,h:12,i:2,r:6,t:3,o:20,k:15,a:16,l:6,u:8,y:1},h:{e:21,r:2,a:22,i:15,o:20,u:15,n:3,l:1,y:1},i:{d:8,m:5,n:18,r:7,a:2,s:8,v:2,l:13,t:10,b:1,e:6,k:2,p:5,g:3,c:6,o:2,f:2,z:1},m:{e:19,s:8,a:21,i:12,m:1,o:15,y:2,b:4,p:8,n:1,u:8},n:{e:18,u:3,a:9,d:10,n:4,o:7,s:11,t:11,g:10,k:6,i:5,y:2,c:1},r:{e:18,s:4,y:4,a:16,c:1,g:1,i:12,m:3,p:2,t:4,b:1,d:4,k:4,n:5,r:2,o:11,l:2,u:6,f:1},t:{a:14,s:17,e:18,i:9,o:15,h:10,t:3,y:2,c:1,z:1,u:5,r:5,w:2},d:{a:14,d:4,s:10,e:22,y:8,i:12,o:14,r:4,u:10,l:1},f:{a:16,f:6,e:12,y:1,i:14,l:13,o:16,r:7,u:7,t:7,n:1,s:1},g:{a:16,e:12,o:17,u:7,s:18,g:1,y:2,i:8,l:4,n:2,h:3,r:9,w:1},j:{a:25,i:7,e:14,o:25,u:29},k:{i:23,s:6,e:41,u:6,a:10,l:2,n:8,o:2,h:1,y:1},p:{s:12,e:20,a:19,y:2,i:13,t:2,u:10,l:5,o:13,r:4},s:{o:8,i:8,e:13,k:6,h:10,s:8,t:14,y:1,p:5,c:2,l:6,a:10,m:1,n:2,u:4,w:2},v:{a:18,e:47,i:22,o:8,y:6},y:{l:4,e:18,s:20,d:3,n:8,r:8,t:4,a:14,k:1,m:1,o:8,x:3,p:3,u:4,v:1},q:{u:100},w:{a:24,e:17,l:4,r:3,s:10,n:6,y:2,k:1,d:1,t:1,i:17,u:1,o:10,h:4},x:{e:35,i:18,l:6,o:6,a:6,t:12,y:18},z:{z:10,y:10,a:3,e:43,r:3,o:17,i:10,u:3}},p=1,x,y,i=0;for(;i<3;){x=w[i],y=w[++i];p*=g[x]&&g[x][y]||0}return p>60}

```

Here's a working implementation http://fiddle.jshell.net/jc73sjyn/

In short: the Object g holds the characters from a to z (as keys), and for each of them, there is a set of characters (also as keys) that each represent a character that may come after, along with its probability percentage. Where no object exists, there is no probability.

The 3 scores (4 letters -\> 3 evaluations) are multiplied, and a word with a score of 60 and above is considered a real word.

Example: for the word 'cope' there are three lookups:

g\[c\]\[o\] = 20

g\[o\]\[p\] = 5

g\[p\]\[e\] = 20

score = 20 * 5 * 20 = 2000, which is more than 60, so that one is valid.

(I'm quite new with javascript, so there might be ways to make it shorter that I don't know of.)

**LATE EDIT:**

Completely irrelevant by now, but I evaluated my way to a more correct g:

```
g={a:{b:7,c:4,d:4,m:6,f:2,r:14,g:4,i:6,x:2,k:2,l:10,n:12,s:6,p:4,t:7,u:2,v:3,w:12,y:3,h:1,z:1},b:{b:10,a:19,e:19,y:3,l:6,o:17,u:10,i:9,s:9,r:3},e:{d:7,l:8,t:4,s:10,n:11,e:10,r:10,c:2,x:2,w:4,a:13,f:1,p:2,g:2,v:20,b:3,m:3,u:1,i:1,k:1,y:2},l:{e:16,y:5,a:16,b:1,f:2,l:12,m:2,o:14,p:1,s:6,u:61,d:1,i:10,k:3,t:5},o:{s:7,g:3,e:3,k:3,n:20,m:4,p:5,w:6,b:3,c:2,t:6,a:5,d:5,h:10,i:2,l:8,o:3,r:8,u:4,y:2,v:2,z:1,f:20,x:1},u:{t:8,e:5,m:7,s:11,a:2,n:13,r:15,d:6,c:1,f:10,g:5,l:9,y:1,z:1,b:5,j:1,x:1,p:2,k:1,i:2},c:{e:9,h:20,i:2,r:6,t:20,o:15,k:15,a:15,l:6,u:8,y:1},h:{e:21,r:2,a:7,i:15,o:20,u:15,n:10,l:0,y:1},i:{d:8,m:5,n:18,r:7,a:5,s:8,v:2,l:13,t:20,b:1,e:21,k:2,p:5,g:20,c:4,o:2,f:2,z:1},m:{e:10,s:8,a:21,i:12,m:1,o:15,y:2,b:4,p:2,n:1,u:8},n:{e:18,u:3,a:9,d:3,n:4,o:20,s:2,t:11,g:10,k:6,i:5,y:2,c:1},r:{e:15,s:4,y:4,a:16,c:1,g:1,i:12,m:3,p:2,t:4,b:1,d:4,k:4,n:5,r:2,o:11,l:2,u:20,f:1},t:{a:14,s:15,e:18,i:2,o:15,h:10,t:3,y:2,c:1,z:1,u:5,r:5,w:2},d:{a:14,d:4,s:10,e:61,y:8,i:12,o:7,r:3,u:10,l:0},f:{a:5,f:6,e:12,y:1,i:3,l:13,o:16,r:7,u:20,t:4,n:1,s:1},g:{a:16,e:12,o:17,u:7,s:18,g:0,y:2,i:8,l:3,n:2,h:3,r:9,w:1},j:{a:8,i:7,e:14,o:5,u:29},k:{i:3,s:20,e:41,u:6,a:10,l:20,n:8,o:2,h:1,y:1},p:{s:12,e:20,a:5,y:2,i:13,t:4,u:10,l:3,o:13,r:4},s:{o:8,i:8,e:13,k:6,h:10,s:8,t:14,y:1,p:5,c:2,l:2,a:10,m:2,n:6,u:8,w:2},v:{a:10,e:20,i:22,o:6,y:6},y:{l:6,e:15,s:20,d:3,n:8,r:8,t:4,a:4,k:1,m:1,o:3,x:3,p:3,u:1,v:1},q:{u:100},w:{a:24,e:17,l:4,r:2,s:3,n:6,y:20,k:1,d:1,t:1,i:17,u:6,o:10,h:20},x:{e:35,i:6,l:3,o:6,a:6,t:3,y:7},z:{z:10,y:10,a:3,e:43,r:1,o:8,i:7,u:1}}

```

New results:

words: 53 mistakes, non-words: 159 mistakes

http://fiddle.jshell.net/jc73sjyn/2/
> 9 votes

# Answer
# Python 2, 5254 bytes

This solution separates the good words into two halves. The lookup first checks the first 2 characters to find the right string, then looks for the second 2 characters in that string. Not very compact, but quick to write. This method matches every word without mistakes.

```
d='''gwenyn
guamlflllpmsnsrushsttsys
grabadamayegeweyidiminipisitowub
gyro
gearldlsmsnentrmts
gagsilinitlellltmengpepsrbryshspteulvewkze
goadalatbidsesffghldlfnengodofreryshtoutwn
gnataw
gladeeenowueut
giftldllltnannnonsrdrlrtstve
wrapenit
leadafakanaparekeresftgsnandnsntonsssttsvivywd
labsceckcydsdygsidinirkembmempnandnengospsrdrkrsshssstteuevawnwsyszy
loadafanbecickebftgogsiniskilambmenengokomonopotrdresesssttsudutvewews
tubebsckftgsnerfrn
trapayeeekimioipodotoyueuk
liarceckdsedeneseufeftkelalymambmempndnenkntonpssasespssstve
toadbyddesgoilldllmbneninsokolpsrernrysstourwnys
luckcyiskellmpndngrarerkshsttetz
thaianataweaemeneyinisorudugus
tickdedyedereslellltmemsnansntnypsretots
teamarasemenllndnsntrmssstxt
lylennnxonrare
dockdderesgegslellmenensomorperasetetsugvewnze
typepo
yokerkstur
dialcedoedemesetgskellmemsnengntonpsrertscshskve
yagilenkrdrnwn
deadafalanarbtckedemeperfyllmonsntnyskuswy
yearaslllp
dadadedshllelilymemnmpmsnanererkrnrtshtatevevywnysze
dyadedereskene
dualbsckctelesetkelllymbmpnengnknnpeskstty
drabagamawewipopugum
yves
yubakiri
quadayipitiz
iranaqesisksmaon
emilitma
elbakslamsse
endsidosvy
eire
zincon
ekedes
eels
eddyengeitna
egangsos
eachrlrnrprssestsyts
echo
ebbsen
eyederes
examecit
ezra
etch
ewenes
eveneril
wokelfmbngntodofolosrdrerkrmrnve
epic
espy
erasgoicieikisneosrs
rubebsbydedygsinlempngnsntshssstthts
ryan
readalamapardodsedefelidinlymynandnenontstub
raceckftgegsidilinkemompmsndngnkntpepsptreshsptetsulveysze
itchelem
roadamarbebsckdedslellmempofokomotpesasesssythtsutvewewsxy
rhea
ribscacechckcodedsftgagsllmemsndngnkotpepsscsesktetz
beadakamanaratauckdsefeneperesetgslallltlyndntnzrnrtsssttatsvy
weakanarbbbsdsedekephrldllntptrestts
babebychckdegsilitjakekuldlelilklllmndnengnknsrbrdrerkrnrrrsrtseshskssthtsudwlys
wacodeftgegshlilitkelkllltndnengntrdrermrnrprsrtryshspvexyys
blabedewipobocotowueumur
juandddedodygslympnengnknorareryst
boaratbscadedyergshrilisldllltmbndnengnnnyobokomonorosotrergrnsessthutwlwsydys
biasbsdedsenerkelelkllndngninsrdtets
wickdeerfegsldlellltlyndnengnknspereryseshspthtstt
whatenimipitizom
buckdddsffgslblkllmpmsnknsntoyrlrnrprrrtryshssstsyttyszz
joanbsdyelesgshninkeltsetsveys
jigsll
braeaganasatayedewieigimowyn
jeaneperffrksttsws
byrdte
wynn
ooze
onceeslytousyx
omanenit
olafavdyeggain
okay
oilsly
ohio
offs
oddsesinor
obeyoe
oaksrsthts
ivan
stabaganarayemepewiropowubudunyx
oxen
owedeneslsns
ovalenerid
ouchrsstts
otisto
oslo
oralesgyinly
opalecelentsus
vialcedaederesetewlenesatato
citety
chadaoaparatefenewicinipitopouum
coalataxbbcackcodedyedgshnilinkeldleltmbmeneokolonoppepspyrdrerkrnstsytsvewlwszy
cladamanapawayioipodogotubueuj
cabsdyfegeinkelflllmmempnensntpepsrdrerlrprrrsrtseshsksttsve
cedellltntrn
czar
cyst
zoneomosrn
crabagamayeeewibopowuduxuz
cubabebsedesffllltpsrbrdrerlrsrtsptets
vealdaergailinlannntrarbrnrystto
prayepeyimodoposow
pubsffghkelllpmampnsntnypapsrerrshsststt
smogugut
pylere
jabsckdeilkemsnersvawszz
paceckctdsgeidilinirlelllmlolsnengnsntparcrerkrrrsrtsosssttethtsulvewnwsys
peakalarasatckekelepergsltndnhnnnsntrkrusttetsws
phil
picackcteresgskelellmpnengnknsntonpesassthtstttyus
isisle
planayeaodotowoyugumus
hydemn
hubsckeseygeghgollmempmsngnknsntrdrlrtshskts
hickdeghkellltndntpsresstsve
hoaresffgsldlelmlymemoneodofokopotpepipsrnsesturwewlyt
haagasckhnilirlelfllltmsndngnsrdrerkrmrprtshtetsulvewkyszezy
headalaparatbeckedelirldlllmlpmpmsnsrarbrdrerorrrsssws
meadalanateketltmondnsnureshsstatetsws
macechdeidiliminkelelillltmanennnsnypsrcrerkrsrtrxryshsksssttethtsttulwryayoze
utah
moanatbsckdeenhrldlellnankntodonorotpsrernssstthvews
micaceckenkeldlelkllmindneninkntpsraressst
upon
twasiginos
podsemetgokelelklllompndngnyolorpepsrerkrtseshsttsurut
muchckddffgsirlellngseshsksttettzo
ulan
undoitixixto
imps
ugly
tabsckctftgsilkelelkllmengnkospepsrartskssteutxi
myrath
illsly
vailinlenensrysestts
acesheidmeneretats
abbabebyedeletlelyosut
adamdsen
agaredeeeresogue
afar
aidadedsmsnursry
swabamanapatayimum
akin
ajarax
amenesidmookosyl
alanarasbaeceeexfagalymamsoepssoumva
analdyewnaneonsitetitsus
aqua
apedesexse
asiaks
arabchcocseaesgoidmsmypats
auntrato
atomop
awayedlsry
averidisivonow
ayes
axedeleresisleon
icedeson
ibexidis
ideaemlelyol
igor
ifni
niceckghlenaneps
usederes
noahdedselllneokonrarmseteun
nagsgyilirmepsrysashtetourvyzi
nealaratckedffilllonrosssttsvawswtxt
voidltsstews
zulu
nudellmbnsts
franauayedeeeteyogomye
urdugeisnssa
fueljillmendnkrsrysesszz
ionstawa
facectdegsilinirkelkllmengnsrermsttetsunwnze
fearatedelesetllltndrnssud
zealrostus
fiateffegsjilelllmndnenknnnsrermshsksttsve
flagakamapatawaxeaedeeewexipitogopowueux
foalamciesgsgyilldlkndntodolotrdrerkrmrtssulurwl
kahnlinentrlrptetz
incachdodyksnsto
keelenepmpntptrnrrys
kickdselevllndngnkrksstets
spanatecedinitotunur
kochng
kneeewitobotowox
subschckdsedesezitlkmsngnknsrerf
klanux
skewidiminipisitye
siamanckdeftghgnkhlkllloltmsnengnknspsrerstetstuvaze
shameaedinipitodoeopotowunut
soakaparbsckdadsfaftilldlelomengnsnyonotrertulupurwnya
snagapipobowubug
kudohnrdrt
slabamapatavayedewidimipitobopotowugumur
scabanarotowud
sackfegagegsidilkelelkltlzmenandnengnkpsrarishteudulvewsys
sealamanarasatctedekemenepereslfllmindntptrfthtswsxy'''
w=raw_input()
s=[t[2:] for t in d.split() if t[:2]==w[:2]]
print s and w[2:] in [s[0][i:i+2] for i in range(0,len(s[0]),2)]

```
> 7 votes

# Answer
# Word VBA, 25 Bytes

Anonymous VBE immediate window function that takes input as the current selection and outputs if it is a word as boolean to the VBE immediate window.

```
?CheckSpelling(Selection)

```

### Tester Function

The below function was used to test the above function against the testcases. The function failed 9.07 percent of the cases (396 of the actual words and 10 of the fake words)

```
i=0:For Each w In Split(Selection,vbcr):i=i-CheckSpelling(w):Next:?i" were recognized as words

```
> 6 votes

# Answer
## C# WPF, 110 ~~139~~

Shorter

```
bool F(string s){var t=new TextBox();t.SpellCheck.IsEnabled=true;t.Text=s;return t.GetSpellingError(0)==null;}

```

Old answer

```
public bool F(string s){TextBox t=new TextBox();t.SpellCheck.IsEnabled=true;t.Text=s;SpellingError e=t.GetSpellingError(0);return e==null;}

```
> 5 votes

# Answer
# Mathematica, 33 bytes

Hey, somebody had to do it!

```
Length[DictionaryLookup[Input[]]]

```

Self-explanatory.
> 3 votes

# Answer
# Lexurgy, 106 bytes

Lexurgy, despite the fact it's meant for constructed languages, can be used for natural language processing as well.

Keeps the input if it thinks it's a word, and an empty string if it thinks it's not.

Reimplements @Sp3000's regex, so this **fails at the same rate (660 misclassifications)**.

```
Class V {a,e,i,o,u}
Class F {j,q,x,z}
a propagate:
[]? !@V !@V !@V []?=>*
[]=>*/{_ @F,@F _}
v:
@F=>*

```

Explanation:

```
# Define the classes
Class V {a,e,i,o,u}
Class F {j,q,x,z} # forbidden letters

a propagate:           # while the input is changed from last iteration:
[]? !@V !@V !@V []?=>* #   remove `[^aeiou]{3}`
[]=>*/{_ @F,@F _}      #   remove any letters next to the forbidden ones
v:                     # then:
@F=>*                  #   remove the forbidden letters

```
> 1 votes

# Answer
# Javascript ES6, 32 bytes:

Using the regex from @Sp3000 answer:

```
s=>!/[^aeiou]{3}|[jqxz]/.test(s)

```

This creates an anonymous function. To use it, you simply wrap it around `()`.

Example:

```
(s=>!/[^aeiou]{3}|[jqxz]/.test(s))('word')

```

This has **exactly** the same fail rate as @Sp3000, and returns `true` or `false` accordingly.

All credits due to @Sp3000 for letting me use his regex.
> 0 votes

---
Tags: code-golf, optimization, word, classification
---


# Question
Title: Write a pluralization function for Russian
In English, nouns can take on two different forms depending on whether they are singular (one) or plural (anything else). For example, we would say "1 dog" but "2 dogs", "0 dogs", "57 dogs" and so forth.

In Russian, there are three categories. Instead of "1 dog, 2 dogs, 5 dogs", in Russian it would be "1 собака, 2 собаки, 5 собак".

The categories are divided according to the following logic:

* "Singular": used for 1 and any number ending in 1, except for numbers ending in 11.
    + Examples: 1 собака, 21 собака, 101 собака
* "Few": used for 2, 3, and 4, and any number ending in 2, 3, or 4 except for numbers ending in 12, 13, and 14.
    + Examples: 2 собаки, 3 собаки, 4 собаки, 32 собаки, 43 собаки, 104 собаки
* "Many": anything that is not considered "Singular" or "Few".
    + Examples: 0 собак, 5 собак, 11 собак, 13 собак, 25 собак, 111 собак, 114 собак

## The challenge

Given an integer input in the range \[0, 1000\], return `1` if it belongs to the "singular" category, `2` if it belongs to the "few" category, and `5` if it belongs to the "many" category.

Your program may be a function or it can use STDIN. You may print to STDOUT or return a value from the function

This is a **code golf** challenge, so the solution with the fewest number of bytes wins.

# Answer
> 15 votes
# Python 2, 36 bytes

```
lambda n:'5521'[n%~9/-3>>n/10%~9/-9]

```

Try it online!

Same length arithmetically:

```
lambda n:5/(n%~9/-3>>n/10%~9/-9or 1)

```

Let's first look at simpler code that doesn't account for teens.

```
lambda n:'5521'[n%~9/-3]

```

Here, we want a mapping of the one's digit to an output that works like

```
[5, 1, 2, 2, 2, 5, 5, 5, 5, 5][n%10]

```

But, rather than take `n` modulo 10 (`%10`), we can do `n%-10`, which maps to the intervals `[-9..0]` to give remainders:

```
> [n%~9 for n in range(10)]
[0, -9, -8, -7, -6, -5, -4, -3, -2, -1]

```

This is promising because the first two entries `0` and `-9` are far apart, and they need to be sent to different outputs. Also, `-10` can be shortened to `~9`.

From here, floor-dividing by `/-3` gives chunks of 3 with the right starting spot

```
> [n%~9/-3 for n in range(10)]
[0, 3, 2, 2, 2, 1, 1, 1, 0, 0]

```

To get the desired output, we now just need to map `0->5, 1->5, 2->2, 1->1`, which we do with the string selection `'5521'[_]`.

Now, we also need numbers ending in 11 to 15 to always give `5`. We first do this by detecting whether then tens digit is `1`. Taking `n/10` to remove the last digit, we then apply `%~9` as before to get the outcomes

```
[0, -9, -8, -7, -6, -5, -4, -3, -2, -1]

```

for respective final digits. The digit of 1 that we want to detect is mapped to the extremal value `-9`. Floor-dividing by `-9` turns it to 1 and everything else to 0.

```
> [k%~9/-9 for k in range(10)]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]

```

Finally, we make this indicator being `1` always give output 5. This is done by bit-shifting the result of `n%~9/-3` right by the indicator. The result of `0,1,2,3` always bit-shifts right to 0 or 1, which gives an output of 5 as desired.

# Answer
> 13 votes
# Python 2, 45 bytes

```
lambda n,s='5122255555':(s+'5'*10+s*8)[n%100]

```

Try it online!

# Answer
> 9 votes
# Perl 5, 26 bytes

25 bytes of code + `-p` flag.

```
$_=/1.$|[5-90]$/?5:2-/1$/

```

Try it online!

For one more byte, there is `$_=/(?<!1)[1-4]$/?2-/1$/:5`.

**Explanations:** (on the 27 bytes version; the 26 is quite symmetrical)
Both "singular" and "few" end with "not a 1 followed by a digit from 1 to 4" (tested with `(?<!1)[1-4]$/`). In those case, the result is 2, minus 1 if the number ends with 1 (`2-/1$/`). Otherwise, the result if 5.

# Answer
> 7 votes
# JavaScript (ES6), ~~53~~ ~~49~~ ~~48~~ ~~40~~ ~~39~~ ~~38~~ ~~37~~ 36 bytes

```
n=>/[05-9]$|1.$/.test(n)?5:1+(n%5>1)

```

---

## Try it

```
f=
n=>/[05-9]$|1.$/.test(n)?5:1+(n%5>1)
oninput=_=>o.innerText=f(+i.value);o.innerText=f(i.value=0)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 5 votes
# Jelly,  ~~19~~  18 bytes

```
DµṖṚi1’ȧṪị“M;ọ6’D¤

```

A monadic link taking and returning non-negative integers.

**Try it online!** or see the three groups from 0 to 1000 inclusive in this test suite.

### How?

```
DµṖṚi1’ȧṪị“M;ọ6’D¤ - Main link: non-negative number, n  e.g. 301      311      313
D                  - cast to decimal list                [3,0,1]  [3,1,1]  [1,3,3]
 µ                 - monadic chain separation, call that d
  Ṗ                - pop d                               [3,0]      [3,1]    [1,3]
   Ṛ               - reverse                             [0,3]      [1,3]    [3,1]
     1             - literal 1
    i              - first index of (0 if not found)      0          1        2
      ’            - decrement                           -1          0        1
        Ṫ          - tail d                               1          1        3
       ȧ           - logical and                          1          0        3
                 ¤ - nilad followed by link(s) as a nilad:
          “M;ọ6’   -   base 250 literal = 1222555555
                D  -   cast to decimal list [1,2,2,2,5,5,5,5,5,5]
         ị         - index into (1-based and modular)     1          5        2

```

# Answer
> 4 votes
# 05AB1E, ~~38~~ 19 bytes

Uses the index-trick from Rod's python answer

```
•1rê¢°•©5T×®9×JIт%è

```

Try it online!

**Explanation**

```
•1rê¢°•              # push the number 5122255555
       ©             # store a copy in register
        5T×          # push 5 repeated 10 times
           ®         # retrieve the first number from register
            9×       # repeat it 9 times
              J      # join everything to string
               Iт%   # push input mod 100
                  è  # use this to index into the string of digits

```

# Answer
> 2 votes
# PHP\>=7.1, 44 Bytes

```
<?=$argn[-2]!=1&($m=($argn+9)%10)<4?2-!$m:5;

```

Online Version

# Answer
> 2 votes
# Retina, ~~25~~ 21 bytes

```
1.$
5
T`d`512225
!`.$

```

Try it online! -4 bytes thanks to Neil.

# Answer
> 2 votes
# MCxxxx Assembly, 123 Bytes

```
e:slx x0
mov x0 acc
dst 2 0
tlt acc 11
-tgt acc 14
-jmp v
+dgt 0
teq acc 1
+mov 1 x1
+jmp e
tlt acc 5
+mov 2 x1
v:-mov 5 x1

```

### Note:

TiO doesn't support this language, which is used in the Zachtronics game Shenzhen I/O, so there's no link to test this.

## Explanation:

This is a function that takes input through XBus port x0, and outputs through port x1. It's too long to execute on an MC4000, but fits nicely into the memory of an MC6000. XBus ports, for those unfamiliar, allow the transmission of discrete packets of digital data.

One piece of information that may be helpful in reading this: in MCxxxx assembly, test instructions set a flag that indicates which branch should be taken. Lines that begin with `+` are only executed if the most recent test returned true, and lines that begin with `-` are only executed if the test was false.

Line by line:

```
e:slx x0    # Label this line e, then sleep until input is available on XBus port x0
mov x0 acc  # Move the input into register acc
dst 2 0     # Set the leftmost digit of the input to 0
tlt acc 11  # Test if the value in acc is less than 11
-tgt acc 14 # If it's not, check if it's greater than 14
-jmp v      # If it's not, jump to the line labeled v (the last line)
+dgt 0      # If either of the previous tests returned true,
            #     set acc to the value of acc's rightmost digit
teq acc 1   # Test if acc equals 1
+mov 1 x1   # If it does, return 1
+jmp e      # Then jump to label e, which ends execution
tlt acc 5   # Test if acc is less than 5
+mov 2 x1   # If it is, return 2
v:-mov 5 x1 # If the previous test is false, return 5

```

A note about scoring: MCxxxx assembly doesn't have functions per se, but this is as close to a function as you can get - it's a program that fits in a single execution node, takes input through one port and outputs through another. As a result, I've scored this like a function (i.e. without counting the bytes necessary to make a valid MCxxxx emulator file).

# Answer
> 1 votes
# Haskell, 62 58 bytes

```
f n|s<-"5122255555"=(s++('5'<$[0..9])++cycle s)!!mod n 100

```

Try it online!

## Explanation

This builds the following string:

5122255555555555555551222555555122255555512225555551222555555122255555512225555551222555555122255555...

Which is a table where cell `n` contains the answer for the `nth` number. The table is only correct for the first 100 elements, hence the `mod`.

# Answer
> 0 votes
**Scala, 110 bytes**

```
n=>Stream.iterate("512225555555555555555")(_=>"1222555555").flatMap(_.toCharArray).map(_.toInt).take(n-1).head

```

# Answer
> 0 votes
# Turtlèd, 35 bytes

```
!--.(1#0#)+.@3(1@1)(2@2)(3@2)(4@2),

```

Try it online!

This function requires that the input starts with a \>, which I guess is ok because python2 uses input semi regularly, and that needs quotes.

Explanation:

```
!             input the number as a string, complete with the >
 --.          wrap around to the end of the string, and then move one back. if this
              is a single digit, we end up on the >,
              otherwise we end up on the second to last digit. write the digit/>

    (1#0#)    if it is 1, set the string to 0. this way it will always write 3 at the end.

          +.       write the last digit (or 0 if the second last digit was 1)
            @3      set the character variable to 3. this means if what was written was not
                       in (1, 2, 3, 4), then it will write 3 at the end
              (1@1)    if the character written was a 1, set the character to be written
                       at the end to 1
                   (2@2)(3@2)(4@2)
                     if it is any of 2,3,4, set the character to be written at the end to 2
                                  ,    write the character that was set

```

# Answer
> 0 votes
# Lexurgy, 88 bytes

```
s:
\1=>\1/_ $//\1 _ $
else:
{\2,\3,\4}=>\2/_//\1 _ $
else:
[]=>\5
c:
[]=>*/_//_ $

```

Ungolfed explanation:

```
singular: # 1 to 1 if no 1 preceding 1
\1=>\1/_ $//\1 _ $
else:     # 2,3,4 to 2 if no preceding 1
{\2,\3,\4}=>\2/_ $//\1 _ $
else:     # everything else to 5
[]=>\5/_ $

clean:    # keep only the last digit
[]=>*/_//_ $

```

Trivia: the technical linguistics terms for `one, few, many` is `singular, paucal, plural`.

---
Tags: code-golf, natural-language, classification
---


title: Parse my Esperanto!

text:
# Question
Title: Parse my Esperanto!
The famous constructed language Esperanto uses the Latin alphabet (mostly, see the linked wikipedia page for details). However, there are some characters with accents: **ĉ, ĝ, ĥ, ĵ, ŝ, and ŭ**. (C-circumflex, g-circumflex, h-circumflex, j-circumflex, s-circumflex, and u-**breve**.) Naturally, these characters are very hard to type. Even for this question, I had to search in the Unicode selector for the characters. Due to this, a convention using the letter "x" has been developed for electronic use. For example, "cxu" is used for "ĉu". (Note: the letter "x" is not used normally in the Esperanto alphabet."

However, I am a language purist! This \*air quote\* x nonsense is killing me! I need a program to fix this, preferably as short as possible so I can type it into my terminal as fast as possible!

## Challenge

Your mission is to take a string of Esperanto using x-convention and convert it to real Esperanto.

In effect, you have to map:

```
cx: ĉ
gx: ĝ
hx: ĥ
jx: ĵ
sx: ŝ
ux: ŭ
Cx: Ĉ
Gx: Ĝ
Hx: Ĥ
Jx: Ĵ
Sx: Ŝ
Ux: Ŭ

```

All other printable ASCII characters should be accepted and not changed. Unicode would be nice, but not necessary.

Input and output can be in any format reasonable to your language. Good luck!

## Testcases

```
"input" : "output"
_____________
"gxi estas varma" : "ĝi estas varma"
"Cxu sxi sxatas katojn aux hundojn?" : "Ĉu ŝi ŝatas katojn aŭ hundojn?"
"Uxcxsxabcd(hxSx)efg{};" : "Ŭĉŝabcd(ĥŜ)efg{};"
"qwertyuiop" : "qwertyuiop"
" " : " "
"" : ""
"x" : "x"
"xc" : "xc"
"xcx" : "xĉ"
"cxx" : "ĉx"

```

## Scoring

This is . Answers are scored by smallest bytecount in the language's default encoding.

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
# Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
# Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
# Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the leaderboard snippet:

```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=149292,OVERRIDE_USER=47670;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

Good luck, have fun, and feel free to suggest improvements!

## Clarifications:

* You only need to worry about *printable* ASCII characters.
* You only need to output a character that *looks like* the correct output. Yes, this means you can tack the accent onto the standard character.

# Answer
> 9 votes
# QuadR, 65 bytes

```
.x
3::⍵M⋄'ĉĝĥĵŝŭĈĜĤĴŜŬ'['cghjsuCGHJSU'⍳⊃⍵M]

```

Try it online!

`.x` replace any char followed by "x" with

`3::⍵M` upon indexing error, return the match unmodified
now try:
`'ĉĝĥĵŝŭĈĜĤĴŜŬ'[``]` index into this string with
`⍵M` the match's
first letter's
index
`'cghjsuCGHJSU'` in this string

This is equivalent to the Dyalog APL tacit function:

```
'.x'⎕R{3::⍵.Match⋄'ĉĝĥĵŝŭĈĜĤĴŜŬ'['cghjsuCGHJSU'⍳⊃⍵.Match]}

```

# Answer
> 7 votes
# Retina, 27 bytes

```
iT`x`̂`[cghjs]x
iT`x`̆`ux

```

Try it online!

This program is composed by two transliterations. Due to having combining characters in the code this doesn't render too well, the first line should actually look similar to `iT`x`^`[cghjs]x`, where `^` stands for the circumflex accent combining character. What this is saying is that it should `T`ransliterate (`i`gnoring case) all the `x`s in the input into a `^`, whenever they are following any letter in `[cghjs]`.

---

Note: TIO incorrectly measures this code as 25 bytes. Actually, this Retina program uses UTF-8 encoding (other programs can use UTF-32 or ISO 8859-1) and the two combining characters present cost 2 bytes each.

# Answer
> 5 votes
# C,  ~~173~~  154 bytes

*Thanks to @Colera Su for saving 17 bytes!*

```
p,c,i;f(char*s){for(char*l="cghjsuCGHJSU";p=*s;~c&&putchar(p))for(c=*++s,i=0;c=='x'&&l[i];++i)l[i]-p||write(1,"ĉĝĥĵŝŭĈĜĤĴŜŬ"+i*2,2,c=-1,++s);}

```

Try it online!

**Explanation:**

```
p,c,i;
f(char*s)
{
    // The outer loop and an array of characters that are modified by a trailing 'x'.
    // The array/string is used for getting the index for the accented character later.
    for (char*l="cghjsuCGHJSU";

                                // Store the current character of the input string in 'p'.
                                // If it is '\0', the loop terminates.
                                p=*s;

                                      // The last statement in the loop.
                                      // If 'c==-1', it outputs the char stored in 'p'.
                                      ~c&&putchar(p))

        // Store the character following 'p' in 'c' and increment the string pointer.
        for(c=*++s, i=0;

                        // If 'c' is not the letter 'x', the inner loop terminates
                        // immediately. Otherwise it loops through the characters of
                        // string 'l'.
                        c=='x'&&l[i]; ++i)

            // If the character stored in 'p' is found inside the string 'l'...
            l[i]-p ||

                      // ...then print the accented character corresponding to 'p'.
                      // 'i' is the index of 'p' in 'l', and, because the characters
                      // with accents are two bytes each, the index is multiplied by 2.
                      write(1,"ĉĝĥĵŝŭĈĜĤĴŜŬ"+i*2,2,

                      // Finally set 'c' to -1 so that the non-accented character doesn't
                      // get printed too, and increment the string pointer so that the
                      // letter 'x' doesn't get printed either.
                                                    c=-1, ++s);
}

```

# Answer
> 5 votes
# Python 3, 81 bytes

```
lambda s,T="cĉgĝhĥjĵsŝuŭ":eval("s"+".replace('%sx',%r)"*12%(*T+T.upper(),))

```

Try it online!

Generates and evaluates the string:

```
s.replace('cx','ĉ').replace('gx','ĝ').replace('hx','ĥ').replace('jx','ĵ').replace('sx','ŝ').replace('ux','ŭ').replace('Cx','Ĉ').replace('Gx','Ĝ').replace('Hx','Ĥ').replace('Jx','Ĵ').replace('Sx','Ŝ').replace('Ux','Ŭ')

```

*Erik the Outgolfer saved a byte.*

# Answer
> 3 votes
# ///, 75 bytes

```
/,/\/\///>/x\,/c>ĉ,g>ĝ,h>ĥ,j>ĵ,s>ŝ,u>ŭ,C>Ĉ,G>Ĝ,H>Ĥ,J>Ĵ,S>Ŝ,U>Ŭ/

```

Note: Because the OP request all printable characters must be processed, my "special characters" chosen must not be printable. So I chosen tab and newline instead of , which does not change my bytecount or code functionality. The code would look like:

```
/
/\/\/// /x\
/c  ĉ
g   ĝ
h   ĥ
j   ĵ
s   ŝ
u   ŭ
C   Ĉ
G   Ĝ
H   Ĥ
J   Ĵ
S   Ŝ
U   Ŭ/

```

However that requires the input must not contains tab or newlines.

Try it online!

Because `///` can't take input, you should put the input after the code.

Pretty straightforward. I guess it can't be shorter because `///` need special handling of each character.

Explanation:

```
/,/\/\//       Replace all `,` in the code by `//`
               (two slashes are represented as two backslash-ed slashes)
/>/x\,         (in original code) becomes
/>/x\//        (because `,` is replaced by `//`) - replace all occurence of
               `>` by `x/`.
/cx/ĉ//gx/ĝ//hx/ĥ//jx/ĵ//sx/ŝ//ux/ŭ//Cx/Ĉ//Gx/Ĝ//Hx/Ĥ//Jx/Ĵ//Sx/Ŝ//Ux/Ŭ/
               ^ The remaining part of the code should look like this.
               Straightforward replacement.

```

# Answer
> 2 votes
# Python 3, 95 bytes

```
f=lambda x,v="cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ":v and f(x.replace(v[0]+"x",v[1]),v[2:])or x

```

Try it online!

-10 bytes thanks to WhatToDo
-1 byte thanks to Colera Su

# Answer
> 2 votes
# Retina, 55 bytes

```
iT`CG\HJSUcg\hjsux`ĈĜĤĴŜŬĉĝĥĵŝŭ_`[cghjsux]x

```

Try it online! Non-combining approach. Bytes could be saved if not for the standalone `x` test cases.

# Answer
> 1 votes
# Perl 5, 101 + 1 (`-p`) = 102 bytes

```
%k=qw/c ĉ g ĝ h ĥ j ĵ s ŝ u ŭ C Ĉ G Ĝ H Ĥ J Ĵ S Ŝ U Ŭ/;$"=join"|",keys%k;s/($")x/$k{$1}/g

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 92 bytes

```
s=>[..."cghjsuCGHJSU"].reduce((a,v,i)=>a.split(v+"x").join("ĉĝĥĵŝŭĈĜĤĴŜŬ"[i]),s)

```

Try it online!

Used split-join method recommended in here to reduce byte counts because the `new RegExp(/*blah*/)` constructor took up too many bytes.

Comparison:

```
Original: a.replace(new RegExp(v+"x", "g"), "ĉĝĥĵŝŭĈĜĤĴŜŬ"[i])
New     : a.split(v+"x").join("ĉĝĥĵŝŭĈĜĤĴŜŬ"[i])

```

Shorter, combining accent approach (63 bytes), but with some artifacts visible.

```
s=>s.replace(/([cghjs])x/gi," ̂$1").replace(/(u)x/gi," ̌$1");

```

Footnote: I'm claiming my answer 92 bytes because the 63-byte solution has artifacts that may affect the output.

# Answer
> 1 votes
# C, ~~145~~ 144 bytes

Another C approach. Return by overwriting the input, using the fact that circumflex / breve are 2 bytes.

*-1 bytes thanks to Steadybox.*

```
i,t;f(char*s){for(t=1;*s;s++)if(*s^'x')for(i=12,t=1;i--;)t="cghjsuCGHJSU"[i]-*s?t:i*2;else t^1&&memcpy(s-1,"ĉĝĥĵŝŭĈĜĤĴŜŬ"+t,2),t=1;}

```

Try it online!

# Answer
> 1 votes
# QuadR, 25 bytes

Combining diacritics edition.

```
ux
([cghjs])x
 ̆&
 ̂\1

```

`i` flag

Try it online!

*Replace…*

```
(u)x         u followed by x and
([cghjs])x   any of these letters followed by x …
 ̆\1          by a breve followed by the first group (the u) and
 ̂\1          a circumflex followed by the first group (the letter)

```

*case **i**nsensitively*

Equivalent to the following Dyalog APL code:

```
'(u)x' '([cghjs])x'⎕R' ̆\1' ' ̂\1'

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 57 bytes

Anonymous tacit function. Usages:

1. Prefix function to string. This transliterates the string.
2. Prefix function to list of strings. This transliterates the strings.
3. Infix function with input file tie number as right argument and output file tie number as left argument. This populates the output file with the transliterated content of the input file.

`('cghjsuCGHJSU',¨'x')⎕R(,¨'ĉĝĥĵŝŭĈĜĤĴŜŬ')`

`(``)⎕R(``)` PCRE **R**eplace

`'cghjsuCGHJSU'` these letters

`,¨'x'` each followed by an x

… with…

`,¨'ĉĝĥĵŝŭĈĜĤĴŜŬ'` each of these letters as strings

Try it online!

# Answer
> 1 votes
# Perl 5, 49 + 2 (`-p -C`) = ~~61~~ 51 bytes

```
s/[CGHJScghjs]\Kx/\x{0302}/g;s/[Uu]\Kx/\x{0306}/g

```

Try it online!

*Saved 10 bytes thanks to Nahuel Fouilleul*

# Answer
> 1 votes
# , 64 63 bytes

```
rplc((_2]\'ĉĝĥĵŝŭĈĜĤĴŜŬ');~"1'cghjsuCGHJSU',.'x')"0

```

How it works:

With `_2]\` I rearrange the string 'ĉĝĥĵŝŭĈĜĤĴŜŬ' into a 12-row column in order to fit the shape of the other string.

`,.` adds 'x' to each character of the 'cghjsuCGHJSU' string and makes a 12 row by 2 columns array

`;~"1'` makes a list of boxed pairs of the above, "1 - rank 1 - apply to each row.

```
┌──┬──┐
│cx│ĉ │
├──┼──┤
│gx│ĝ │
├──┼──┤
│hx│ĥ │
├──┼──┤
│jx│ĵ │
├──┼──┤
│sx│ŝ │
├──┼──┤
│ux│ŭ │
├──┼──┤
│Cx│Ĉ │
├──┼──┤
│Gx│Ĝ │
├──┼──┤
│Hx│Ĥ │
├──┼──┤
│Jx│Ĵ │
├──┼──┤
│Sx│Ŝ │
├──┼──┤
│Ux│Ŭ │
└──┴──┘

```

`rplc` uses these boxed items to replace each occurrence of the left boxed item from a pair with the right one.

Try it online!

# Answer
> 1 votes
# , ~~75~~ 70 bytes

```
function(s)gsub('([cghjs])x','\\1\U302',gsub('(u)x','\\1\U306',s,T),T)

```

Try it online!

-5 bytes thanks to Giuseppe

### Explanation

* `gsub('(u)x','\\1\U306',s,T)`: replace in `s` every occurrence of an uppercase or lowercase "u" (by using `ignore.case=TRUE` via the fourth argument `T`) followed by an "x" the "u" followed by the unicode for a breve
* `gsub('([cghjs])x','\\1\U302',gsub('(u)x','\\1\U306',s,T),T)`: take the result of that and replace every occurrence of an uppercase or lowercase (by using `ignore.case=TRUE` via the fourth argument `T`) "c", "g", "h", "j", or "s" followed by an "x" with the letter followed by the unicode for a circumflex

# Answer
> 1 votes
# Befunge, 2x48 +1 = 99 bytes

```
>~:1+!#@_:"x"-v>$ 11p0"cghjsuCGHJSU"1\ >\31p11g-v
^ # #, : ++$\ _^#1"x"0*4!-"u"g11*"ʊ"!\_^#!:\*g13<

```

Try It Out (TIO is super weird about Befunge and I couldn't get any of my solutions to work on it)

### How it works

```
>~:1+!@_

```

Gets input and checks if it's the end. End program if it is.

```
          "x"-v>
^ # #, : ++$\ _^

```

Checks if the character is an "x". If not, keep a copy of the character and print it.

```
               >$ 11p0"cghjsuCGHJSU"1\

```

Store the last character at (1,1). Puts all the characters to check into the stack.

```
                                       >\31p11g-v
                                      _^#!:\*g13<

```

Compare the last character against all the values in the stack.

```
                 1"x"0*4!-"u"g11*"ʊ"!\

```

Multiply the check (0 or 1) by ʊ (unicode value 650). Check whether the character was a u (for the breve) and adds 4 to the stack if so. Finally, add the ascii value of x (100) as well. The total adds up to the correct accent if needed or just an "x" if not.

```
>~:1+!#@_
^ # #, : ++$\ _^#

```

Add all the values in the stack together, print it and keep a duplicate. Go back up for the next input.

# Answer
> 1 votes
# Mathematica, 81 bytes or 57 bytes

`StringReplace[RemoveDiacritics@#<>"x"->#&/@Characters@"ĉĝĥĵŝŭĈĜĤĴŜŬ"]`

It applies a replacement rule where the letter without the hat together with an "x" is replaced by the letter.

Here is an alternative using the added accents character: `StringReplace[{"ux"->"ŭ","Ux"->"Ŭ",c_~~"x":>c<>"̂"}]`

# Answer
> 1 votes
# sed, 40 bytes (38 chars)

```
s/([cghjsCGHJS])x/\1̂/g
s/(u|U)x/\1̆/g

```

Try it online!

I believe this is different enough from iBug's answer.

# Answer
> 1 votes
# Lexurgy, ~~60~~ 48 bytes

```
a:
x=>̂/{c,g,h,j,s,C,G,H,J,S} _
x=>̆/{U,u} _

```

Replaces `x` with the correct combining diacritic based on the preceding character.

* -12 bytes for removing the `Class`.

# Answer
> 0 votes
# CJam, 51 bytes

```
q"ĉĝĥĵŝŭĈĜĤĴŜŬ""cghjsuCGHJSU".{'x+@\/*}

```

Try it online!

Explanation:

```
q                   Read input
"ĉĝĥĵŝŭĈĜĤĴŜŬ"      String literal
"cghjsuCGHJSU"      Another string literal
.{                  Iterate over the strings in parallel
  'x+                 Add an 'x to the normal character
  @                   Rotate to bring the input to the top of stack
  \                   Swap to bring the "cx" to the top
  /                   Split the input on instances of "cx"
  *                   Join the input on instances of the accented character
}

```

# Answer
> 0 votes
## PowerShell, 58 bytes

It's 54 characters and saving it in PowerShell ISE makes it UTF-8 + BOM for 58 bytes. It doesn't render as nicely in a browser:

```
$args-replace'(?<=u)x','̆'-replace'(?<=[cghjs])x','̂'

```

regex replaces the x with the combining Unicode characters from @user202729's comment.

e.g.

```
PS C:\> .\eo.ps1 "Cxu vi sxatas la cxapelliterojn? Mi ankaux."
Ĉu vi ŝatas la ĉapelliterojn? Mi ankaŭ.

```

# Answer
> 0 votes
# Clojure, ~~126~~ 115 bytes

-11 bytes by changing the replacement map to a partition of a string.

```
#(reduce(fn[a[f r]](clojure.string/replace a(str f\x)(str r)))%(partition 2"cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ"))

```

A reduction over a map of replacements to look for, and what to replace them with.

Still working on a way to compress the replacement map.

```
(defn translate [^String esperanto]
  (reduce (fn [acc [f r]] (clojure.string/replace
                            acc ; Replace the translation so far by
                            (str f \x) ; adding a x after each character, search for it in the string,
                            (str r))) ; and replace it with a stringified accented char

          esperanto ; Before the reduction happens, the accumulator is the original string

          ; A list of [char-to-find what-to-replace-with] pairs
          (partition 2"cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ")))))

```

# Answer
> 0 votes
# JavaScript (ES6), 91 bytes

```
(i,s='cĉgĝhĥjĵsŝuŭCĈGĜHĤJĴSŜUŬ')=>i.replace(/.x/g,m=>s[1+s.search(m[0])||s]||m)

```

Try it online!

# Answer
> 0 votes
# Scala, 110 bytes

Boring regex solution:

```
def?(s:String)="(.)x".r.replaceAllIn(s,m=>m.group(0)(0)+(if(m.group(0)(0).toUpper=='U')"\u0306"else"\u0302"))

```

Old scala solution (116 bytes)

```
def?(s:String)=s.foldLeft("")((r,c)=>if(c=='x')r.init+r.last+(if(r.last.toUpper=='U')"\u0306"else"\u0302")else r+c)

```

Ungolfed

```
def?(s:String)=
  s.foldLeft("")((r,c)=>  // 'Fold' string with empty string as first result
    if(c=='x')            // If current character is x
      r.init+             // Take the every character from result but the last
        r.last+           // The last character from result and add
          (if(r.last.toUpper=='U')
            "\u0306"      // combining breve if 'u' or 'U'
          else"\u0302")   // combining circumflex in any other case
 else r+c                 // Otherwise return result + character
)

```

# Answer
> 0 votes
# JavaScript, 35 chars, 36 bytes

```
s=>s.replace(/([cghjsu])x/gi,"$1̂")

```

# Answer
> 0 votes
# Raku, ~~57~~ 50 bytes

```
{S:g:i/(<[cghjsu]>)x/{$0~chr 770+4*("u"eq$0.lc)}/}

```

Try it online!

# Answer
> 0 votes
# Zsh, 71 bytes

```
for 2 3 (`fold -1<<<${a=cĉgĝhĥjĵsŝuŭ}${a:u}`)1=${1//$2x/$3}
<<<$1

```

Try it online!

# Answer
> -1 votes
# sed, 108 bytes

```
s/cx/ĉ/g
s/gx/ĝ/g
s/hx/ĥ/g
s/jx/ĵ/g
s/sx/ŝ/g
s/ux/ŭ/g
s/Cx/Ĉ/g
s/Gx/Ĝ/g
s/Hx/Ĥ/g
s/Jx/Ĵ/g
s/Sx/Ŝ/g
s/Ux/Ŭ/g

```

---
Tags: code-golf, string, parsing, natural-language, unicode
---


title: Output the next kana

text:
# Question
Title: Output the next kana
Japanese kana characters correspond to a single sound in the Japanese language. With the exception of ん (*n*), every other kana consists of a consonant part and a vowel part. There is a natural ordering to Japanese kana, a sort of "alphabetical order", which is typically arranged in a 10 by 5 table:

```
   |   a    i    u    e    o
-----------------------------
*  |   a    i    u    e    o
k  |  ka   ki   ku   ke   ko
s  |  sa   si   su   se   so
t  |  ta   ti   tu   te   to
n  |  na   ni   nu   ne   no
h  |  ha   hi   hu   he   ho
m  |  ma   mi   mu   me   mo
y  |  ya        yu        yo
r  |  ra   ri   ru   re   ro
w  |  wa                  wo

```

This ordering is called *gojuuon*, or "fifty sounds", even though some of the fifty cells in the table are in fact empty.

## The challenge

Input will be any of the listed kana above, with the exception for *wo*. Your program or function should output the next kana along in left-to-right, top-to-bottom reading order, e.g:

```
Input       Output
------------------
a     ->    i
i     ->    u
o     ->    ka
ke    ->    ko
so    ->    ta
ni    ->    nu
ya    ->    yu
yu    ->    yo
wa    ->    wo
wo    ->    (undefined behaviour)

```

With the exception of an optional single trailing newline, there should be no leading or trailing whitespace in the output.

This is , so the goal is to minimise program size, in bytes.

## Additional notes

* In order to keep things simple, this challenge uses Nihon-shiki romanisation. Hepburn romanisation is more common, but has a few kinks which make things more annoying for golf (e.g. *si* becomes *shi*, *hu* becomes *fu*).
* Kana *do* exist for the empty spots (see Japanese SE), but they were either non-standard or are now obsolete.

# Answer
> 16 votes
## Retina, ~~54~~ 53 bytes

```
T`au`ie`y.
wa
we
T`\oeuia`ao
T`ko`stn\hmyr\w`.a
^a
ka

```

Try it online.

### Explanation

Wooo, showing off even more features from today's 0.7.2 release. :) (The release predates this challenge by about 7 hours.)

```
T`au`ie`y.

```

This is a transliteration which replaces `a` with `i` and `u` with `e`, but only in matches of `y.`. The purpose of that is to treat `ya` and `yu` like `yi` and `ye`, respectively, in order to skip the gaps.

```
wa
we

```

Replace `wa` with `we` to skip that gap as well.

```
T`\oeuia`ao

```

Here is the new feature. When rotating sets of characters, the "from" and "to" set in a transliteration are usually almost identical. So now we've got `o` (without a backslash) to refer to the other set, which allows us to get rid of some duplication. The `\o` just stands for a literal `o` in that case. So the two sets expand to:

```
oeuia
aoeuia

```

The extraneous `a` in the second set is ignored and the vowels are replaced cyclically as expected.

```
T`ko`stn\hmyr\w`.a

```

This does the same thing for the consonants, but using `o` in the first set (just because we can...). `h` and `w` need escaping because they are character classes. The expanded sets are:

```
kstnhmyrw
stnhmyrw

```

The `.a` restricts this operation to syllables that end in `a`, i.e. those that wrap to the next line of the table.

```
^a
ka

```

Finally, we replace a single `a` with `ka`, because that case cannot be handled by the previous transliteration.

# Answer
> 5 votes
## Pyth, ~~42~~ ~~40~~ 38 bytes

```
s.r]z.DrR6*" kstnhmyrw""aiueo"CM"$&./0

```

This takes the outer product between vowels and consonants, and removes elements at the ords of each number in `$&./0`. Then it outputs the element after the input.

```
@J.DrR6*" kstnhmyrw""aiueo"CM"$&./0"hxJz    Implicit: z=input()
       *" kstnhmyrw""aiueo"                 Outer product: [' a',...,' o','ka',...]
    rR6                                     Strip each string—'a'~'o' now single letters
                           CM"$&./0"        Map ord onto the string: [36,38,46,47,48]
  .D                                        Remove elements at those indices.
 J                                          That's the list of kana; assign it to J
                                     xJz    Find the index (x) of z in J,
                                    h       add one,
@J                                          and access J at that index.

```

Try it here.

# Answer
> 5 votes
# GNU sed, 65

Comments not included in score:

```
:                        # Define unnamed label
y/aiueo/iueoa/           # Rotate vowels
/a/y/kstnhmyr/stnhmyrw/  # If at end of row, rotate consonants
s/^a/ka/                 # If at end of 1st row, prefix a "k"
/[yw][ie]\|wu/b          # If one of the invalid values, jump back to label and redo

```

Oy, this is beginning to look a lot like @Martin's Retina answer (but longer, of course).

# Answer
> 4 votes
# Ruby, 105

```
->n{a=['wo','wa']
'rymhntsk '.chars{|c|a+='*o *e *u *i *a'.tr(?*,c).split}
a[8..10]='yu'
a[a.index(n)-1]}

```

Commented in test program

```
f=->n{a=['wo','wa']                     #initialize array to last line of table, begin to build table backwards
  'rymhntsk '.chars{|c|                 #for each consonant,
    a+='*o *e *u *i *a'.tr(?*,c).split  #perform a sustitution to get that line of table in string form,
  }                                     #then split into array at spaces and append to a
  a[8..10]='yu'                         #substitute 3 elements ye yu yi with 1 element yu
  a[a.index(n)-1]                       #return element before argument (array is backwards.)
}

puts f[gets.chop]

```

# Answer
> 3 votes
# TXR Lisp, ~~135~~ ~~127~~ ~~124~~ 91 bytes

```
(ret[(memqual @1(diff(maprod(op trim-str`@1@2`)" kstnhmyrw""aiueo")'#"yi ye wi wu we"))1])

```

Run:

```
1> (ret[(memqual @1(diff(maprod(op trim-str`@1@2`)" kstnhmyrw""aiueo")'#"yi ye wi wu we"))1])
#<interpreted fun: lambda (#:arg-1-0208 . #:arg-rest-0207)>
2> [*1 "a"]
"i"
3> [*1 "o"]
"ka"
4> [*1 "ki"]
"ku"
5> [*1 "mu"]
"me"
6> [*1 "ya"]
"yu"
7> [*1 "yo"]
"ra"
8> [*1 "wa"]
"wo"

```

# Answer
> 1 votes
## JavaScript, ~~145~~ ~~162~~ ~~131~~ 118 bytes

```
x=>(d=" kstnhmyrw".replace(/./g,"$&a$&i$&u$&e$&o").replace(/ |yi|ye|wiwuwe/g,"").match(/[^aiueo]?./g))[d.indexOf(x)+1]

```

~~Admit it, you couldn't imagine a more ridiculous solution to solve this problem ;)~~ ok, done this in a more interesting way.

Demo:

```
function p(x) {
  return (d=" kstnhmyrw".replace(/./g,"$&a$&i$&u$&e$&o") //build the sequence of kana, regex rulez!
        .replace(/ |yi|ye|wiwuwe/g,"")                   //remove the spaces and excess kana
        .match(/[^aiueo]?./g))[d.indexOf(x)+1]           //split it into array using regex and get the index of input in it
}

alert(p(prompt()))
```

# Answer
> 1 votes
# Bash + sed, 83

```
echo {,k,s,t,n,h,m,y,r,w}{a,i,u,e,o}|sed -E "s/[yw][ie]|wu//g;s/.*\b$1 +//;s/ .*//"

```
* Brace expansion to create full table on one line
* sed to:
    + remove `yi`, `ye`, `wi`, `wu` and `we`
    + remove everything up to and including the input entry (but not the next entry)
    + remove everything after the next entry

# Answer
> 1 votes
## Haskell, ~~114~~ 96 bytes

```
f"ya"="yu"
f"yu"="yo"
f"wa"="wo"
f x=snd(span(/=x)[words[a,b]!!0|a<-" kstnhmyrw",b<-"aiueo"])!!1

```

`[words[a,b]!!0|a<-" kstnhmyrw",b<-"aiueo"]` is a list of all kanas, including the "holes". I break up the list into the part before the input kana and from the input kana up to the end. From the 2nd part I pick the second element. The exceptions around the "holes" a caught before by separate cases.

Edit: @xnor came up with the idea of using `span`which saved 18 bytes.

# Answer
> 1 votes
## Japt, ~~75~~ ~~70~~ 68 bytes

```
X=" kstnhmyrw"£"aiueo"®+X w} r" |yi|ye|wiwuwe"P f"[^aiueo]?.")g1+XbU

```

Try it online!

# Answer
> 1 votes
# Lexurgy, 115 bytes

```
a:
{a,i,u,e,o}=>{i,u,e,o,'a}
b:
'=>k/$ _
{',k,s,t,n,h,m,y,r,w} '=>{k,s,t,n,h,m,y,r,w,`} *
y:
{i,e}=>{u,o}/y _

```

Explained:

```
# advance the vowel
a:
{a,i,u,e,o}=>{i,u,e,o,'a}
# advance the consonant
b:
'=>k/$ _ # o => ka case
{',k,s,t,n,h,m,y,r,w} '=>{k,s,t,n,h,m,y,r,w,`} * # everything else
# force yu yo
y:
{i,e}=>{u,o}/y _

```

# Answer
> 0 votes
# Perl 6, 105 bytes

```
.[.first(@*ARGS[0],:k)+1].say with (" kstnhmyrw".comb X~ <a e i o u>).grep(* !~~/[y|w][i|e]|wu/)».trim

```

This is as short as I can get it on my first go, I might have another crack at it later but I feel pretty good about this.

# Answer
> 0 votes
# JavaScript (ES6), 127 bytes

```
s=>s>"yt"?"yo":s=="ya"?"yu":s=="wa"?"wo":(m=[].concat(...["",..."kstnhmyrw"].map(c=>[..."aiueo"].map(v=>c+v))),m[m.indexOf(s)+1])

```

## Explanation

```
s=>

  // Hardcode "yu", "ya" and "wa"
  s>"yt"?"yo":
  s=="ya"?"yu":
  s=="wa"?"wo":

  // Generate table
  (m=[].concat(...                                   // flatten the array of arrays
    ["",                                             // first consonant is blank
    ..."kstnhmyrw"].map(c=>[..."aiueo"].map(v=>c+v)) // combine each consonant and vowel
  ))[m.indexOf(s)+1]                                 // return the next sound

```

## Test

```
var solution = s=>s>"yt"?"yo":s=="ya"?"yu":s=="wa"?"wo":(m=[].concat(...["",..."kstnhmyrw"].map(c=>[..."aiueo"].map(v=>c+v))),m[m.indexOf(s)+1])
```

```
<input type="text" id="input" value="mo" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 0 votes
## Perl 6, 96 bytes

```
{my @a=(" kstnhmyrw".comb X~ <a i u e o>).grep({!/[y|w][e|i]|wu/})>>.trim;@a[1+@a.first($_,:k)]}

```

# Answer
> 0 votes
# C, ~~138~~ 135 bytes

```
char*s="aiueokstnhmyrw";i,j;k(*v){j=strchr(s,*v>>8)-s;i=strchr(s,*v)-s;j=i<4?i++:j<4?j-~(2520%i&3):!++i;printf("%c%c",s[i],i<5?:s[j]);}

```

Wandbox

# Answer
> 0 votes
# Python 2, 107 bytes

```
L=[(x+y).lstrip()for x in' kstnhmyrw'for y in'aiueo'if x+y not in'yiyewiwuwe']
print L[L.index(input())+1]

```

Expects input enclosed in quotes, `'he'` for example

# Answer
> 0 votes
## Racket 151 bytes

```
(second(member s '(a i u e o ka ki ku ke ko sa si su se so ta ti tu te to na
ni nu ne no ha hi hu he ho ma mi mu me mo ya yu yo ra ri ru re ro wa wo)))

```

Ungolfed:

```
(define (f s)
  (second
   (member s
           '(a i u e o ka ki ku ke ko sa si su se so ta ti tu te to na ni nu ne
               no ha hi hu he ho ma mi mu me mo ya yu yo ra ri ru re ro wa wo))))

```

Testing:

```
(f 'a)
(f 'i)
(f 'o)
(f 'ke)
(f 'so)
(f 'ni)
(f 'ya)
(f 'yu)
(f 'wa)

```

Output:

```
'i
'u
'ka
'ko
'ta
'nu
'yu
'yo
'wo

```

There is an error message if 'wo is sent.

---
Tags: code-golf, natural-language
---


# Question
Title: Conjugate in the Spanish imperfect / Conjugue en el imperfecto de indicativo
Given an input of a Spanish verb in its infinitive form, output the verb conjugated in all 6 forms of the indicative imperfect.

To conjugate an infinitive in the imperfect, remove the infinitive ending (-ar, -er, -ir, and sometimes -ír) and add the imperfect endings listed below. There are three irregular verbs in the imperfect, also listed below.

```
Verb ending    Replace with...
--------------------------------------------------------
-ar            -aba, -abas, -aba, -ábamos, -abais, -aban
-er, -ir, -ír  -ía,  -ías,  -ía,  -íamos,  -íais,  -ían

```

```
Irreg. verb    Conjugations
--------------------------------------------------------
ser            era,  eras,  era,  éramos,  erais,  eran
ver            veía, veías, veía, veíamos, veíais, veían
ir             iba,  ibas,  iba,  íbamos,  ibais,  iban

```

For the purposes of this challenge, use capital letters instead of accented letters (á becomes A, é becomes E, and í becomes I). This is only because accented letters are 2 bytes in UTF-8, but they can be different in other encodings, and I'd rather not have to deal with any of that and stay within printable ASCII instead.

Infinitive verbs will always be three or more characters long with the sole exception of the verb *ir*, will never contain accented letters with the exception of verbs that end in -ír, and will always end in either -ar, -er, -ir, or -ír. Reflexive verbs do not need to be handled.

Output may be in either the form of a whitespace-/comma-separated string (so printing each conjugation to STDOUT on its own line is okay) or an array/list/etc.

Since this is , the shortest code in bytes wins.

Test cases:

```
In       Out
---------------------------------------------------------------
hablar   hablaba hablabas hablaba hablAbamos hablabais hablaban
comer    comIa comIas comIa comIamos comIais comIan
vivir    vivIa vivIas vivIa vivIamos vivIais vivIan
sonreIr  sonreIa sonreIas sonreIa sonreIamos sonreIais sonreIan
ser      era eras era Eramos erais eran
ver      veIa veIas veIa veIamos veIais veIan
ir       iba ibas iba Ibamos ibais iban

```

# Answer
> 6 votes
## Retina, ~~100~~ 82 bytes

```
\B[^a]r$
I
r$
b
^vI$
veI
^sI$
er
$
a
$
 $_s $_ $_mos $_is $_n
T`l`L`.(?=[^I]amos )

```

Try it online. Unfortunately, due to the use of `$_` it's not possible to modify the code to run all tests at once, so you'll have to copy in the individual verbs. I'm working on a new feature that will make this possible though.

### Explanation

```
\B[^a]r$
I

```

We start by turning all endings which aren't `ar` into `I`, provided the input isn't the irregular verb `ir`. That takes care of the `-er`, `-ir`, `-ír` conjugations, messes up the irregular verbs `ser` and `ver` (but shortens them in the process), and leaves only `ir` and `-ar` with a trailing `r`.

```
r$
b

```

If the word still ends in `r`, we replace that with a `b`. We've now covered all standard conjugations as well as the irregular verb `ir`.

```
^vI$
veI

```

This fixes the irregular verb `ver` which has been turned into `vI` in the first stage.

```
^sI$
er

```

This fixes the irregular verb `ser` which has been turned into `sI` in the first stage. Now we've modified all possible stems correctly. All that's left to do is append all the possible endings, and then fix the accent for the first person plural in some cases.

```
$
a

```

First we append an `a` to the stem, because that's always part of all endings.

```
$
 $_s $_ $_mos $_is $_n

```

This makes use of the rarely seen `$_` which inserts the entire string into the substitution (regardless of what was matched). This is actually very useful when duplicating strings, as are `$`` and `$'`, which are also quite underappreciated.

Before this stage, we've got the first person singular in the string. We now append the other conjugations, by matching the end of the string with `$` and building the other forms by appending the appropriate suffixes to the first person singular.

```
T`l`L`.(?=[^I]amos )

```

Finally, we fix the accent for the first person plural if applicable. This only needs to be done for a vowel, two characters in front of the `-amos` *unless* the character in between is `I`. So we match such a character and then use a transliteration stage to convert lower to upper case. This makes use of the new character classes `l` and `L` which I only added yesterday. They expand to `a-z` and `A-Z` respectively, so that new feature saves 4 bytes here.

# Answer
> 3 votes
# Python 3, ~~154~~ 232 bytes

```
M=input()
Q={'ser':'er','ver':'veI','ir':'ib'}.get(M)
H=[(Q if Q else M[:-2]+("ab"if M[-2:]=="ar"else"I"))+j for j in"a as a amos ais an".split(' ')]
if M[-2:]=="ar":H[3]=M[:-2]+"Abamos"
if Q in['er','ib']:H[3]=H[3].title()
print(H)

```

Fixed the missing capitals in irregular verbs.

---

### Ungolfed

```
M=input()
Q={'ser':'er','ver':'veI','ir':'ib'}.get(M)

H=[]
for j in "a as a amos ais an".split(' '):
    if Q:
        F = Q
    else:
        if M[-2:] == "ar":
            F = M[:-2] + "ab"
        else:
            F = M[:-2] + "I"
    H += [F + j]

if M[-2:] == "ar":
    H[3] = M[:-2] + "Abamos"

if Q in ['er', 'ib']:
    H[3] = H[3].title()

print(H)

```

# Answer
> 1 votes
# Milky Way 1.6.2, 281 bytes

```
'?{"ser"b_^"er";_}?{"ver"b_^"veI";_}?{"ir"b_^"ib";_}?{_:y2->CH=<1-&{~>;+<1-}^>;+<;_^""0}?{"ar"b_"ab";>+<0_}?{_"I";>+<_^}^;^"an ais amos a as a"" "\?{<y__<^}=3&{~<:>;>;+!^<1-}^?{'C=^"a"b_'C:y2->=^^<ΩG"Abamos"+!^^_}?{<"er"b_"Eramos"!^^_}?{<"ib"b_"Ibamos"!^^_}J:y1-;=<&{~<:>;>;+!^<1-}

```

Well *that* took awhile! Looks like I need to add some builtins, hehe...

---

### Usage

```
./mw <path-to-code> -i <input>

```

---

### Examples

```
$ ./mw test.mwg -i "hablar"
hablaba
hablabas
hablaba
hablAbamos
hablabais
hablaban

$ ./mw test.mwg -i "ver"
veIa
veIas
veIa
veIamos
veIais
veIan

```

# Answer
> 1 votes
# Ruby, ~~151~~ 149

Normally, I'll choose a newline over a semicolon where possible in the interests of readability, but as there are no semicolons, this is a one liner.

```
->n{%w{a as a amos ais an}.map{|z|['3r','veI','1b',n[0..-3]+(n[-2]==?a?'@b':?I)][("ser ver ir  "+n).index(n)/4].tr('31@',['eia','EIA'][z.size/4])+z}}

```

A feature is the use of placeholders `31@` for the accented vowels which depend on the `amos` endings. Thus the correct stem is formed, and then the placeholder is substituted for one of `eia` or `EIA` as appropriate

There a few uses of negative array indexes in here. Thus `n[-2]` refers to the second to last character of the input, and `n[0..-3]` refers to the input with the last 2 characters removed (the infinitive stem).

Ungolfed in test program

```
f=->n{
%w{a as a amos ais an}.map{|z|            #iterate through each verb ending
    ['3r','veI','1b',                     #array index 0,1,2 formats for irregular stems (note numbers 1 and 3 used as placeholders)
    n[0..-3]+(n[-2]==?a?'@b':?I)][        #array index 3 format for regular stems, AR->@b or ER/IR->I depending if A found at index -2 (@ used as placeholder)
    ("ser ver ir  "+n).index(n)/4]        #find index of input verb n in "ser ver ir  "+n, divide by 4 to obtain 0,1,2,3 above
    .tr('31@',['eia','EIA'][z.size/4])+   #if z is 4 characters long (AMOS) replace 3,1,@ with uppercase E,I,A. Otherwise with lowercase e,i,a
    z                                     #add the verb ending to the stem
  }
}

n=gets.chop
puts f[n]

```

# Answer
> 1 votes
# Lexurgy, 153 bytes

```
i:
ser=>era
ver=>veIa
ir=>iba
([]+)$1 {a,{e,i,I}} r=>$1 {ab,I} a
c:
([]+)$1=>$1 ` $1 s ` $1 ` $1 mos ` $1 is ` $1 n
j:
i=>I/` _ bam
e=>E/` _ ram

```

Ungolfed explained:

```
# turn the irregulars into their roots
irreg:
ser=>era
ver=>veIa
ir=>iba

# do the same for everything else
roots:
([]+)$1 {a,{e,i,I}} r=>$1 {ab,I} a

# tack on the same endings
conjugate:
([]+)$1=>$1 ` $1 s ` $1 ` $1 mos ` $1 is ` $1 n

# fix the irregulars
irreg2:
i=>I/` _ bam
e=>E/` _ ram

```

---
Tags: code-golf, string, natural-language
---


title: Cell Evolution Matrix

text:
# Question
Title: Cell Evolution Matrix
Your lab needed to simulate how a particular cell evolves over time in a 2D grid space. A sample 2D grid space below shows a single cell at the centre of the grid.

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

```

The cell evolution follows these rules:

1. '0' indicates no live cell
2. A positive number indicates a live cell. The number indicates its age.
3. A cell will grow from age 1 to 5 in each evolution
4. After age 5, a cell will die at the next evolution (resetting to '0')
5. If a cell has 4 or more neighbours (adjacent and diagonally), it will die due to over-crowding.
6. In each evolution, a live cell will spread to its neighbour (adjacent and diagonally) if there is no live cell there

# Rule change

Given an integer `n` in the input, which represents the size of the grid given, output the **next `n` evolution of cells**

Extra rules:

1. The first live cell is always in the center of the grid
2. `n` must be odd so the live cell is always centered
3. The first grid of the 1 in the center is not counted as an evolution

# Test case

Only 1 to save space in question

Input: 3

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

```

```
1 1 1
1 2 1
1 1 1

```

```
2 0 2
0 0 0
2 0 2

```

```
3 1 3
1 1 1
3 1 3

```

This is code-golf, so shortest bytes wins!

# Answer
> 2 votes
# APL(Dyalog Unicode), 62 bytes SBCS

```
{(0,⍳⍵){(6|{(+/∊8⍳⍤-4×5⊃⊢)×,⍵}⌺3 3×1+⊢)⍣⍺⊢⍵}¨⊂⍵ ⍵⍴1↑⍨-⌈2÷⍨⍵*2}

```

Try it on APLgolf!

Or 54 bytes as a full program with a questionable output format:

```
{(6|{(+/∊8⍳⍤-4×5⊃⊢)×,⍵}⌺3 3×1+⎕∘←)⍣⍵⊢⍵ ⍵⍴1↑⍨-⌈2÷⍨⍵*2}⎕

```

Try it online! Slightly adjusted to run on the version 17 on TIO.

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

This version uses the cumbersome output format mentioned in the comments.

```
n=>(v=[...Array(n)],z=~-n/2*~n,g=m=>~n--?[m.map(r=>r.join` `).join`
`,...g(m.map((r,y)=>r.map((v,x)=>[t=0,..."1235678"].map(d=>(m[y+~-(d/3)]||0)[x+d%3-1]&&t++)|v++?v%=t>3||6:+!!t)))]:[])(v.map(_=>v.map(_=>+!z++))).join`

`

```

Try it online!

Or **187 bytes** if a standard output is allowed (a list of matrices).

### Center cell of the matrix

Given the width \\$n\\$ of the matrix, we define:

$$z=\frac{(n-1)\times(-n-1)}{2}$$

Or as JS code: `z=~-n/2*~n`

We increment \\$z\\$ after each visited cell while walking through the matrix from left to right and top to bottom. The center cell is reached when \\$z=0\\$.

For instance, for \\$n=5\\$ we start with \\$z=-12\\$, leading to:

$$\begin{pmatrix}-12&-11&-10&-9&-8\\ -7&-6&-5&-4&-3\\ -2&-1&0&1&2\\ 3&4&5&6&7\\ 8&9&10&11&12\end{pmatrix}$$

This is -- I think -- shorter than keeping track of \\$(x,y)\\$ and doing the test on them.

# Answer
> 2 votes
# Python 3.8 (pre-release), 287 bytes

```
N=int(input())
K=range(N)
G=[[+(i==j==N//2)for j in K]for i in K]
F=lambda:print('\n'.join(' '.join(str(c)for c in r)for r in G)+'\n')
F()
for _ in K:G=[[-~G[i][j]%6*(0<sum(-1<I<N and-1<J<N and G[I][J]>0for J in[j-1,j,j+1]for I in[i-1,i,i+1])<5+5*(not G[i][j]))for j in K]for i in K];F()

```

Try it online!

This is the version with a nice, tidy output method.

## Explanation

Take integer as input (call it N) representing the size of the grid.

Make a variable for its range, to save bytes. (The range is used quite a few times.)

Set up the grid by placing 1 in the center (the row and column are N//2) and 0 in all other places.

Make a function to print the grid.

Print the grid.

Change the grid N times, by changing the element at i, j to `-~G[i][j]%6` (one plus the existing one, modulo 6: the modulo 6 ensures that 5 becomes 6%6 = 0) if there is at least one live element in its neighborhood (which includes itself; if no live elements are in the area, it cannot come alive) and at most 5 live elements if that element is itself live (this is the part which kills overcrowded elements), and 10 live elements if that element is dead (it doesn't matter how overcrowded the element is, because if there is at least one live element around it, which is not itself as it is dead, it comes alive regardless). If those conditions are not satisfied, set it to zero. Then print the grid at each iteration.

## "the first grid is not an evolution"

# Python 3.8 (pre-release), 270 bytes

```
N=int(input())
K=range(N)
G=[[+(i==j==N//2)for j in K]for i in K]
for _ in K:G=[[-~G[i][j]%6*(0<sum(-1<I<N and-1<J<N and G[I][J]>0for J in[j-1,j,j+1]for I in[i-1,i,i+1])<5+5*(not G[i][j]))for j in K]for i in K];print('\n'.join(' '.join(str(c)for c in r)for r in G)+'\n')

```

Try it online!

At present, I am not sure if the first grid is an evolution, but just in case, I have provided both versions. (The statement that the first grid is not an evolution conflicts with the test case output.)

# Answer
> 2 votes
# 05AB1E, ~~55~~ ~~54~~ 52 bytes

```
δ‚·<QPIƒD»,¶?0δ.ø¬0*šĆ2Fø€ü3}εε˜DÅsD>I>%Š_iOĀ*ëĀO5‹*

```

Formats by joining each row with a space-delimiter and then all lines with a newline-delimiter. The output can therefore be a bit wonky if it contains any multi-digit integers (for inputs \\$n\geq17\\$).
The `D»,¶?` could have been `=` (-4 bytes) without the strict output format, by just outputting the matrices as is (without popping).

Try it online or verify all test cases below 10.

**Explanation:**

Step 1: Using the input \\$n\\$, create an \\$n\times n\\$ matrix of \\$0\\$s with a \\$1\\$ in the center:

```
δ                   # Apply double-vectorized:
                    # (which implicitly converts the implicit input-integer to
                    # the range [1,input] first, used twice)
 ‚                  #  Pair them together
  ·                 # Double each inner integer
   <                # Decrease each by 1
    Q               # Check for each value if it's equal to the (implicit) input
     P              # Get the product of each inner pair

```

Try just step 1 online.

Step 2: Loop \\$n+1\\$ amount of times, and pretty-print the matrix at the start of each iteration:

```
Iƒ                  # Loop the input+1 amount of times:
  D                 #  Duplicate the current matrix
   »                #  Join each inner list by spaces,
                    #  and then each string by newlines
    ,               #  Pop and print it with trailing newline
     ¶?             #  Print an additional empty line

```

Try steps 1 & 2 online.

Step 3a: Surround the entire matrix with a ring of 0s:

```
   δ                #  Map over each row:
  0 .ø              #   Surround it with a leading/trailing 0
      ¬             #  Push the first row (without popping the matrix)
       0*           #  Convert all its values to 0
         š          #  Prepend this list to the matrix
          Ć         #  Enclose; append its first row

```

Step 3b: And then get all overlapping 3x3 blocks. Each of these 3x3 blocks will have the current value at the center, and its 8 neighbors around it.

```
  2F                #  Loop 2 times:
    ø               #   Zip/transpose; swapping rows/columns
     €              #   Map over each row:
      ü3            #    Create overlapping triplets of this row
   }                #  Close the loop

```

Try steps 1 & 3 online.

Step 4: Based on these 3x3 blocks, determine the next value for the cell:

```
εε                  #  Map over each inner 3x3 block:
  ˜                 #    Flatten it to a single list of 9 values
   D                #    Duplicate this list
    Ås              #    Pop and push the middle cell value
      D             #    Duplicate this middle value
       >            #    Increase it by 1
        I>%         #    Modulo the (input+1)
           Š        #    Triple-swap list,middle,middle+1 to middle+1,list,middle
            _i      #    If the middle cell is 0:
              O     #     Sum its neighbors together
               Ā    #     Check if this is not 0 (0 if 0; 1 otherwise)
                *   #     Multiply this by the middle+1
             ë      #    Else:
              Ā     #     Check for each value that it's NOT 0
               O    #     Sum to get the amount of filled cells, including itself
                5‹  #     Check if this is smaller than 5,
                    #     so there are not 4 or more filled neighbors
                  * #     Multiply this by the middle+1

```

# Answer
> 1 votes
# , 62 bytes

```
<@>:_&(](-~&*+(5>])*[+0<[)[:+/(>,{;~i:1)|.!.0*@])[:*/~<.@-:=i.

```

Try it online!

# Answer
> 1 votes
# Python 2, 214 bytes

```
E=enumerate
n=input()
g=eval(`[[0]*n]*n`)
g[n/2][n/2]=1
exec'print("%d "*n+"\\n")*n%tuple(sum(g,[]));g=[[(0<sum(e>0for q in g[y+y%~y:y+2]for e in q[x+x%~x:x+2])<5+4*0**v)*-~v%6for x,v in E(r)]for y,r in E(g)];'*-~n
```

Attempt This Online!

Because of the fixed output format switching to Python 3 could actually save a few bytes here: ATO

The most interesting part of this program is the following expression:

```
(0<sum(e>0for q in g[y+y%~y:y+2]for e in q[x+x%~x:x+2])<5+4*0**v)*-~v%6

```

Given the previous state in `g`, the indices of a cell `y, x` and the value of that cell `v`, this generates the next state of that cell. To select three rows of `g` centered on `y` the slice `g[y-1:y+2]`. This works if `y` is not on the boundaries of `g` or if `y == n-1`. For `y == 0` the slice would start at the end of `g`, which is not what we want. To adjust for that we can use `y-(y>0)` instead, but `y+y%~y` is a shorter expression that achieves the same.

In conclusion `[e for q in g[y+y%~y:y+2]for e in q[x+x%~x:x+2]]` lists all values in a truncated 3x3 block centered on `y, x`. We then count the non-zero values and check for overpopulation if `v>0`.

# Answer
> 0 votes
# Charcoal, 74 bytes

```
Ｎθ≔ＥθＥθ⁰η§≔§η⊘θ⊘θ¹Ｆ⊕θ«Ｅη⪫κωＦθＦθ«Ｊλκ§≔§ηκλ∧›5ＫＫ⎇ΣＫＫ∧›⁴ＬΦＫＭΣμ⊕ＫＫ‹0⌈ＫＭ»ＵＥ¹Ｄ⎚Ｄ

```

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

```
Ｎθ

```

Input `n`.

```
≔ＥθＥθ⁰η§≔§η⊘θ⊘θ¹

```

Create an `n×n` matrix whose centre element is `1`.

```
Ｆ⊕θ«

```

Loop `n+1` times, because we output the position first.

```
Ｅη⪫κω

```

Output the current position to the canvas.

```
ＦθＦθ«Ｊλκ

```

Loop over each cell.

```
§≔§ηκλ∧›5ＫＫ⎇ΣＫＫ∧›⁴ＬΦＫＭΣμ⊕ＫＫ‹0⌈ＫＭ

```

If the current cell is less than `5`, then if it is a `0` then set it to `1` if it has any neighbours, otherwise increment it if it has fewer than `4` neighbours. Otherwise, set it to `0`.

```
»ＵＥ¹Ｄ⎚Ｄ

```

Output the canvas neatly. (`Ｄ⎚` would work but the output would be much less readable.)

---
Tags: code-golf, ascii-art, matrix, cellular-automata
---


title: Recursive palindromes

text:
# Question
Title: Recursive palindromes
A palindrome is a word which is spelled the same backwards and forwards. For example, "racecar" is a palindrome as is "redder". A double palindrome is a palindrome whose halves are also palindromes. For example, "abbabba" is a double palindrome, as the half "abba" is also a palindrome. Similarily, "abaababaaba" is a triple palindrome and so on. Your task is to take a string and return the degree of palindromess. If the string is not a palindrome, return 0.

In order to avoid ambiguity in some edge-cases, the first two letters are guranteed to be different, and the input has at least three letters.

The input string consists entirely of lowercase letters.

# Examples

```
"notapalindrome"
-> 0

"madam"
-> 1

"xyxxxyx"
-> 1

"racecarracecar"
-> 2

"ababababa"
-> 3

"abbaabbaabbaabba"
-> 3

```

# Answer
> 7 votes
# Python 2, 41 bytes

```
f=lambda s:s==s[::-1]and-~f(s[len(s)/2:])

```

Try it online!

Simple recursive function. If the string is not a palindrome, returns false instead of 0 (which I think is allowed for Python).

# Answer
> 4 votes
# Husk, 9 bytes

```
←VS≠↔¡o←½

```

Try it online!

Longer recursion: `?K0ö→₀←½S≠↔`

# Answer
> 4 votes
# Vyxal, 8 bytes

```
‡Ḃ=‡½hŀL

```

Try it Online!

```
‡  ‡  ŀ  # Collect until false
 Ḃ=      # Is a palindrome
    ½h   # Get first half (rounded up)

       L # Get length

```

# Answer
> 3 votes
# BQN, 21 bytes

```
{≡⌽?1+↑˜⌈÷⟜2≠;0}

```

Anonymous function that takes a string and returns an integer. Run it online!

### Explanation

```
{≡⌽?1+↑˜⌈÷⟜2≠;0}
{                     }  Define a block function
      ?                  If:
   ⌽                      The argument, reversed
 ≡                         is the same as the argument
                         Then (the argument is a palindrome):
                  ≠       Length of the argument
              ÷⟜2          Divided by 2
             ⌈             Rounded up
          ↑˜              Take that many characters from the argument
                          Recurse
       1+                  Add 1 to the result of the recursive call
                    ;    Else (the argument is not a palindrome):
                     0     0

```

# Answer
> 2 votes
# , 61 bytes

Or **\>=4.1, 54 bytes** by replacing the word `function` with a `\`.

```
f=function(x)"if"(any(x-rev(x)),0,1+f(x[1:((sum(x|1)+1)/2)]))

```

Try it online!

I hate and am ashamed of the part taking first half of the input, but couldn't think of something better...

# Answer
> 2 votes
# Java 8, 101 bytes

```
s->{int r=0;for(;s.contains(new StringBuffer(s).reverse());r++)s=s.substring(s.length()/2);return r;}

```

Try it online.

**Explanation:**

```
s->{          // Method with String parameter and integer return-type
  int r=0;    //  Result-integer, starting at 0
  for(;s.contains(new StringBuffer(s).reverse())
              //  Loop as long as the String is a palindrome:
     ;r++)    //    After every iteration: Increase the result by 1
    s=        //   Replace the String with:
      s.substring(s.length()/2);
              //    Its second halve; substring at index-range [length//2,length)
  return r;}  //  After the loop, return the result

```

# Answer
> 2 votes
# Jelly, 10 bytes

```
ŒHḢ$ŒḂÐ¿L’

```

A monadic Link accepting a list of characters that yields an integer.

**Try it online!**

So many 2 byte instructions:(

### How?

```
ŒHḢ$ŒḂÐ¿L’ - Link: list of characters, S
      Ð¿   - collect up input values while...
    ŒḂ     - ...condition: is a palindrome?
   $       - ...next input: last two links as a monad:
ŒH         -      split into halves (first 1 longer if odd length)
  Ḣ        -      head
        L  - length
         ’ - decrement

```

# Answer
> 2 votes
# Brachylog, ~~10~~ 9 bytes

*-1 byte thanks to a clever observation from Unrelated String*

```
↔?ḍt↰<|∧0

```

Try it online!

Alternate 9-byte solution: `↔?ḍt↰<.∨0` (Try it online!)

### Explanation

```
↔?ḍt↰<|∧0
↔          The input reversed
 ?         is the same as the input
  ḍ        Split into two halves
   t       Take the second half (which is the longer one if they aren't the same)
    ↰      Recurse
     <     First integer greater than the result of the recursive call
      |    If the preceding part failed (because the input isn't a palindrome):
       ∧   Break unification with the input
        0  and set the output to 0

```

# Answer
> 1 votes
# Haskell, 51 bytes

```
v s|s/=reverse s=0|0<1=1+v(take(div(1+length s)2)s)

```

Try it Online!

# Answer
> 1 votes
# Retina 0.8.2, 36 bytes

```
+m`^((.)+.?)(?<-2>\2)+(?(2)^)$
$1¶
¶

```

Try it online! Link includes test cases. Accepts a double letter as a palindrome but not a single letter. Explanation:

```
+`

```

Repeat until no more matches can be made:

```
m`^((.)+.?)

```

Match the first half (including the middle character where relevant) of the palindrome, ...

```
(?<-2>\2)+(?(2)^)$

```

... then match the characters captured by capture group 2 in reverse, popping as we go, until there are none left, and...

```
$1¶

```

... replace the second half of the palindrome with a newline.

Count the number of newlines.

# Answer
> 1 votes
# Charcoal, 20 bytes

```
Ｗ⁼θ⮌θ«≔∕⁺θψ²θ⊞υω»ＩＬυ

```

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

```
Ｗ⁼θ⮌θ«

```

Repeat while the word equals its reverse...

```
≔∕⁺θψ²θ

```

... append a character, then halve its length, so that odd lengths get rounded up, and...

```
⊞υω

```

... keep track of how many times the loop executed.

```
»ＩＬυ

```

Output the final number of loops.

# Answer
> 1 votes
# JavaScript (Node.js), 57 bytes

```
f=n=>n==[...n].reverse().join``&&f(n.slice(n.length/2))+1

```

Try it online!

A port of Surculose Sputum's Python answer (I couldn't find any other shorter way). Replace `&&` with `?` and add `:0` at the end of the program to make it return 0 in cases where it currently returns `false`, for an extra byte.

# Answer
> 1 votes
# 05AB1E (legacy), 10 bytes

```
[ÐRÊ#2äн}N

```

Try it online or verify all test cases.

**Explanation:**

```
[      # Loop indefinitely:
 Ð     #  Triplicate the current string
       #  (which will be the implicit input in the first iteration)
  R    #  Reverse the top copy
   Ê   #  Pop the top two, and check whether they're NOT equal
    #  #  If this is truthy (it's not a palindrome): stop the infinite loop
  2ä   #  Split the string into two equal-sized halves
       #  (if the length is odd, the first string is one char longer)
    н  #  Pop and keep just the first item
}N     # After the infinite loop: push the (last) 0-based loop-index
       # (after which it is output implicitly as result)

```

Uses the legacy version, because pushing `N` outside of a loop will result in `0` in the new version of 05AB1E.

---
Tags: code-golf, palindrome
---