title: Biggest Irreducible Cat

text:
# Question
Title: Biggest Irreducible Cat
I guess you could call this the next challenge in the "Irreducible series".

# Challenge

Create a cat subject to the constraint that it is *irreducible*.

A cat program `C` is considered *irreducible* if there does not exist a cat (in the same programming language as `C`) that can be constructed by removing characters from `C`.

For example

```
console.log(prompt.call());

```

can have the the bracketed characters removed

```
console.log(prompt[.call]())[;] ->
console.log(prompt())

```

And it will still be a cat. Therefore `console.log(prompt.call());` is not irreducible.

The winner will be the program with the longest source code.

# Extras

A big shout out to @acupoftea for showing that, for any given language, there is actually a maximum score. Otherwise you could construct an infinite set that would break Higman's lemma!.

# Answer
> 5 votes
# Jelly `u`, \\$4\times10^{41}\\$ bytes

```
“...”WẈbØ%ỌV

```

Except instead of `...` its \\$133390687877217192365177139021057049493695\\$  characters

More specifically, a score of \\$400172063631651577095531417063171148481103\\$

## How it works

The standard cat program in Jelly is

```
ƈȮøL¿

```

Try it online!

If we convert each of these characters to their Unicode code point we get

```
[392, 558, 248, 76, 191]

```

Treat this a base \\$4294967296 = 2^{32}\\$ number and convert it back to decimal to get \\$133390687877217192365177139021057049493695\\$

The above program has a string consisting of \\$133390687877217192365177139021057049493695\\$  characters. We then take its length, convert it to base \\$4294967296\\$, convert back to characters and run as Jelly code.

By forcing Jelly to encode the source as UTF-8 rather than using the Jelly code page, multi byte characters are counted as multiple bytes rather than just 1.

This is 100% irreducible. The cat program it encodes is optimal for Jelly, so there's no way to remove any of the  characters and still create a cat program, and all of the other characters are necessary to correctly convert the string to a program and execute it. More specifically:

* Removing either  or  will cause syntax errors
* Removing the `W` will cause  to return a list of lists of \\$1\\$s rather than the code points in base \\$4294967296\\$
* Removing the  will mean the program won't ever convert the string to the code points in base \\$4294967296\\$
* Removing any of `bØ%` will prevent the base conversion happening
* Removing  or `V` will stop the program from converting to characters and running the program

Furthermore, I believe this is the longest you can get using the method of "long string's length in a high base" in Jelly. The base being used must meet the following criteria:

* The number isn't "constructed" via commands to be larger, as these commands can be removed and the long string adjusted for the lower base
* The number doesn't have digits in it, as characters can be removed to just isolate the lowest digit and the long string can then be adjusted to match this new base

`Ø%` is the largest constant Jelly has which meets these criteria at \\$2^{32}\\$, so, as a higher base leads to a longer string, an answer in Jelly cannot beat this one.

# Answer
> 5 votes
# C (gcc) with `-trigraphs`, ~~327~~ ~~357~~ 413 bytes

Some creative uses of the language:

* Very important `typedef`s for pointers to types
* Constants that are then decremented using the super-experimental tadpole operator
* Dynamic allocation of the character buffer, for reasons
* Use of `fread` to read in a character
* Use of `fprintf` to print a character as a fixed single-byte string
* The essential use of trigraphs in case you are typing on a keyboard from the 1800s
* Using `iso646.h` because the ISO said so :-)

```
??=include <stdio.h>
??=include <stdlib.h>
??=include <iso646.h>
typedef unsigned*v;struct g??<v c;??>;typedef struct g*h;h c;main()??<c=calloc(sizeof(struct g),-??-EXIT_SUCCESS);c->c=calloc(sizeof(unsigned),-??-EXIT_SUCCESS);do??<fread(c->c,-??-EXIT_SUCCESS,-??-EXIT_SUCCESS,stdin);if(feof(stdin)==EXIT_FAILURE xor EXIT_FAILURE)fprintf(stdout,"%.1s",c->c);??>while(feof(stdin)==EXIT_FAILURE xor EXIT_FAILURE);??>

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, ~~11~~ ~~12~~ 15 bytes

```
\A`[^\\](?<=\\)

```

Try it online! Explanation: The `\` suppresses the trailing newline, without which the program fails to be a cat program. The `A`` is required to identify the stage as an AntiGrep rather than a Match stage (which would just output the count of something). For the output to match the input, the pattern must fail to match; this is done by matching any non-`\` and then ensuring that the character was actually a `\`; this character was chosen because it needs to be quoted, making the pattern longer.

I also looked into the other stage types Retina has to see what the best I could do for them was.

* Deduplicate - best I could do was `\D`()` (5 bytes) deduplicate all empty strings
* Grep - best I could do was `\G`` (3 bytes) keep everything
* Match - best I could do was `\!`(.|[^.])+` (12 bytes) match everything
* Sort - best I could do was `\O$`` or `\O`$` or similar (4 bytes) sort in original order or sort nothing
* Replace - best I could do was a single newline (1 byte) replace nothing with nothing - this means that all Retina cat programs that contain a newline can be reduced to 1 byte
* Split - best I could do was `\S`\n` (5 bytes) split on newlines and join with newlines
* Transliteration - best I could do was `\T`` (3 bytes) translate nothing

# Answer
> 3 votes
# JavaScript (ES7), 10346554967051525 bytes

The string `-~[]` is actually repeated \\$2586638741762875\\$ times.

```
Infinity=>eval((-~[]-~[]-~[]-~[]…-~[])**20+'')

```

You can Try this version online!, where all but the last 5 `-~[]` have been replaced with a hard-coded integer.

### How?

The characters in the name of the input variable `Infinity` are not used anywhere else, so we can't simplify the code by shortening it. The only way to get its content is that the expression in `eval()` evaluates to the string `"Infinity"`.

We do it by computing:

$$2586638741762875^{20}$$

where \\$2586638741762875\\$:

We can probably make it longer by using a more convoluted expression. For instance, I think it should still be irreducible if we use `-~RegExp` instead of `-~[]`.

# Answer
> 2 votes
# Japt, 125 bytes

I'm very far from sure that this is valid but I am somewhat sure it can be beaten!

```
Ov"11111111111111111111111111111111111111111111111111111"n2 a"11111111111111111111111111111111111111111111110110001"n2  d  qR

```

Try it

# Answer
> 0 votes
# Python 3, <sup>~~8+(10\*(85+(10\*749535276648396287585636512750330369605831039396714237143337)))~~</sup> infinite bytes

```
exec("\U0000006e\U0000003d\U00000030\U0000003b\U00000063\U0000003d\U00000022\U00000030\U00000030\U00000030\U00000030\U0000002e\U0000002e\U0000002e\U0000002e\U0000002e\U00000022\U0000000a\U00000066\U0000006f\U00000072\U00000020\U0000005f\U00000020\U00000069\U0000006e\U00000020\U00000063\U0000003a\U0000006e\U0000002b\U0000003d\U00000031\U0000000a\U00000073\U0000003d\U00000062\U00000079\U00000074\U00000065\U00000061\U00000072\U00000072\U00000061\U00000079\U00000028\U00000029\U0000000a\U00000077\U00000068\U00000069\U0000006c\U00000065\U00000020\U0000006e\U0000003a\U00000073\U0000002e\U00000061\U00000070\U00000070\U00000065\U0000006e\U00000064\U00000028\U0000006e\U00000026\U00000032\U00000035\U00000035\U00000029\U0000003b\U0000006e\U0000003e\U0000003e\U0000003d\U00000038\U0000000a\U00000065\U00000078\U00000065\U00000063\U00000028\U00000073\U0000002e\U00000064\U00000065\U00000063\U0000006f\U00000064\U00000065\U00000028\U00000029\U00000029")

```

The `exec("")` adds 8 characters, and unicode-escapes multiply the count by 10.

Decoded:

```
n=0;c="\U00000030\U00000030\U00000030\U00000030....."
for _ in c:n+=1
s=bytearray()
while n:s.append(n&255);n>>=8
exec(s.decode())

```

This decoding routine adds the 85 characters.

The string inside `c` is the actual code, encoded in unary, with a unicode-escaped `0` character per unary digit.

This is too large to fit in the observable universe (approximately $$7.5 \times 10 ^ {60}$$ characters long), hence no TIO link.

The unary is then decoded and executed, to get a `cat` program:

```
while True:print(input())

```

I'm pretty sure you could recursively repeat these steps *ad infinitum* and it would still be irreducible (so I win by default), but I thought I'd keep my answer as an example finite.

---
Tags: code-bowling
---


# Question
Title: Output the International Phonetic Alphabet
The International Phonetic Alphabet is a system of phonetic notation intended to be able to accurately represent every sound used in spoken language.

The alphabet contains 29 vowel letters `iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶäɑɒ` and 81 consonant letters, although I missed three (`ɦǀǂ`) when I first posted this challenge, so you only need to consider the following 78: `mɱnɳɲŋɴpbtdʈɖcɟkɡqɢʡʔszʃʒʂʐɕʑɸβfvθðçʝxɣχʁħʕhʋɹɻjɰⱱɾɽʙrʀʜʢɬɮlɭʎʟɺǃʘǁɓɗᶑʄɠʛɧɥʍwɫ` and . We'll be ignoring the various diacritics in use.

Your job is to output those characters exactly once each, *not* including the three letters I missed, and output no other non-whitespace characters. Since the IPA does not have an official ordering, you may output these characters in *any* order so if you find an order that permits a shorter approach feel free to use that.

You may output as much or as little whitespace as you want. The output of your program does *not* need to be constant, as long as the output always meets the specification above (so the order may vary, as may the amount and location of whitespace).

For the sake of convenience, here's a sorted list of all the characters and their unicode codepoints:

```
U+0061 LATIN SMALL LETTER A:    a
U+0062 LATIN SMALL LETTER B:    b
U+0063 LATIN SMALL LETTER C:    c
U+0064 LATIN SMALL LETTER D:    d
U+0065 LATIN SMALL LETTER E:    e
U+0066 LATIN SMALL LETTER F:    f
U+0068 LATIN SMALL LETTER H:    h
U+0069 LATIN SMALL LETTER I:    i
U+006a LATIN SMALL LETTER J:    j
U+006b LATIN SMALL LETTER K:    k
U+006c LATIN SMALL LETTER L:    l
U+006d LATIN SMALL LETTER M:    m
U+006e LATIN SMALL LETTER N:    n
U+006f LATIN SMALL LETTER O:    o
U+0070 LATIN SMALL LETTER P:    p
U+0071 LATIN SMALL LETTER Q:    q
U+0072 LATIN SMALL LETTER R:    r
U+0073 LATIN SMALL LETTER S:    s
U+0074 LATIN SMALL LETTER T:    t
U+0075 LATIN SMALL LETTER U:    u
U+0076 LATIN SMALL LETTER V:    v
U+0077 LATIN SMALL LETTER W:    w
U+0078 LATIN SMALL LETTER X:    x
U+0079 LATIN SMALL LETTER Y:    y
U+007a LATIN SMALL LETTER Z:    z
U+00e4 LATIN SMALL LETTER A WITH DIAERESIS: ä
U+00e6 LATIN SMALL LETTER AE:   æ
U+00e7 LATIN SMALL LETTER C WITH CEDILLA:   ç
U+00f0 LATIN SMALL LETTER ETH:  ð
U+00f8 LATIN SMALL LETTER O WITH STROKE:    ø
U+0127 LATIN SMALL LETTER H WITH STROKE:    ħ
U+014b LATIN SMALL LETTER ENG:  ŋ
U+0153 LATIN SMALL LIGATURE OE: œ
U+01c1 LATIN LETTER LATERAL CLICK:  ǁ
U+01c3 LATIN LETTER RETROFLEX CLICK:    ǃ
U+0250 LATIN SMALL LETTER TURNED A: ɐ
U+0251 LATIN SMALL LETTER ALPHA:    ɑ
U+0252 LATIN SMALL LETTER TURNED ALPHA: ɒ
U+0253 LATIN SMALL LETTER B WITH HOOK:  ɓ
U+0254 LATIN SMALL LETTER OPEN O:   ɔ
U+0255 LATIN SMALL LETTER C WITH CURL:  ɕ
U+0256 LATIN SMALL LETTER D WITH TAIL:  ɖ
U+0257 LATIN SMALL LETTER D WITH HOOK:  ɗ
U+0258 LATIN SMALL LETTER REVERSED E:   ɘ
U+0259 LATIN SMALL LETTER SCHWA:    ə
U+025b LATIN SMALL LETTER OPEN E:   ɛ
U+025c LATIN SMALL LETTER REVERSED OPEN E:  ɜ
U+025e LATIN SMALL LETTER CLOSED REVERSED OPEN E:   ɞ
U+025f LATIN SMALL LETTER DOTLESS J WITH STROKE:    ɟ
U+0260 LATIN SMALL LETTER G WITH HOOK:  ɠ
U+0261 LATIN SMALL LETTER SCRIPT G: ɡ
U+0262 LATIN LETTER SMALL CAPITAL G:    ɢ
U+0263 LATIN SMALL LETTER GAMMA:    ɣ
U+0264 LATIN SMALL LETTER RAMS HORN:    ɤ
U+0265 LATIN SMALL LETTER TURNED H: ɥ
U+0267 LATIN SMALL LETTER HENG WITH HOOK:   ɧ
U+0268 LATIN SMALL LETTER I WITH STROKE:    ɨ
U+026a LATIN LETTER SMALL CAPITAL I:    ɪ
U+026b LATIN SMALL LETTER L WITH MIDDLE TILDE:  ɫ
U+026c LATIN SMALL LETTER L WITH BELT:  ɬ
U+026d LATIN SMALL LETTER L WITH RETROFLEX HOOK:    ɭ
U+026e LATIN SMALL LETTER LEZH: ɮ
U+026f LATIN SMALL LETTER TURNED M: ɯ
U+0270 LATIN SMALL LETTER TURNED M WITH LONG LEG:   ɰ
U+0271 LATIN SMALL LETTER M WITH HOOK:  ɱ
U+0272 LATIN SMALL LETTER N WITH LEFT HOOK: ɲ
U+0273 LATIN SMALL LETTER N WITH RETROFLEX HOOK:    ɳ
U+0274 LATIN LETTER SMALL CAPITAL N:    ɴ
U+0275 LATIN SMALL LETTER BARRED O: ɵ
U+0276 LATIN LETTER SMALL CAPITAL OE:   ɶ
U+0278 LATIN SMALL LETTER PHI:  ɸ
U+0279 LATIN SMALL LETTER TURNED R: ɹ
U+027a LATIN SMALL LETTER TURNED R WITH LONG LEG:   ɺ
U+027b LATIN SMALL LETTER TURNED R WITH HOOK:   ɻ
U+027d LATIN SMALL LETTER R WITH TAIL:  ɽ
U+027e LATIN SMALL LETTER R WITH FISHHOOK:  ɾ
U+0280 LATIN LETTER SMALL CAPITAL R:    ʀ
U+0281 LATIN LETTER SMALL CAPITAL INVERTED R:   ʁ
U+0282 LATIN SMALL LETTER S WITH HOOK:  ʂ
U+0283 LATIN SMALL LETTER ESH:  ʃ
U+0284 LATIN SMALL LETTER DOTLESS J WITH STROKE AND HOOK:   ʄ
U+0288 LATIN SMALL LETTER T WITH RETROFLEX HOOK:    ʈ
U+0289 LATIN SMALL LETTER U BAR:    ʉ
U+028a LATIN SMALL LETTER UPSILON:  ʊ
U+028b LATIN SMALL LETTER V WITH HOOK:  ʋ
U+028c LATIN SMALL LETTER TURNED V: ʌ
U+028d LATIN SMALL LETTER TURNED W: ʍ
U+028e LATIN SMALL LETTER TURNED Y: ʎ
U+028f LATIN LETTER SMALL CAPITAL Y:    ʏ
U+0290 LATIN SMALL LETTER Z WITH RETROFLEX HOOK:    ʐ
U+0291 LATIN SMALL LETTER Z WITH CURL:  ʑ
U+0292 LATIN SMALL LETTER EZH:  ʒ
U+0294 LATIN LETTER GLOTTAL STOP:   ʔ
U+0295 LATIN LETTER PHARYNGEAL VOICED FRICATIVE:    ʕ
U+0298 LATIN LETTER BILABIAL CLICK: ʘ
U+0299 LATIN LETTER SMALL CAPITAL B:    ʙ
U+029b LATIN LETTER SMALL CAPITAL G WITH HOOK:  ʛ
U+029c LATIN LETTER SMALL CAPITAL H:    ʜ
U+029d LATIN SMALL LETTER J WITH CROSSED-TAIL:  ʝ
U+029f LATIN LETTER SMALL CAPITAL L:    ʟ
U+02a1 LATIN LETTER GLOTTAL STOP WITH STROKE:   ʡ
U+02a2 LATIN LETTER REVERSED GLOTTAL STOP WITH STROKE:  ʢ
U+03b2 GREEK SMALL LETTER BETA: β
U+03b8 GREEK SMALL LETTER THETA:    θ
U+03c7 GREEK SMALL LETTER CHI:  χ
U+1d91 LATIN SMALL LETTER D WITH HOOK AND TAIL: ᶑ
U+2c71 LATIN SMALL LETTER V WITH RIGHT HOOK:    ⱱ

```

This is , so golf your code!

# Answer
> 6 votes
# JavaScript (Node.js),  ~~163 161 156~~  154 bytes

```
_=>(c=96,i=20,g=n=>n?String.fromCharCode(c+=n&1n?1:1-~[...'10'+2e7,139,,108,6,34,45,6,7,,104][i--])+g(n/2n):'βθχᶑⱱ')(0x26affdebbffd7f5ff009ffffbfn)

```

Try it online!

### How?

The characters are ordered from lowest to highest code point.

Each **1** in the BigInt bit mask `0x26affdebbffd7f5ff009ffffbfn` means that the code point **c** of the next character immediately follows the previous one. Each **0** means that the code point difference must be picked from a lookup array instead, which happens for the first time between `f` and `h`.

```
111010111111111000000001001111111111111111110111111
ɡɠɟɞɜɛəɘɗɖɕɔɓɒɑɐǃǁœŋħøðçæäzyxwvutsrqponmlkjihfedcba

100110101011111111110111101011101111111111110101111
ʢʡʟʝʜʛʙʘʕʔʒʑʐʏʎʍʌʋʊʉʈʄʃʂʁʀɾɽɻɺɹɸɶɵɴɳɲɱɰɯɮɭɬɫɪɨɧɥɤɣɢ

```

We add an offset of **+2** to each value in the lookup array, including undefined entries.

The values are stored in reverse order to allow the compression trick `[...'10'+2e7]` for the last 10 entries, which expands to:

```
['1','0','2','0','0','0','0','0','0','0']

```

Because the code point differences for the last 5 characters `βθχᶑⱱ` are significantly larger, it's more beneficial to just hard-code them.

# Answer
> 6 votes
# International Phonetic Esoteric Language, 110 bytes

Felt my esolang was appropriate for this.

Naïve approach. Pushes the characters as a string onto the stack, then prints with a newline:

```
"mɱnɳɲŋɴpbtdʈɖcɟkɡqɢʡʔszʃʒʂʐɕʑɸβfvθðçʝxɣχʁħʕhʋɹɻjɰⱱɾɽʙrʀʜʢɬɮlɭʎʟɺǃʘǁɓɗᶑʄɠʛɧɥʍwɫiyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶäɑɒ"o

```

Less naïve approach involving loops, **239 bytes**.

```
{3F}{2P}ɑe{2V}əɐʌɔ|i|eχu|i|e1søɒ"äæçðøħŋœǁǃ"{HW}{GG}ɑe{GQ}əe{GT}əe{HJ}əe{HO}əe{HR}əɞɞɞɞɐʌɔ|j|eχu|j|e1søɒ{IQ}{I0}ɑe{IB}əe{IE}əe{IF}əe{II}əe{IM}əe{IO}əɞɞɞɞɞɐʌɔ|h|eχu|h|e1søɒ"βθχᶑⱱ"o

```

# Answer
> 5 votes
# Charcoal, ~~82~~ ~~71~~ ~~68~~ ~~66~~ 62 bytes

```
⁻βg⭆⪪”)¶←@8⊘Φ@◧%↘Z⪪ξρ”³℅Ｉι⭆⌕Ａ”)∧←₂⁰Y⟧Ｇψ⊟∧⬤º”1℅⁺⁵⁹²ι”yβθχᶑⱱ

```

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

```
⁻βg

```

Output all of the lowercase letters except `g`.

```
⭆⪪”)¶←@8⊘Φ@◧%↘Z⪪ξρ”³℅Ｉι

```

Split the compressed string `228230231240248295331339449451` into 3-digit numbers and convert the code points into characters.

```
⭆⌕Ａ”)∧←₂⁰Y⟧Ｇψ⊟∧⬤º”1℅⁺⁵⁹²ι

```

Add 592 to the indices of all the `1`s in the compressed string `11111111110110111111110110111111111111101111011011111000111111111110110011011101011` and convert the code points to characters.

```
”yβθχᶑⱱ

```

Output 3 literal Greek letters and two literal characters. The Greek letters are in Charcoal's code page so they only cost 1 byte, but they have to be quoted by the `”y` to avoid being interpreted as Charcoal variable names. The final characters cost 3 bytes each.

# Answer
> 4 votes
# 05AB1E, 63 bytes

Outputs the non-ascii characters in ascending order first, then the lowercase alphabet (without `g`).

```
•2£cÈ‹Jd$…•Ƶfв•¤4Àǝ„Æ43†ÂÄт4H·âeš¬•5вƵ¬6 15ŽPäŽEï)˜.¥ƵƵ+çJA'gK«

```

Try it online!

**Commented**:

`•2£c ... ŽEï)˜` encodes the deltas using a mix of integer and integer list compression.

```
...              # compressed deltas
   .¥            # undelta
     ƵƵ+         # add 228 (ä)
        ç        # convert to characters
         J       # join to a single string
          A      # push the lowercase alphabet
           'gK   # without 'g'
              «  # concatenate both strings
                 # implicit output

```

# Answer
> 4 votes
# JavaScript, ~~184~~ 183 bytes

*-1 byte thanks to @Neil*

```
_=>"a6h19äæ2ðøħŋœǁǃɐ10ɛ2ɞ8ɧ2ɪ13ɸ4ɽ2ʀ5ʈ11ʔ2ʘ2ʛ3ʟʡ2βθχᶑⱱ".replace(/.(\d+)/g,(c,n)=>[...Array(+n)].map(_=>String.fromCharCode(a++),a=c.charCodeAt()).join``)

```

Try it online!

# Answer
> 3 votes
# Python 3, 131 bytes

```
a=0
n="\x01"
for c in f"a\x01\x01\x01\x01\x01\x02{n*18}j\x02\x01 \x08/$\x08n\x02\x8d{n*9}\x02\x01\x02{n*7}\x02\x01\x02{n*12}\x02\x01\x01\x01\x02\x01\x02\x01\x01\x01\x01\x04{n*10}\x02\x01\x03\x01\x02\x01\x01\x02\x02\x01Đ\x06\x0f\u19ca\u0ee0":a+=ord(c);print(chr(a))

```

The string's characters have been encoded here for readability, but they are raw (1 byte each for all except the unicode) on TIO.

Try it online!

Simple idea: we can encode the characters as a set of deltas with some hand rolled run length encoding. I tried compression but the overhead is just too large.

We abuse the allowance for whitespace by printing each character on a separate line.

---

## Python 3.8 (pre-release), 152 bytes

```
for c,d in zip("ahäæðøħŋœǁǃɐɛɞɧɪɸɽʀʈʔʘʛʟʡβθχᶑⱱ",b"\x06\x13\x01\x02\x01\x01\x01\x01\x01\x01\x01\n\x02\x08\x02\n\x04\x02\x05\x0b\x02\x02\x03\x01\x02\x01\x01\x01\x01\x01"):print(*map(chr,range(k:=ord(c),k+d)))

```

Try it online!

# Answer
> 3 votes
# MATLAB, 62 chars, 95 bytes (UTF-8)

```
setxor([97:122,'äæçðøħŋœǁǃβθχᶑⱱ',592:674],'gɷɿɼɦɩɚɝʚʞʠʓʖʗʅʆʇ')

```

Outputs char array.
...or if we want lowest bytecount, not charcount:

## MATLAB, 71 chars, 88 bytes (UTF-8)

```
setxor([97:122,'äæçðøħŋœǁǃβθχᶑⱱ',592:674],['g',550+'47@CQVY_`ampqtxz'])

```

# Answer
> 2 votes
# Jelly,  ~~59~~  58 bytes

```
“#×2DHṬ“Ð`“ƥ’ḃ2ż4,3F“ỵ£¢µ®/$®n£⁽“¡©Ð‘jo272;⁽æe,⁽¿9ÄỌ;Øaḟ”g

```

A niladic Link yielding a list of characters (or a full program printing them to STDOUT).

**Try it online!**

### How?

```
“#×2DHṬ“Ð`“ƥ’ḃ2ż4,3F - Link: no arguments
“#×2DHṬ“Ð`“ƥ’        - list of base 250 numbers = [35227363705935,4097,165]
             ḃ2      - convert to bijective-base 2 = [[1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1],[1,1,1,1,1,1,1,1,1,1,2,1],[1,2,1,1,2,2,1]]
                4,3  - [4,3]
               ż     - zip together = [[[1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1],4],[[1,1,1,1,1,1,1,1,1,1,2,1],3],[1,2,1,1,2,2,1]]
                   F - flatten = [1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1,4,1,1,1,1,1,1,1,1,1,1,2,1,3,1,2,1,1,2,2,1]

“...“¡©Ð‘jo272;⁽æe,⁽¿9ÄỌ;Øaḟ”g - (continued Link)
“...“¡©Ð‘                      - lists of code-page indices = [[228,2,1,9,8,47,36,8,110,2,141],[0,6,15]]
         j                     - join that (with the previous list) = [228,2,1,9,8,47,36,8,110,2,141,1,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,2,1,2,1,1,1,1,4,1,1,1,1,1,1,1,1,1,1,2,1,3,1,2,1,1,2,2,1,0,6,15]
           272                 - 272
          o                    - logical OR (replace the single 0 with 272)
               ⁽æe,⁽¿9         - [6602,3808]
              ;                - concatenate
                      Ä        - cumulative sums = [228,230,231,240,248,295,331,339,449,451,592,593,594,595,596,597,598,599,600,601,603,604,606,607,608,609,610,611,612,613,615,616,618,619,620,621,622,623,624,625,626,627,628,629,630,632,633,634,635,637,638,640,641,642,643,644,648,649,650,651,652,653,654,655,656,657,658,660,661,664,665,667,668,669,671,673,674,946,952,967,7569,11377]
                       Ọ       - cast to characters = "äæçðøħŋœǁǃɐɑɒɓɔɕɖɗɘəɛɜɞɟɠɡɢɣɤɥɧɨɪɫɬɭɮɯɰɱɲɳɴɵɶɸɹɺɻɽɾʀʁʂʃʄʈʉʊʋʌʍʎʏʐʑʒʔʕʘʙʛʜʝʟʡʢβθχᶑⱱ"
                         Øa    - lower-case English alphabet
                        ;      - concatenate = "äæçðøħŋœǁǃɐɑɒɓɔɕɖɗɘəɛɜɞɟɠɡɢɣɤɥɧɨɪɫɬɭɮɯɰɱɲɳɴɵɶɸɹɺɻɽɾʀʁʂʃʄʈʉʊʋʌʍʎʏʐʑʒʔʕʘʙʛʜʝʟʡʢβθχᶑⱱabcdefghijklmnopqrstuvwxyz"
                            ”g - 'g'
                           ḟ   - filter-discard = "äæçðøħŋœǁǃɐɑɒɓɔɕɖɗɘəɛɜɞɟɠɡɢɣɤɥɧɨɪɫɬɭɮɯɰɱɲɳɴɵɶɸɹɺɻɽɾʀʁʂʃʄʈʉʊʋʌʍʎʏʐʑʒʔʕʘʙʛʜʝʟʡʢβθχᶑⱱabcdefhijklmnopqrstuvwxyz"

```

# Answer
> 2 votes
# Stax, 70 bytes

```
Ç┼☺►┴┬φ3π╓ùδ±║≈§←¬b☻╬₧○ôT»╤↔ñ¢≤♣=≈î⌂╖ì(P┐Φ│xøïº9r═A,Åáï☼♀εwccù√╞Æ3äö▐π

```

Run and debug it

Run and debug it uncompressed

This is my first proper answer to a compression based question. Hope I did well.

Uses a combo of stax's number array compression and binary to print the alphabet.

## Explanation

`Va'g-p` Print the lowercase alphabet without g

`")%EA&#!jA*E).'"!` Deltas of first few symbols, compressed

`228s+` add 228 to the beginning of it (first letter)

`35141380471727:B` 35141380471727 converted to array of bits

`{2s-m` subtract each bit from two

`"1%%%%%%%%%%)%-%)%%))%6v9].,Q&kj"!` deltas of last few symbols, compressed

`++` join all the deltas together

`:+` sums of all prefixes

`p` print, converting ASCII values

# Answer
> 1 votes
# Wolfram Language (Mathematica), 139 bytes

```
FromCharacterCode@Accumulate@Developer`RawUncompress@"xKd&FÅÄÈÉ¡¯ÂÇÔc+dBÕÂbAe111\.00¼£"<>"βθχᶑⱱ"&

```

Try it online! Pure function. Takes no arguments and returns a string as output. Note that the compressed string contains multiple unprintable characters. For reference, the shortest solution I could come up with that doesn't use built-in compression is 140 bytes long (ignore the `Join::heads` message):

```
Complement[CharacterRange@@@Join[97**122,228|231,592|644,648|674],Characters@"gåɚɝɦɩɷɼɿʓʖʗʚʞʠ"]<>"ðøħŋœǁǃβθχᶑⱱ"&

```

---
Tags: code-golf, kolmogorov-complexity, alphabet
---


title: Deserialize a binary tree breadth-first

text:
# Question
Title: Deserialize a binary tree breadth-first
Deserializing binary trees depth-first is pretty easy, but doing it breadth-first is (hopefully) harder. Your mission, should you choose to accept it, is to do the latter.

The input will be a 1-D list of positive integers representing node values and some other consistent value representing the absence of a child (I'll use `#` here). The first element of that list is the root of your tree, the next is the root's left child, then the root's right child, then the left child's left child, then the root's left child's right child, and so on. If a node doesn't have a left or right child, there will be a `#` instead of a positive number to signify that.

You probably know how to do that already, but here's an example anyways:

```
Input: [1, 5, 3, #, 4, 10, 2]

First element is root
    Tree                List: [5, 3, #, 4, 10, 2]
      1

Set the root's left child to the next element
    Tree                List: [3, #, 4, 10, 2]
      1
     /
    5

Set the root's right child to the next element
    Tree                List: [#, 4, 10, 2]
      1
     / \
    5   3

That level's filled up, move on to 5's left child.
Since it's '#', there's no left child, so leave that empty.
    Tree                List: [4, 10, 2]
      1
     / \
    5   3
   #

Set 5's right child to 4
    Tree                List: [10, 2]
      1
     / \
    5   3
   # \
      4

Move on to 3's left child
    Tree                List: [2]
       1
     /   \
    5     3
   # \   /
     4  10

Move to 3's right child
    Tree                List: []
      1
     /   \
    5     3
   # \   / \
     4  10  2

List is empty, so we're done.

```

## Input

The input will be a 1-D list or multiple values read from STDIN. It won't be empty, and the first element will always be a positive integer. I used '#' here, but you can use `null`, 0, or any consistent value that isn't a positive integer (please indicate what you use in your answer). The input may contain duplicate values and the tree it represents isn't necessarily sorted or in any sort of order.

## Output

The output can be printed to STDOUT in the shape of a tree (you can make it look however you want as long as it's clear which nodes are connected to which and you don't just print the input back out), or returned from a function as a tree-like structure (the latter is preferred).

You can have each level on a separate line (or separated by some other character(s)), and each node also separated by some character(s) (like in Arnauld's JavaScript answer) OR you could have each child separated by some character, so long as it's clear which node is which node's child (like in Neil's Charcoal answer).

If your language doesn't have a "tree" data type or you can't make a `Tree` class (or you just don't want to), you could also use a list to represent the tree. Just make sure that it's in an unambiguous format. For example, the tree above could be written as this:

```
[Value, Left Child, Right Child]

[1,
  [5,
    #, //No left child, so #
    [4, #, #] //or just [4] since both children are absent
  ],
  [3,
    [10, #, #],
    [2, #, #]
  ]
]

```

## Test cases:

```
Input -> Output
Tree

```

```
[1] -> [1, #, #] //or [1], whatever you wish

Tree: 1   //or just 1
     / \
    #   #
([1, #, #] and [1, #] yield the same result as above)

[100, 4, #, 5, #, #] -> [100,[4,[5],#],#]
Tree:    100
        /   \
       4     #
      / \
     5   #
    /
   #

[10, 5, 4, 2, #, 8, 1, 2, 2, 4] -> [10,[5,[2,[2],[2]],#],[4,[8,[4],#],[1]]]
Tree:     10
        /    \
       5      4
      / \    / \
     2   #  8   1
    / \    /
   2   2  4

[100, #, 4, 5, #, #] -> [100, #, [4, [5], #]]
Tree:    100
        /   \
       #     4
            / \
           5   #
          / \
         #   #

```

## Rules

* Since this is , shortest code (in bytes) wins.

100 point bounty for an answer that doesn't use any mutability whatsoever (but please don't just post something you found on StackOverflow).

# Answer
# JavaScript (ES10),  ~~81~~  80 bytes

*Saved 1 byte thanks to @Shaggy*

Expects `-1` for a non-existing child node. Returns a string where each line contains all the nodes at this depth.

```
a=>(g=r=>a+a&&(r=r.map(x=>+x||a.shift()||-1))+`
`+g(r.flatMap(x=>[x=-!~x,x])))``

```

Try it online!
> 5 votes

# Answer
# Charcoal, 40 bytes

```
≔⟦Ｓ⟧θ⊞υθ≔⁰ηＷＳ«Ｆ¬⁼#ι«≔⟦ι⟧ι⊞υι»⊞§υ⊘ηι≦⊕η»θ

```

Try it online! Link is to verbose version of code. Takes input on separate lines with newline termination and empty nodes marked with `#` and output uses Charcoal's default output for a nested array structure which is basically preorder traversal with blank lines to show movement back up the tree. Explanation:

```
≔⟦Ｓ⟧θ

```

Create a node for the root.

```
⊞υθ

```

Add the node to the list of all nodes.

```
≔⁰η

```

Start counting the inputs.

```
ＷＳ«

```

Repeat until the blank line marking the end of the input list.

```
Ｆ¬⁼#ι«

```

If this value is not the empty node marker, then...

```
≔⟦ι⟧ι

```

... turn it into a node, and...

```
⊞υι

```

... add it to the list of all nodes.

```
»⊞§υ⊘ηι

```

Push the node or marker to the child currently being filled.

```
≦⊕η

```

Increment the input count. The child being filled is half (rounded down) of the input count.

```
»θ

```

Output the finished tree.
> 3 votes

---
Tags: code-golf, binary-tree
---


title: Dice Paths on a Grid

text:
# Question
Title: Dice Paths on a Grid
You place a standard die at the origin of a 2D grid that stretches infinitely in every direction. You place the die such that the 1 is facing upwards, the 2 is facing in the negative y direction, and the 3 is facing in the positive x direction, as shown in the figure below:

You then proceed to execute a series of moves with the die by rotating it 90 degrees in the direction of motion. For example, if you were to first rotate the die in the negative x direction, a 3 would be upwards, the 2 would be facing in the negative y direction, and a 6 would be facing in the positive x direction.

The series of moves `+y, +y, +x, +x, -y` is shown in the figure below, along with the net of the die for clarification (sometimes the net is called a 'right-handed die').

We then proceed to read off the top face of the die after every move. In this case it would read `2, 6, 4, 1, 2`, which we call a *dice path*. Note we do not include the top face of the die in its initial position, but it is always 1.

If the path of the die is such that it returns to the square it started on at the end of its movement, we call this a *dice path that returns to the origin*.

## Challenge

Given a nonempty dice path as input (in a list or any other reasonable format), print a truthy value if the dice path returns to the origin, and a falsy value otherwise. Note that:

* The truthy values and falsy values you output do not have to be consistent, but you can't swap them (eg. output a falsy value for a path that returns to the origin and a truthy value otherwise)
* The input will be well formed and represent a valid dice path.
* There is no limit to how far the die can stray from the origin.

## Test Cases

```
Path                            -> Output
2,1                             -> true
3,1                             -> true
5,4,1,5                         -> true
2,4,1,2                         -> true
4,2,4,1                         -> true
2,4,6,2,4,6,5,4                 -> true
2,4,5,1,4,5,3,6,5,1             -> true
5,6,2,3,5,4,6,3,1,5,6,2         -> true
2,4,1,3,5,1,3,5,6,3,5,6,4,5,6,2 -> true
2                               -> false
4,5                             -> false
5,1,2                           -> false
5,6,2,1                         -> false
5,4,6,5,4,6                     -> false
5,6,4,1,5,4,2,6,5,4             -> false
5,1,2,1,5,6,5,1,2,6,4           -> false
4,6,3,1,5,6,2,1,3,6,4,1         -> false

```

## Scoring

Shortest code in bytes wins.

# Answer
> 12 votes
# JavaScript (ES6),  ~~142 ... 122~~  121 bytes

Expects an array of characters, e.g. `['5','1','2']`. Returns **0** or **1**.

```
a=>a.map(n=>D=D.map((_,i)=>D['504405076067'[d*6+i>>1]^i],p+=[w=a.length,-w,1,-1][d=D.indexOf(n)]),p=0,D=[...'254316'])|!p

```

Try it online!

### How?

The array `D[]` holds the face values in the following order:

```
 index |    0   |    1   |    2   |    3   |    4   |    5
-------+--------+--------+--------+--------+--------+--------
 face  |  front | behind |  left  |  right |   top  | bottom

```

We start with `D = ['2','5','4','3','1','6']`, which is the initial orientation of the die as described in the challenge, using this encoding.

The direction `d` of the next move is the 0-indexed position of the new top face in `D[]`:

```
 index (d) |   0   |   1   |   2   |   3
-----------+-------+-------+-------+-------
 direction |  up   |  down | right |  left

```

When moving towards direction `d`, the `i`-th face in the updated die is the face at the following position in the previous die:

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

```

This table is encoded with the following expression:

```
'504405076067'[d * 6 + i >> 1] ^ i

```

Try it online!

At each iteration, we update `D[]` and the position `p`. We add \\$\pm 1\\$ to \\$p\\$ when moving horizontally, or \\$\pm w\\$ when moving vertically, where \\$w\\$ is the length of the input array (an upper bound of the distance that can be traveled in a single direction). We test whether we're back to our starting point at the end of the process.

# Answer
> 8 votes
# , 79 bytes

Takes in the dice path as a reversed list of boxed 0 to 5.

```
0 0-:[:+/(0,(,-@|.)=i.2){~]i.~&>[:}.(]A.~0 224 283 389 489{~i.~)&.>/\.@,&(<i.6)

```

Try it online!

### How it works

We have the starting dice as the list `0 1 2 3 4 5`. Looking for the next top digit, we have either `1 2 3 4` as its index (`0` and `5` would be illegal moves). Taking the anagram indices `224 283 389 489` we permute the list, executing a dice move. We do this for the whole path and gather the intermediate results: `0 1 2 3 4 5│4 0 2 3 5 1│3 0 4 1 5 2`. Again, after looking for the indices, we map them to coordination changes `_1 0, 0 _1, 1 0, 0 1`, sum them up and check if they end up at `0 0`.

There should be a byte saving by remapping the dice numbers 6 to 4, 5 to 3, …, 1 to 5 to save the two dummy zeros (`0,` and `0` ) by shifting the possible indices to `0 1 2 3`. But this feels so wrong that I'll try to think of another solution first. :-)

# Answer
> 7 votes
# Charcoal, ~~55~~ 48 bytes

```
≔324516θＦＳ«≔⌕θιιＭ✳⊗ι≔⭆§⪪”)⊟？2p}Þ↔～>”⁶ι§θＩκθ»¬∨ⅈⅉ

```

Try it online! Link is to verbose version of code. Takes input as a string of digits and outputs a Charcoal boolean, i.e. `-` for back at the origin, whitespace if not (+2 bytes to remove the whitespace). Explanation:

```
≔324516θ

```

The digits on the die, in the order right, up, left, down, top, bottom.

```
ＦＳ«

```

Loop through the input digits.

```
≔⌕θιι

```

Find in which direction the die was rolled.

```
Ｍ✳⊗ι

```

Move in that direction.

```
≔⭆§⪪”)⊟？2p}Þ↔～>”⁶ι§θＩκθ»¬∨ⅈⅉ

```

Permute the digits to their new positions using a lookup table `514302` `052413` `415320` `042531` depending on the direction.

```
»¬∨ⅈⅉ

```

Did we end up back at the origin?

# Answer
> 6 votes
# Python 2, 91 bytes

```
a=b=1
t=0
for c in input():t=1+t*1j**(a*c*(a*a-c*c)*b**5%7*2/3+2*(a==c));a,b=b,c
print t==0

```

Try it online!

The idea is to translate each triplet of consecutive die faces shown into the corresponding turn made by the die's path. The possible turn directions are left, right, straight, or reversing, all taken relative to the die's previous move. From the sequence of turns, we track the die's current coordinate and check whether it returns to the origin. Instead of tracking the die's facing direction, we simply rotate the whole coordinate system around it when it turns, and then move it.

Doing it this way means we don't have to track the state of the die itself -- just looking at local snippets of the input sequence suffices. We also don't use any hardcoded values or magic numbers.

The tricky bit is extracting the turn direction from the three consecutive die faces. You can think of these as a bug crawling on the from the first face to the second face, and then from the second face to the third face -- which direction does it need to turn on the second face to do this? We can detect that it doubles back if the first and third faces are equal, and that it goes straight forward when the first and third faces are opposite, so they add to 7.

In the remaining cases, it remains to detect whether the bug turns left of right, that is the triple of faces is left-handed or right-handed. For this, we borrow an algebraic trick from my CW solution to Determine dice value from side view. The expression `3*a*c*(a*a-c*c)` will equal either `b` or `-b` modulo 7 depending on whether the triple is right-handed or left-handed. From there, some massaging takes the four cases of turn directions to numbers that equal `0,1,2,3` modulo 4, so that we can get the right complex rotation using the complex exponent `1j**`.

# Answer
> 5 votes
# Jelly, 35 bytes

```
6RW;⁸œ?@\ḊḢ€⁼
“§ṫ²G‘×J$ṗLçƇ:19Ḣı*S¬

```

A monadic Link accepting the dice-path as a list of the faces in \\$\[1,6\]\\$ which yields `1` (truthy) if it ends back at the start, or `0` (falsey) otherwise.

**Try it online!** Or see the test-suite (6 longest removed since the method is inefficient).

### How?

Forms all the possible paths of the given dice-path's length formed from the four possible directions as the permutations-indices of the next state.
Filters these to find the one that matches the face-up numbers in the given dice-path.
Translates the permutation indices to the four Cartesian directions as complex numbers.
Checks if the sum of these is zero.

```
“§ṫ²G‘×J$ṗLçƇ:19Ḣı*S¬ - Main Link: dice-path
“§ṫ²G‘                - list of code-page indices = [225,245,130,71]
      ×J$             - multiply by their indices = [225,490,390,284]
                        (these correspond to [up, down, right, left])
          L           - length (of the dice-path)
         ṗ            - Cartesian power (all lists of that length using {225,490,390,284})
            Ƈ         - filter keep those for which:
           ç          -   call Link 1 as a dyad - f(potential-path, dice-path)
             :19      - integer divide by 19 (225,490,390,284 -> 11,25,20,14)
                Ḣ     - head (get the single path that filering found)
                        (having Ḣ here rather than before the :19 saves a byte)
                 ı*   - i exponentiate (that) (11,25,20,14 -> -i,i,1,-1)
                        (yep we've mirrored but it makes no difference)
                   S  - sum
                    ¬ - logical NOT

6RW;⁸œ?@\ḊḢ€⁼ - Link 1: potential-path (as permutation indices), dice-path
6             - six
 R            - range -> [1,2,3,4,5,6]
  W           - wrap -> [[1,2,3,4,5,6]]
   ;⁸         - concatenate with the permutation indices -> [[1,2,3,4,5,6],a,b,c,...]
        \     - cumulative reduce (current-state, permuation index) by:
       @      -   with swapped arguments:
     œ?       -     permuation (of the current state) at index (permutation index)
         Ḋ    - dequeue (remove the leading [1,2,3,4,5,6])
          Ḣ€  - head of each (get the list of face-up pips)
            ⁼ - equals (the dice-path)?

```

# Answer
> 5 votes
# Wolfram Language (Mathematica), ~~96...74~~ 72 bytes

```
<<Quaternions`
0==Tr[a={-1,-K,J,-J,K,1};#&[t=a[[#]],a=++t**a**t/2]&/@#]&

```

Try it online!

`Quaternions`` must be loaded prior to the function definition.

```
<<Quaternions`              (* load the Quaternions` package *)
a={-1,-K,J,-J,K,1};         (* (a die roll of i moves the die in direction a[[i]]) *)
            a=++t**a**t/2   (* rotate `a` in a direction *)
#&[t=a[[#]],             ]& (* and return the direction, *)
% /@#                       (* taking directions one at a time from input. *)
0==Tr[ % ]&                 (* check if the sum of directions returns to the origin. *)

```

# Answer
> 4 votes
# Python 3, <sup>~~174~~ \\$\cdots\\$ ~~130~~</sup> 129 bytes

Saved a whopping ~~15~~ ~~30~~ 35 bytes thanks to the man himself Arnauld!!!
Saved another whopping ~~3~~ ~~9~~ 10 bytes thanks to ovs!!!

```
def f(l,p=[3,2,4,5,1,6],v=0):
 for d in l:n=p.index(d);v+=1j**n;p=[p[int(i)]for i in'%06d'%ord('첽꘣'[n])]
 return v==0

```

Try it online!

Returns `True` if we end up back at the origin or `False` otherwise.

Port of Neil's Charcoal answer using complex arithmetic to find out if we're back where we started.

# Answer
> 4 votes
# , ~~143 ... 116~~ 102 bytes

*Edits: -13 bytes by switching to linear instead of matrix list of transitions, then -4 bytes by halving the list of transitions & calculating the left, back & bottom die values as 7 minus the right, front & top values at each roll, then -3 bytes by switching to a base-7-encoded number to generate the list of transitions, then -14 bytes by rearranging the transition list to up, right, down, left to make calculating the new position easier using powers of i, and -6 bytes by various other minor golfs that didn't alter the approach*

```
p=a=1:4;m=5032105982%/%7^(11:0)%%7;for(i in scan()){p[6:4]=7-p;p=p[m[q<-(p[m[a]]==i)]];F=F+1i^a[q]};!F

```

Try it online!

**How?**

(commented code before golfing)

```
is_dice_loop=
function(s,                     # s = vector of top die values along path
 p=1:6,                         # p = positions of current die values
                                #     (top,front,right,left,back,bot)
 m=matrix(                      # m = matrix of transitions at each roll
  utf8ToInt(                    #     created from ASCII values of
   "bedcfabbccafddfaafeeebcd")  #     this string
   -96,                         #     -96,
  4)                            #     matrix has 4 rows.
 ){
 for(i in s){                   # Now, for each die value i along the path
  r=match(i,p[m[,1]]);          #  calculate the roll direction r
                                #  (1:4 -> up,down,right,left),
  p=p[m[r,]];                   #  then calculate the new positions of die values,
  F=F+(-.5+r%%2)*1i^(r>2)       #  and calculate the new location of the die
                                #  as a complex number (real=left->right, imaginary=down->up)
                                #  (F is initialized as 0+0i by default).
 }
 !F                             # If we end up back at 0+0i, then we've done a loop,
}                               # so NOT F is true.

```

# Answer
> 2 votes
# Perl 5 `-pF`, ~~130~~, 121 bytes

```
@A=(2,4,-1,1,-@F,@F+!s/^/1/);s/.(?=.(.))/$x+=$A[$&==$1||$&+$1!=7&&($P[$|--]=$&)&&$1==$P[$|]?$A[$|]^=1:$A[$|]]/ge;$_=$x==1

```

Try it online!

A different solution, the straightforward one was 173 bytes, which could be golfed to 165 bytes.

EDIT : I realized after that the straightforward could be golfed to 136 bytes

But to golf more I though differently. Using the fact that the sum of opposite side is 7. And that keeping a track of some previous number could be sufficent to get the directions.

* array A :
    + `[0]`={2|3} and `[1]`={4|5} : to store the direction on (+/-)x or (+/-)y, where x and y depend on the firsts move's direction on these axes
    + the next `[2..5]` : to store numbers to add to `$x` corresponding to direction
* `s/^/1/` : prepend `1` the initial face
* regex `.(?=.(.))` : consumes one die face `$&` and capture the next next `$1`
* `$&==$1` the direction is changing backward
* `$&+$1==7` the direction doesn't change, the test is inverted because nothing to do
* otherwise the direction has changed to rigth or left compared to the previous direction
* array P : stores the last die face \[0\] x, \[1\] y, where x and y are depends on the firsts moves
    + `$P[$|--]=$&` :
        - `$P[$|]=$&` to store the die face when turning left or right
        - `$|--` switches axis index 0/1 for x/y
* `$1==$P[$|]` the next next face is compared to the last when moving on the same axis if is equal the direction is changing backward compared to the previous direction
* `^=1` : to switch using bytwise xor (2\<-\>3) or (4\<-\>5)
* `$_=$x==1` : the initial position when `$x==1` because first move (direction 2 : -1) was not added.

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


title: Loves me, loves me not

text:
# Question
Title: Loves me, loves me not
# Loves me, Loves me not

This simple kids' game is old, but still popular. Since we are living in 21st century now, let's digitize it!

# Specification

Program must take no input, unless you are using a language that can't generate random seed - in that case you are allowed to take the seed as an input. Your task is to write a program that will output randomly a total of 3 to 20 lines inclusive: "Loves me..." and "Loves me not..." in turns, as in the game (and one additional line; keep reading).

However, there are some restrictions. Each line should be followed by newline. The first line must be "Loves me...". The last line (either "Loves me" or "Loves me not") should end with exclamation mark or a single dot, respectively. After the last line, you need to output either a heart( `<3` ) or a broken heart ( `</3` ) in the new line, depending whether "Loves me!" or "Loves me not." was the last sentence.

Trailing whitespace are allowed.

# Example Output

Output:

> Loves me...
> Loves me not...
> Loves me...
> Loves me not...
> Loves me!
> \<3

Another output:

> Loves me...
> Loves me not...
> Loves me...
> Loves me not.
> \</3

## This is the , so the shortest entry wins!

Also, my first challenge :) Good luck!

# Answer
# Pyth, 54 53 51 50 48 bytes

```
pj+*3\.bm+W~!Z"Loves me"" not"+3O18@".!"Z%hZ"</3

```
> 23 votes

# Answer
# CJam, ~~53~~ ~~50~~ 49 bytes

*Thanks to Dennis for saving 1 byte.*

```
Imr3+{"Loves me"X!:X" not"*'.3*N}*&"!."X=N'<'/X*3

```

Test it here.

## Explanation

The code just dumps the string in bits and pieces onto the stack, which is printed automatically at the end of the program:

```
Imr3+         e# Generate a random number in [3,20]
{             e# Execute this block that many times.
  "Loves me"  e#   Push "Loves me", we always need that.
  X!:X        e#   Toggle X (initially 1) between 0 and 1 and leave it on the stack.
  " not"*     e#   Repeat " not" that many times, removing it on every other line.
  '.3*N       e#   Push "..." and a newline.
}*
&             e# Set intersection of "..." and newline, turning them into an empty array.
"!."X=        e# Select "!" or "." based on the last value of X.
N'<           e# Push a newline and "<".
'/X*          e# Include "/" or not depending on the last value of X.
3             e# Push a 3.

```
> 23 votes

# Answer
# Brainfuck, 2766 bytes (currently invalid)

Just because. I'll add an ungolfed version later.

### Code

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

```

### Pseudocode

```
loop
    get a random byte
until random byte is >2 and <21

point to byte
[
    output "Loves me..."
    decrease byte by 1
    if byte is 0
        output "<3"
        exit
    eif
    output "Loves me not..."
    decrease byte by 1
]
output "</3"

```

### Sample

When run, the program enters an interactive session waiting for input. Input should be a number. This number is used as a seed.

**Seed: 1 (random number is 5, takes 218,168,042 operations)**

```
1
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
<3

```

**Seed: 3 (random number is 20, takes 463,253,048 operations)**

```
3
Loves me...
Loves me not...
(...)
Loves me...
Loves me not...
</3

```

I'd suggest that you do not seed with `6`, as it takes `2,105,900,375` iterations to compute the result :).

### Compiling / Running

You need a fast interpreter for this. No online interpreter I've tested could handle the execution speed. The ips (iterations per second) should be more than `100,000,000`. So I came up with another solution.

This is a Brainfuck to C compiler written in Brainfuck. You can use any online interpreter to transpile my code to pure C. I suggest using brainfuck.tk. Paste my code in the stdin input, past this code in the code input:

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

```

Download the source and compile it:

```
gcc.exe -c main.c -o main.o
gcc.exe main.o -o loveme.exe

```

You can also run a copy of the C code online here: via. CodingGround.

### Optimizations

There is still some work to do, but the cell re-use is almost optimal.

### Remarks

You can use words or phrases as a seed:

```
Programming Puzzles & Code Golf
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
<3

```
> 17 votes

# Answer
# Javascript (ES6), ~~119~~ ~~104~~ ~~99~~ 98 bytes

```
for(i=new Date%18+3,s=i&1?`!
<3`:`.
</3`;i--;)s=`...
Loves me`+(i&1?' not':'')+s
alert(s.slice(4))

```
> 7 votes

# Answer
# Python, 147

```
from random import*;t=randint(3,20)
print"\n".join("LLoovveess  mmee  n o t"[i%2::2].strip()+"..."*(i<t-1)for i in range(t))+"!.\n\n<<3/ 3"[t%2::2]

```

Uses the `from random import*` instead of `import random` and `randint` instead of `randrange` to save a few bytes. There's probably some bytes left to golf out.
> 6 votes

# Answer
# Javascript (ES6), ~~110~~ 102 bytes

```
a='';for(i=j=new Date%18+3;i--;)a+='Loves me'+(j-i&1?'':' not')+(i?`...
`:j&1?`!
<3`:`.
</3`);alert(a)

```

This was a short but fun little challenge. It may be possible to shorten more. Thanks to Mwr247 for some byte-saving tricks!

Alternate version using `repeat()`, 105 bytes:

```
a='';for(i=j=new Date%18+3;i;)a+='Loves me'+' not'.repeat(j-i--&1)+(i?`...
`:j&1?`!
<3`:`.
</3`);alert(a)

```

Darn JS 5+-char built-in names. Oh well. Suggestions welcome!
> 6 votes

# Answer
# Perl 5 \+ `-M5.10.0`, 76 bytes

```
print"...
"x!!$_,"Loves me"," not"x$|--for 0..2+rand 18;say$|?"!
<3":".
</3"

```

Try it online!
> 5 votes

# Answer
# Ruby, 91 bytes

```
(n=3+rand(18)).times{|i|puts"Loves me"+[""," not"][i%2]+(i<n-1?"...":i%2>0?".
</3":"!
<3")}

```
> 5 votes

# Answer
# Common Lisp ~~106~~ 104 bytes

```
(format t"~{Loves me~[ not~]~#[~:*~[.~%</~;!~%<~]3~:;...~]~%~}"(subseq'#1=(1 0 . #1#)0(+ 3(random 18))))

```

This only works on lisps that don't check for a proper sequence (e.g. cmucl, sbcl, clisp) ccl will check for circularity and error out on default safety level. ecl will loop forever.

## Explanation:

`#1=(1 0 . #1#)` generates a circular list containing `1` and `0` and `subseq` is used to make a list of length \[3,20\] (this is the only non-portable part, as `subseq` is only required by the standard to work on proper (i.e. non-circular) lists).

Our format is now operating on a list of `1 0 1 0...` of length \[3,20\]

### Explanation of `format` directives:

`~{` iterates over this list

`~[` followed by any number of `~;` and terminated with `~]` will select the Nth item, based on the value of the format argument. This is used here so that the first item in a `~[` will be the "loves me not" case and the second one the "loves me" case. Note that with `~[` a separator of `~:;` selects a default case.

`~#[` works like `~[` except the argument is the number of remaining arguments. 0 remaining arguments means we are at the end, the default case is to print `...`

`~:*` backs up the argument list one position, which allows us to print the correct trailer.
> 5 votes

# Answer
# Python 2, ~~161~~ ~~159~~ ~~156~~ 144 bytes

```
from random import*;a=randrange(3,21)
for i in range(a):print'Loves me'+i%2*' not'+('...'if i!=a-1 else'.'if i%2 else'!')
print['<3','</3'][i%2]

```

It's 39 bytes just to get the random number.

A big thank you to muddyfish, fryamtheeggman, and orlp for their help.

# PYG, 109 bytes

```
a=RR(3,21)
for i in R(a):P('Loves me'+i%2*' not'+('...'if i!=a-1 else'.'if i%2 else'!'))
P(['<3','</3'][i%2])

```
> 4 votes

# Answer
# Julia, 98 bytes

```
r=rand(3:20)
for i=1:r println("Loves me"*(i%2>0?" not":"")*(i<r?"...":i%2>0?".\n</3":"!\n<3"))end

```

Ungolfed:

```
# Define a random number 3 ≤ r ≤ 20
r = rand(3:20)

for i = 1:r
    # The loveless lines occur when i is even
    println("Loves me" *
            (i % 2 > 0 ? " not" : "") *
            (i < r ? "..." : i % 2 > 0 ? ".\n</3" : "!\n<3"))
end

```
> 4 votes

# Answer
# UNIX shell, 193 bytes

```
t=$(seq 2 19|shuf|head -1)
l=t
p=...
while [ $t -ge 0 ];do
case $l:$t in t:0)p=!;h=\<3;;f:0)p=.;h=\</3;;esac
case $l in t)l=f;n=;; f)l=t;n=\ not;;esac
t=$((t-1))
echo Loves me$n$p
done
echo $h

```
> 4 votes

# Answer
# Java, ~~210~~ ~~209~~ ~~203~~ ~~200~~ 177 bytes

* ~~flipped `i%2==0` to `i%2<1`~~
* trimmed `{ ... }` braces for `for`-loop, moved `e` declaration to loop
* re-ordered conditionals
* removed modifiers and unnecessary parentheses, reworked `Random` usage and increment for `i`

Note: newline is added below for formatting on this site, the count above is for a *single* line.

```
class F{public static void main(String[]a){for(int e=3+(int)(Math.random()*18),i=0;++i<=e;)
System.out.println("Loves me"+(i%2>0?i<e?"...":"!\n<3":" not."+(i<e?"..":"\n</3")));}}

```

Ungolfed:

```
class F {
    public static void main(String[] a) {
        for (int e = 3 + (int) (Math.random() * 18), i = 0; ++i <= e; )
            System.out.println("Loves me" + (i % 2 > 0 ? i < e ? "..." : "!\n<3"
                    : " not." + (i < e ? ".." : "\n</3")));
    }
}

```
> 4 votes

# Answer
# C, 123, 121, 109 106 characters (108 bytes)

(with a little ♥♥♥cheating♥♥♥)

```
O;main(o){for(o=time(O)%18+3;o-O++;printf("Loves me%s%s\n",O&1?"":" not",o-O?"...":O%2?"!\n♥":".\n</3"));}

```

There's also a broken heart Unicode point at 1f494, but I had difficulties finding a font which implements it.
> 4 votes

# Answer
# PowerShell, ~~121~~ ~~119~~ 111 Bytes

```
$i=2..19|Random;1..$i|%{"Loves me$(if(!($_%2)){" not"})..."};"Loves me$(if(!($i%2)){"!`n<"}else{" not.`n</"})3"

```

Edit--actually shorter to explicitly include `"Loves me"` rather than declaring `$l`

Edit2--forgot that I can golf `for()` loops by pipelining...durr...

Not too shabby. Uses inline code execution blocks `$(...)` to dynamically adjust the printed string as we're `for()`-looping. Note that because this uses an implicit `Get-` in front of `Random` to save a couple bytes, this may operate extremely slowly on certain PowerShell versions. Reference

Expanded below for clarification:

```
# Create a collection of (2,3,4,...18,19) and pipe it as input to Get-Random
$i = 2..19 | Get-Random

# Create a collection of (1,2,...$i-1,$i) and pipe it to seed a ForEach-Object loop
1..$i | ForEach-Object {
  if(!($_%2)) {
    # If the input number is even, we're on an even line
    Write-Output "Loves me not..."
  }
  Else {
    # The input number is odd
    Write-Output "Loves me..."
  }
}
If(!($i%2)) {
  # Our random number is odd
  Write-Output "Loves me!"
  Write-Output "<3"
}
Else {
  # Our random number is even
  Write-Output "Loves me not."
  Write-Output "</3"
}

```
> 3 votes

# Answer
# C++, ~~210~~ ~~193~~ ~~184~~ 168 bytes

In C++.. because.. Why not? :)

```
#include <iostream>
main(){auto&c=std::cout;srand(time(0));int i,j=3+rand()%18;while(i++<j)c<<"Loves me"<<(i%2?"":" not")<<(i==j?"":"...\n");c<<(j%2?"!\n<3":".\n</3");}

```

Live: ~~210~~ ~~193~~ ~~184~~ 168

Just hope that any of my changes are not platform dependent.

Thanks to Ben Voigt for the help. Also, thanks to all the comments, they were very helpful.
> 3 votes

# Answer
# Groovy, 110 bytes

A groovy kind of love:

```
int r=Math.random()*18;print((0..r+2).collect{"Loves me"+" not"*(it%2)}.join('...\n')+['!\n<3','.\n</3'][r%2])

```
> 3 votes

# Answer
# Python 2, 117 bytes

```
from random import*
n=randint(3,20)
print"...\n".join("Loves me"+i%2*" not"for i in range(n))+[".\n</3","!\n<3"][n%2]

```

Observe that every `Loves me( not)?` is followed by `...` and a newline, except for the last one. So this looks like a job for `join`.
> 2 votes

# Answer
# R, ~~141~~ ~~132~~ ~~128~~ ~~114~~ ~~111~~ 109 bytes

### Code

```
k=sample(3:23,1);for(i in 1:k)cat("Loves",c("me not...\n","me...\n","me not.\n</3","me!\n<3")[1+i%%2+2*!i<k])

```

### Ungolfed

```
k <- sample(3:23, 1)        # Generates random "k" number from 3 to 23
for(i in 1:k) {             # Loop this block increasing i from 1 until k by 1
  cat                       # Concatenate and paste everything inside this block
  ("Loves",                 # Push "Loves" on every iterations of the loop
      c(                    # Create a vector of strings
        "me not...\n",      # Push string to the index "1" of vector
        "me...\n",          #   to the index "2"
        "me not.\n</3",     #   to the index "3"
        "me!\n<3"           #   to the index "4"
        )[1+i%%2            # Subset the vector by the index (1 or 2)
          +2*!i<k])}        #   if final iteration of loop then index += 2 (3 or 4)

```

I've took some inspiration from Eric Brooks code.

Edit 1: Now the code correctly outputs the last punctuation as pointed out by Martin
Edit 2: Changed the for loop to a sapply and included the hearts inside the last line string.
Edit 3: Removed the `{}` and changed `+(x==k)*2` to `+2*!x<k`
Edit 4: Back to for loop and removed the `()` from `(i%%2)+1`
Edit 5: Wrote `me` 4 times and removed the `sep=""`
> 2 votes

# Answer
# R, ~~119~~ ~~111~~ 105 bytes

```
x<-sample(3:20,1);cat(rep(c("Loves me...\n","Loves me not...\n"),x)[1:x]);cat(ifelse(x%%2==1,"<3","</3"))

```

Edits 1,2: Coding the two options explicitly is saving space.
> 1 votes

# Answer
# C 226 bytes

```
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void main(){srand(time(NULL));int i=rand()%18+3;int j;for(j=0;j<i;j++)printf("Loves me%s%s\n",(j%2)?" not":"",(j==i-1)?(j%2)?".":"!":"...");printf("<%s3\n",(j%2)?"":"/");}

```

(With formatting)

```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    int i = rand()%18 + 3;
    int j;
    for (j = 0; j < i; j++)
        printf("Loves me%s%s\n", (j % 2) ? " not" : "", (j==i-1) ? (j % 2) ? "." : "!" : "...");
    printf("<%s3\n", (j%2) ? "" : "/");
    return 0;
}

```
> 1 votes

# Answer
# mSL, 178 176 156 154 bytes

Edit 1: Changed `== 0` to `< 1`
Edit 2: Removed unnecessary whitespace, thanks AlexA!
Edit 3: Removed parentheses

```
alias l {
var %n 1
while %n <= $rand(3,20) {
var %m $+(Love me,$iif($calc(%n % 2) < 1,$chr(32) $+ not),...)
echo %m
inc %n
}
echo $iif(n isin %m,</3,<3)
}

```
> 1 votes

# Answer
# Python 2, 115 bytes

```
from random import*
n=randint(2,20)
print'...\n'.join('Loves me'+i%2*' not'for i in range(n))+'.!\n\n<</33'[n%2::2]

```
> 1 votes

# Answer
# Hassium, 265 Bytes

```
func main(){rnd=new Random();times=rnd.next(3,21);println("Loves me...");for(x=0;x<times-1;x++){if(x%2==0)println("Loves me not...");else println("Loves me...");}if((times-1)%2==0){println("Loves me not.");println("</3");}else{println("Loves me!");println("<3");}}

```

The answer has been golfed.
> 1 votes

# Answer
# Hassium, ~~161~~ 165 bytes

I golfed Reagan's answer.

```
func main()println(range(-1,t=new Random().next(3,21)).select(x=>"Loves me"+(x%2==0?" not":"")+(x==t-2?(x%2==0?".":"!"):"...")).join("\n"),"\n",t%2==0?"</3":"<3");

```

Unleashing the power of Hassium.

### Ungolfed version

```
func main()
{
    t = new Random().next(3,21); # initialize the love number
    loveNumber = range(-1, t); # creates an array like this Array { -1 0 1 2 ... ... up to n } where n is a random number between 3 and 21 }
    loves = loveNumber.select(x => # iterates through the array
                                {
                                    ret = "Loves me";
                                    if (x % 2 == 0) # check if x is even
                                    {
                                        ret += " not"; # add ' not' to the result
                                    }
                                    ret += (x == t ? (x % 2 == 0 ? "." : "!") : "...");
                                    return ret;
                                }).join("\n"); # join the result with Unix newlines (\n)
    println(loves); # print it
    println(t%2==0?"</3":"<3");
}

```
> 1 votes

# Answer
# PHP, 191 187 146 165 Bytes

```
$x=rand(5,22);for($i=2;++$i<=$x;){echo"\nLoves me";if($i%2<1)echo" not";if($i<$x)echo"...";if($i==$x&&$i%2<1){echo".\n</3\n";}elseif($i==$x&&$i%2>0){echo"!\n<3\n";}}

```

Ungolfed:

```
$x=rand(5,22);
for($i=2;++$i<=$x;){
    echo "\nLoves me";
    if($i%2<1) echo " not";
    if($i<$x) echo "...";
    if($i==$x && $i%2<1){
        echo ".\n</3\n";
    }
    elseif($i==$x && $i%2>0){
        echo "!\n<3\n";
    }
}

```

48,49 bytes for pyth and cjam ... wow :)
> 1 votes

# Answer
## Perl, 97 bytes

```
$_='She loves me...
'x(3+rand 18);s/(me.*?)me/$1me not/gs;s/e...
$/e!
<3/;s/t...
$/t.
<\/3/;print

```

Readable version:

```
$_="She loves me...\n"x(3+rand 18);
s/(me.*?)me/$1me not/gs;
s/e...$/e!\n<3/;
s/t...$/t.\n<\/3/;
print

```
> 1 votes

# Answer
## C# (160)

The code is inspired by **the answer** from **h.j.k.**, credit goes to him.

```
class P{static void Main(){for(int e=3+new Random().Next(0,18),i=0;++i<=e;)Console.WriteLine("Loves me"+(i%2>0?i<e?"...":"!\n<3":" not."+(i<e?"..":"\n</3")));}}

```

Ungolfed:

```
class P
{
    private static void Main()
    {
        for (int e = 3 + new Random().Next(0, 18), i = 0; ++i <= e;)
            Console.WriteLine("Loves me" + (i % 2 > 0 ? i < e ? "..." : "!\n<3" : " not." + (i < e ? ".." : "\n</3")));
    }
}

```
> 1 votes

# Answer
## Lua, ~~137~~ 132 bytes

Probably can be golfed a lot more, but here it is for now:

```
t=math.random(3,20)for i=1,t do io.write(i%2==0 and"Loves me"or"Loves me not")print(i==t and(i%2==0 and"!\n<3"or".\n</3")or"...")end

```

Code explanation and ungolfed:

```
t=math.random(3,20) --Generates a random number between 1 and 30. We need to assign it to a variable to check if the loop is over later.
for i=1,t do
  io.write(i%2==0 and"Loves me"or"Loves me not") --If i%2 is 0 write without a newline Loves me, if not print Loves me not.
  print(i==t and (i%2==0 and"!\n<3" or ".\n</3") or "...") --If it is not the end of the loop, put ..., else if we ended on an even print ! a newline, and then a heart, but if we ended on an odd put ., a newline and a broken heart :(
end

```

Edit: Chopped off some whitespace.
> 1 votes

# Answer
# Jelly, 55 bytes

```
“¢zḞzƘFq»,;¥“ not”ṁ18X+2¤j“...¶”µċ⁷Ḃ©”/ẋ;3⁾¶<;®ị⁾.!¤;⁸;

```

Try it online!

As usual Jelly sucks with strings.
> 1 votes

# Answer
# PowerShell, ~~85~~ 88 bytes

*+3 bytes thanks Veskah: That's a good point.*

```
0..(1..19|Random)|%{($l='Loves me')+' not'*($n=$_%2)+'...'}
$l+('!
<3',' not.
</3')[!$n]

```

Try it online!
> 1 votes

# Answer
# , 138 bytes

Works (with valid output). More *a* solution than *the* solution, could be golfed further:

```
R=ß!G3,20,1)µL='Loves me'µD='...@LF@'µ€L&D)°/X=0°(R-1µ€L)°\mod(X,2)=0°{€' not')µ€D)°)€L)°\mod(R,2)°{µ€'!'&@LF&'<3')°]€' not.'&@LF&'</3')°}

```

Sample:

```
$ sharps "R=ß!G3,20,1)µL='Loves me'µD='...@LF@'µ€L&D)°/X=0°(R-1µ€L)°\mod(X,2)=0°{€' not')µ€D)°)€L)°\mod(R,2)°{µ€'!'&@LF&'<3')°]€' not.'&@LF&'</3')°}"
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me...
Loves me not...
Loves me!
<3

```
> 0 votes

# Answer
# Japt, ~~77~~ 76 bytes

```
Mq17 +3 o £`Lov ´{Y%2?" not":""}...`Ã
U· +`
Lov ´`+(UÊ%2?" not.
</3":"!
<3

```

Probably can be golfed a lot further.

Try it Online!
> 0 votes

# Answer
# 1. Python 3, 179 171 167 bytes

```
from random import*;n=randint(3,20);s=""
for i in range(n):
    b=i%2==0;s+="Loves me"+(""if b else" not")
    if i<n-1:s+="...\n"
s+="!\n<3"if b else".\n</3";print(s)

```
> 0 votes

# Answer
# ink, 78 bytes

```
-(l)Loves me{&| not}{
-l<3||l>20||RANDOM(0,1):<>...
->l
}{l%2:!|.}
<{1-l%2:/}3

```

Try it online!

\\$p(n) = \begin{cases} \frac{1}{2^{n-3}}& \text{if }3 \le n \le 19\\ \frac{1}{2^{16}}& \text{if }n=20\\ 0& \text{otherwise} \end{cases}\\$

This is probably my least favourite of the three approaches I tried. But the others clocked in at 79 and 80 bytes.
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity
---


title: Conway's Game of Points!

text:
# Question
Title: Conway's Game of Points!
*Rest in peace, John Horton Conway*

There are a **ton** of different Game of Life interpreters out there! A **ton**!

Currently for you, getting an interpreter is just a dozen types and a couple of clicks away.

But wait, do you notice a common thing in the interpreters? Every interpreter is *graphical*, i.e there are only images and no ASCII text!

# The Problem

Fun fact: I was in the middle of creating a 2DF interpreter in my favourite practical programming language while writing this question. 2DF has a command that performs a step of Game of Life on its memory field. I needed to implement that command in my code. I have not done it yet, so this question is technically an actual question rather than a challenge.

I have a **list of some points or coordinates** on a *Cartesian plane*. Each point has an X and a Y value. This is your input! Input can be formated in anyway (you can use any type of formatting, so specify your format in your answers).

Example input format:

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

```

This is a representation of a period of Glider (The Hacker Logo). Draw the points on a grid, and you will see a shape that resembles this:

What I want for output is the same list, but modified! These are the modification steps.

* A new point is added if it has exactly three existing neighbours.
* An existing point is removed if it has more than three or less than two existing neighbours.

### What is a neighbour?

A neighbour of a point X is defined as a point adjacent to X either horizontally, vertically, or diagonaly. The neighbours of point \\$(2, 3)\\$ are:

* \\$(1, 3)\\$
* \\$(1, 2)\\$
* \\$(2, 2)\\$
* \\$(3, 2)\\$
* \\$(3, 3)\\$
* \\$(3, 4)\\$
* \\$(2, 4)\\$
* \\$(1, 4)\\$

In this case, the output should be similar to this:

```
[[1, 0], [2, 0], [2, 1], [0, 1], [1, -1]]

```

# Task

Write a program or implement a function that takes a list of points, and prints or returns a list of points that displays the modified list according to the above modification rules (The order of the output list does not matter).

Oh, and be sure to make the code as short as possible! (`code-golf`)

P.S It would be great if you included an explanation of your program in your answer!

## Some Example Test Cases

```
Example STDIN                                  Example STDOUT
[[0, 0]]                           =>          []
[[0, 0], [0, 1]]                   =>          []
[[0, 0], [0, 1], [1, 0]]           =>          [[0, 0], [0, 1], [1, 0], [1, 1]]
[[0, 0], [0, 1], [1, 0], [1, 1]]   =>          [[0, 0], [0, 1], [1, 0], [1, 1]]
[[0, 0], [0, 1], [0, -1]]          =>          [[0, 0], [1, 0], [-1, 0]]
[[1, 0], [1, 1], [1, 2]]           =>          [[2, 1], [1, 1], [0, 1]]

```

# Good Luck! :)

# Answer
> 7 votes
# APL (Dyalog Extended), ~~34~~ 32 bytes (SBCS)

Anonymous tacit prefix function. Requires `⎕IO←0` (zero-based indexing).

```
⌊/{⍺-1-⍸⌂life 0,∘⌽∘⍉⍣4⍸⍣¯1∧⍵-⍺}⊢

```

Try it online!

`⌊/{``}⊢` call the following anonymous lambda with the smallest existing x and y coordinates as left argument () and the full list as right argument ():

`⍵-⍺` subtract smallest point from all points (scales so every number is non-negative)

sort ascending

`⍸⍣¯1` generate a Boolean matrix with 1s in those positions (lit. inverse of "**ɩ**ndices of 1s")

`0``⍣4` repeat four times with zero as left argument:

…`∘⍉` transpose, then

…`∘⌽` mirror, then (this constitutes a 90° clockwise turn)

…`,` concatenate zeros to the left edge

`⌂life` compute the next Game of Life generation

**ɩ**ndices of 1s

`1-` subtract those from 1

`⍺-` subtract those from the offset of the lowest x and y coordinates

# Answer
> 7 votes
# Husk, 17 bytes

```
uṠfo≈6#-¹×z+π2ṡ1D

```

Try it online! Note that the interpreter doesn't like extra spaces in inputs.

## Explanation

```
uṠfo≈6#-¹×z+π2ṡ1D   Input is a list of lists, e.g. L=[[0,0],[1,0],[2,1]]
                D   Repeat twice: X=[[0,0],[1,0],[2,1],[0,0],[1,0],[2,1]]
              ṡ1    Symmetric range to 1: [-1,0,1]
            π2      Cartesian second power: [[-1,-1],[-1,0],…,[1,1]]
         ×          Pick all elements from this and X and combine with
          z+        zipping by addition: [[-1,-1],[0,-1],…,[3,2]]
       -¹           Remove one occurrence of each element of L.
                    Call the result Y.
  f                 Filter by condition:
 Ṡ    #             number of occurrences in Y
   o≈6              is close to 6 (so 5, 6 or 7).
u                   Remove duplicates: [[1,1],[1,0]]

```

# Answer
> 5 votes
# , ~~164~~ 156 bytes

*Note: now outgolfed in  by my own other answer*

```
function(p){m=matrix(F,u<-max(p)-(r=min(p)-2)+1,u)
m[t(p-r)]=T
t(which(m[]<-(s=sapply(1:u^2,function(j)sum(m[(j+-3:5%/%3*u+-2:0)%%u^2+1])))==3|m&s==4,T))+r}

```

Try it online!

Function that accepts and returns coordinates as columns of a 2-row matrix.

Works by creating a matrix & filling it at the specified coordinates, then calculating the next generation & outputting the indices of filled elements.

**How?**

```
gol_points=
function(p){            # p = matrix with coords in columns
 m=matrix(F,            # create a matrix, filled with FALSE...
  u<-diff(              #  with row number u equal to the difference...
  r<-range(p))+3,       #  between the range r of values in p, plus 3,
  u)                    #  and the same number of columns
                        #  (so it's a square matrix with dimensions 1 bigger
                        #  than the largest range of p)
 m[t(p-r[1]+2)]=T       # Now, set the elements of m at coordinates p + offset to TRUE
 t(which(               # Then, return the coordinates of elements that satisfy...
  m[]<-(s=              #  m, filled with...
   sapply(1:u^2,        #   the results for each of 1..u^2 (each element of m)...
    function(j)         #   of a function taking argument j...
     sum(m[(j+          #   and returning the sum of elements of m at position j...
     -3:5%/%3*u+-2:0    #   plus the elements at all adjacent positions...
     )%%u^2             #   (modulo the matrix size u^2 to wrap-around the edges)
     +1])               #   +1 (R uses 1-based indices),
   ))==3                #  is equal to 3 (3 neighbours, or filled cell with 2 neighbours)
   |m&s==4,         #  or is itself TRUE and sum is equal to 4 (filled cell with 3 neighbours)
   T))                  # (arr.ind=TRUE = return coordinates, rather than linear indices),
  +r[1]-2}              # minus the offset used in the first place.

```

# Answer
> 3 votes
# Julia 1.0, ~~121~~ 91 bytes

```
f=g->[v for v=Set(h+[j,k] for h=g,j=-1:1,k=-1:1)if 2<sum(i->all(abs.(v-i).<2),g)<4+in(v,g)]

```

Try it online!

## Explanation

```
f=g->[v for v=                          # Array Comprehension of final result

    Set(h+[j,k] for h=g,j=-1:1,k=-1:1)  # Set Comprehension of all neighboring cells
                                        # of occupied cells, including self
    if 2<
        sum(i->all(abs.(v-i).<2),g)     # Count the number of neighbors, including self.
                                        # For i in g, count iff the distance
                                        # between v and i is less than 2
                                        # for all dimensions

        <4+in(v,g)                      # <4 if cell is empty, <5 if occupied
]

```

# Answer
> 2 votes
# Wolfram Language, 92 bytes

```
CellularAutomaton["GameOfLife",{SparseArray[#+1-Min@#->(1&/@#)],0}][[1]]~Position~1-2+Min@#&

```

`#+1-Min@#->(1&/@#)` converts the input to rules for SparseArray: `#+1-Min@#` generates the proper shift to make the indices positive and `(1&/@#)` makes a list of ones of the proper length.

This is then fed into CellularAutomaton to generate a step of Conway's Game of Life. The result is extracted and fed into Position to find the positions of living cells, then the index shift is reversed with `-2+Min@#` (it's minus 2 rather than minus 1 because CellularAutomaton adds padding to encompass all cells that could be affected).

Try it online!

# Answer
> 2 votes
# Python 3, ~~215~~ \\$\cdots\\$ ~~129~~ 127 bytes

Saved a whopping 36 bytes thanks to att!!!
Saved 2 bytes thanks to ovs!!!

```
lambda l:{(a+c,b+d)for c in(-1,0,1)for d in(-1,0,1)for a,b in l if((a+c,b+d)in l)+4>sum(abs(a+c-e+(b+d-f)*1j)<2for e,f in l)>2}

```

Try it online!

Inputs of a list of points and returns the next generation as a list of points.

### Explanation (before some golfs)

```
def f(z):               # input a list of complex numbers

n={                     # create a set of neighbouring complex numbers
   p+                   # by adding to every point
    a+b*1j              # a vector of
     for a in(-1,0,1)   # one left, 0, one right: all combined with each of
      for b in(-1,0,1)  # one down, 0, one up
       for p in z};     # for all the input points

g=lambda                # create a function
   p:                   # mapping a point
     sum(               # to the sum...
         0<abs(a-p)<2   #     if the distance between them
                        #     is either 1 or root 2
          for a in z)   # ...of the live points

return[(p               # return a list of complex numbers
 for p in n             # for all the points in the neighborhood
  if g[p]==3            # if it has 3 neighbors
   or g[p]==2and p in z]# or 2 neighbors and is alive

```

# Answer
> 2 votes
# , 59 bytes

```
(([(~.#~3=#/.~)@-.~[:,+/),[#~3 4 e.~[:+/[e."1+/)&(,j./~i:1)

```

Try it online!

Explanation later.

# Answer
> 2 votes
# Scala, ~~151~~ 118 bytes

Uses stuff from the Julia answer by @Vole. Go upvote that!

```
g=>for{x->y<-g
r= -1 to 1
a<-r
b<-r
n=(for(i<-r;j<-r)yield(x+a+i,y+b+j))count g
if n==3|g(x+a,y+b)&n==4}yield(x+a,y+b)

```

Try it online!

TIO says 119 bytes, but that's because I have to use `(x,y)` to extract a Tuple2 instead of just `x->y`, which was added after Scala 2.10 (the version TIO uses).

# Dotty, 117 bytes

```
g=>for{x->y<-g;r= -1 to 1;a<-r;b<-r;n=g.count((i,j)=>math.hypot(x+a-i,y+b-j)<2)if n==3|g(x+a,y+b)&n==4}yield(x+a,y+b)

```

Try it online

## Explanation

```
g =>
  for {
    x -> y <- g     //For every point in the grid,
    r = -1 to 1     //Create range from -1 to 1 to use later
    a <- r          //For every a in r
    b <- r          //For every b in r ((x+a, y+b) is a neighbor of (x,y) or (x,y) itself)
    n = (for(i <- r; j <- r)
          yield (x + a + i, y + b + j) //(x+a, y+b) and all its neighbors
        ) count g   //How many of them are in g?
    if n == 3 | g(x + a, y + b) & n == 4 //Filter the cells that'll be live next round
    //If n=3, it's live and has 2 neighbors, or it's not live and has 3 neighbors, so it'll be live next round.
    //Otherwise, check if it's live and has 3 neighbors
  } yield (x + a, y + b)  //Yield every such point

```

# Answer
> 2 votes
# Jelly, 25 bytes

```
-r1ṗ2⁸+€Ẏċ€@Ḅe6,7,9ʋƇ,¥⁸Q

```

A monadic Link accepting a list of coordinates which yields the same after an iteration of the Game Of Life.

**Try it online!**

### How?

```
-r1ṗ2⁸+€Ẏċ€@Ḅe6,7,9ʋƇ,¥⁸Q - Link: list of coordinates, A
-r1                       - -1 inclusive range 1 -> [-1,0,1]
   ṗ2                     - Cartesian power two -> [0,0] and its the eight neighbours
     ⁸+€                  - add to each of A -> list of lists of an existing cell + its neighbours
        Ẏ                 - tighten -> list of all existing cells and their neighbours
                            call this B
                      ¥⁸  - last two links as a dyad - f(B, A):
                     ,    -   pair -> [B, A]
                    Ƈ     -   filter keep those c in B for which:
                   ʋ      -     last four links as a dyad - f(c, [B, A])
         ċ€@              -       count occurrence of c in each of [B, A]
                                  -> i.e. X = [n_neighbours + is_existing, is_existing]
            Ḅ             -       convert from binary -> 2×n_neighbours+3×is_existing
              6,7,9       -       [6,7,9]
             e            -       exists in? -> i.e. is X in [[3,0],[3,1],[4,1]]?
                        Q - deduplicate

```

# Answer
> 2 votes
# , ~~132~~ ~~125~~ 122 bytes

```
function(x,y,n=rep(q<-x+1i*y,e=9)+-3:5%/%3+1i*-1:1,s=rowSums(outer(n,n,`==`)))list(Re(c<-unique(n[s>2&s-n%in%q<4])),Im(c))

```

Try it online!

A completely different approach to my other R answer, so posting separately.

Manipulates complex coordinates instead of filling a matrix.

Input is 2 vectors containing x- and y-coordinates of points. Output is a list containing 2 vectors of x- and y-coordinates.

**How?**

```
gol_points=
function(x,y,
q=x+1i*y,                   # convert x and y into complex coordinates q;
d=-3:5%/%3+1i*-1:1,         # create vector d of all differences to neighbouring cells:
                            #   (so, d = -1-i, -1, -1+i, -i, 0, i, 1-i  1, and 1+i)
n=q+rep(d,e=ncol(p)),       # n = coordinates of neighbouring cells,
                            #   by adding d to each element of q
s=rowSums(outer(n,n,`==`)), # s = the number of copies of each element in n
                            #   and, therefore, the number of live neighbours it has (including itself)
i=(s==3|s==4&n%in%q),       # i = indices in n of new generation of cells:
                            #   TRUE if neighbours (including self) ==3,
                            #   or if neighbours (including self) ==4 AND it's a living cell (so: in q)
c=unique(n[i]))             # c = unique set of new generation of cells
list(Re(c),Im(c))           # output list containing Real & Imaginary parts of c

```

# Answer
> 1 votes
# Jelly, 39 bytes

```
żIAṀo-4×<2$$
3Ḷ’p`+þẎẎQçⱮ³$SṪe-2,-,3Ʋ$Ƈ

```

Try it online!

This is probably really bad

# Answer
> 1 votes
# JavaScript (ES10),  ~~156~~  152 bytes

```
a=>a.flatMap(a=>g(a,b=[])+.5|0?b:[...b,a],g=(B,b,k=9)=>k--?g(B,b,k,g[A=[B[0]+k%3-1,B[1]+~-(k/3)]]|a.some(a=>k=a+''==A)|!b||g(B=A)?0:g[B]=b.push(B))-k:3)

```

Try it online!

### How?

The helper function \\$g\\$ counts the number \\$N\\$ of cells around a reference position `B[] = [x,y]`. For golfing reasons, the reference position is counted as well. The value returned by \\$g\\$ is \\$3-N\\$. Therefore:

* \\$g\\$ returns \\$0\\$ or \\$-1\\$ for a cell surrounded by \\$2\\$ or \\$3\\$ other cells respectively, which is characterized by `(g() + 0.5 | 0) == 0`
* \\$g\\$ returns \\$0\\$ for an empty position surrounded by exactly \\$3\\$ cells

When it's called with a 2nd argument `b[]`, \\$g\\$ also pushes into this array the coordinates of all cells that are currently off and must be turned on, provided that this is the first time they are encountered.

### Commented

```
a =>                          // a[] = input array
a.flatMap(a =>                // for each coordinate pairs a[] in a[]:
  g(a, b = [])                //   invoke g with an empty array b[]
  + .5 | 0 ?                  //   if the result is neither -1 or 0:
    b                         //     return b[] without a[]
  :                           //   else:
    [...b, a],                //     return b[] with a[]
  g = (                       //   g is a recursive function taking:
    B,                        //     B[] = [x, y]
    b,                        //     b[] = list of coordinate pairs
    k = 9                     //     k = counter
  ) =>                        //
    k-- ?                     //     decrement k; if it was not 0:
      g(                      //       recursive call:
        B, b, k,              //         pass B[], b[] and k unchanged
        g[                    //
          A = [               //         define the coordinates A[] of the neighbor:
            B[0] + k % 3 - 1, //           x' = x + (k mod 3) - 1
            B[1] + ~-(k / 3)  //           y' = y + floor(k / 3) - 1
          ]                   //
        ] |                   //         abort if g[A] is already defined
        a.some(a =>           //         or A[] exists in a[]
          k = a + '' == A     //         (in which case k is set to true)
        )                     //
        | !b                  //         or b is not defined
        || g(B = A)           //         otherwise, invoke g with B = A and without
        ?                     //         the 2nd argument; if the result is not 0:
          0                   //           do nothing
        :                     //         else:
          g[B] = b.push(B)    //           append B[] to b[] and set g[B]
      ) - k                   //       end of recursive call; subtract k
    :                         //     else:
      3                       //       return 3 and stop the recursion
)                             // end of flatMap()

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 70 bytes

```
l#&@@@Cases[Tally@Array[l+#+I#2&,{3,3},-1,Join],{_,3}|{#|##&@@l,4}]

```

Try it online!

Takes and returns a list of complex numbers.

# Answer
> 1 votes
# Charcoal, ~~80~~ ~~75~~ ~~48~~ 43 bytes

```
Ｆ³Ｆ³Ｆ⊕⌈↔⊖⟦ικ⟧Ｆθ⊞υ⊖Ｅμ⁺ν⎇ξκιＩΦυ∧⁼κ⌕υι›²↔⁻⁶№υι

```

Try it online! Link is to verbose version of code. Just a boring port of @Zgarb's Husk answer. Outputs points using Charcoal's default format which is each coordinate on its own line with points double-spaced from each other. Explanation:

```
Ｆ³Ｆ³

```

Loop through all neighbourhoods.

```
Ｆ⊕⌈↔⊖⟦ικ⟧

```

Loop through adjacent cells twice but the cell itself only once.

```
Ｆθ⊞υ⊖Ｅμ⁺ν⎇ξκι

```

Push all of the resulting cells to the predefined empty list.

```
ＩΦυ∧⁼κ⌕υι›²↔⁻⁶№υι

```

Print the first appearance of those cells that appear between 5 and 7 times.

Previous ~~80~~ 75-byte more Charcoal-y solution:

```
≔Ｅ²Ｅθ§λιηＵＭη…·⊖⌊ι⊕⌈ιＦθ«Ｊ⊟ι⊟ιＵＭＫＭＩ⌊⟦⁹⁺²Σκ⟧Ｉ⊕ΣＫＫ»Ｆ⊟ηＦ§η⁰«Ｊικ¿№567ＫＫ⊞υ⟦κι⟧»⎚Ｉυ

```

Try it online! Link is to verbose version of code. Outputs points using Charcoal's default format which is each coordinate on its own line with points double-spaced from each other. Explanation:

```
≔Ｅ²Ｅθ§λιη

```

Get a transposed copy of the points.

```
ＵＭη…·⊖⌊ι⊕⌈ι

```

Replace each row of the transpose with a padded range.

```
Ｆθ«

```

Loop over each point.

```
Ｊ⊟ι⊟ι

```

Jump to that point.

```
ＵＭＫＭＩ⌊⟦⁹⁺²Σκ⟧

```

Doubly increment each of the neighbours, limited to 9.

```
Ｉ⊕ΣＫＫ

```

Increment the cell.

```
»Ｆ⊟ηＦ§η⁰«

```

Loop over the padded ranges.

```
Ｊικ

```

Jump to that point.

```
¿№567ＫＫ

```

If it's between 5 and 7, then...

```
⊞υ⟦κι⟧

```

... save that point in the predefined empty list.

```
»⎚Ｉυ

```

Clear the canvas and output the new points.

# Answer
> 1 votes
# 05AB1E, 30 bytes

```
2и2Ý<©ãδ+€`D€»DI€»õ.;s¢®6+såÏê

```

Port of *@Zgarb* Husk answer, so make sure to upvote him as well.
The reason it's so much longer is due to less convenient builtins. One is that there isn't a remove\_first builtin, so we'll use a replace\_first builtin instead. In addition, the count doesn't vectorize on a list of pairs, so we have to join each string with a newline delimiter for both the replace\_first and count builtins.

Try it online or verify all test cases.

**Explanation:**

```
2и                  # Repeat the (implicit) input-list twice
                    #  i.e. [[0,0],[1,0],[2,1]] → [[0,0],[1,0],[2,1],[0,0],[1,0],[2,1]]
  2Ý                # Push list [0,1,2]
    <               # Decrease each by 1: [-1,0,1]
     ©              # Store this list in variable `®` (without popping)
      ã             # Take the cartesian product of this list with itself
                    #  → [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]]
       δ            # Apply double vectorized on the two lists:
        +           #  Add the values at the same positions in the pairs together
                    #   → [[[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]],
                    #      [[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1],[2,-1],[2,0],[2,1]],
                    #      [[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2]],
                    #      [[-1,-1],[-1,0],[-1,1],[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1]],
                    #      [[0,-1],[0,0],[0,1],[1,-1],[1,0],[1,1],[2,-1],[2,0],[2,1]],
                    #      [[1,0],[1,1],[1,2],[2,0],[2,1],[2,2],[3,0],[3,1],[3,2]]]
         €`         # Flatten it one level down to a list of pairs
D                   # Duplicate this list of pairs
 €»                 # Join each inner pair together with a newline delimiter
                    #  → ["1\n1","1\n0","1\n-1","0\n1","0\n0","0\n-1","-1\n1","-1\n0",
                    #     "-1\n-1","2\n1","2\n0","2\n-1","1\n1","1\n0","1\n-1","0\n1",
                    #     "0\n0","0\n-1","3\n2","3\n1","3\n0","2\n2","2\n1","2\n0",
                    #     "1\n2","1\n1","1\n0","1\n1","1\n0","1\n-1","0\n1","0\n0",
                    #     "0\n-1","-1\n1","-1\n0","-1\n-1","2\n1","2\n0","2\n-1","1\n1",
                    #     "1\n0","1\n-1","0\n1","0\n0","0\n-1","3\n2","3\n1","3\n0",
                    #     "2\n2","2\n1","2\n0","1\n2","1\n1","1\n0"]
   D                # Duplicate this list of strings
    I               # Push the input list of pairs
     €»             # Join each inner pair with a newline delimiter as well
                    #  → ["0\n0","1\n0","2\n1"]
       õ.;          # Replace every first occurrence of the input-pair with an empty string
                    #  → ["1\n1","","1\n-1","0\n1","","0\n-1","-1\n1","-1\n0",
                    #     "-1\n-1","","2\n0","2\n-1","1\n1","1\n0","1\n-1","0\n1",
                    #     "0\n0","0\n-1","3\n2","3\n1","3\n0","2\n2","2\n1","2\n0",
                    #     "1\n2","1\n1","1\n0","1\n1","1\n0","1\n-1","0\n1","0\n0",
                    #     "0\n-1","-1\n1","-1\n0","-1\n-1","2\n1","2\n0","2\n-1","1\n1",
                    #     "1\n0","1\n-1","0\n1","0\n0","0\n-1","3\n2","3\n1","3\n0",
                    #     "2\n2","2\n1","2\n0","1\n2","1\n1","1\n0"]
          s         # Swap so the other list of strings is at the top of the stack again
           ¢        # Count the amount of occurrences of each item
                    #  → [6,3,4,4,3,4,2,2,2,3,4,2,6,5,4,4,3,4,2,2,2,2,3,4,2,6,5,6,5,4,4,
                    #     3,4,2,2,2,3,4,2,6,5,4,4,3,4,2,2,2,2,3,4,2,6,5]
            ®       # Push list [-1,0,1] from variable `®`
             6+     # Add 6 to each: [5,6,7]
               s    # Swap so the list of counts are at the top of the stack
                å   # Check for each count if it occurs in the [5,6,7] list
                    #  → [1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,
                    #     0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,1,1]
                 Ï  # Only keep the pairs at the truthy indices
                    #  → [[1,1],[1,1],[1,0],[1,1],[1,0],[1,1],[1,0],[1,1],[1,0],[1,1],[1,0]]
                  ê # Sort and uniquify the remaining pairs
                    #  → [[1,0],[1,1]]
                    # (after which the result is output implicitly)

```

---
Tags: code-golf, grid, game-of-life
---