title: A rainbow of identity functions

text:
# Question
Title: A rainbow of identity functions
Closely related: How high can you count?

## Challenge

In your programming language of choice, write as many different identity programs/functions as possible, under the following constraints:

* Each program should be a function or full program that is one of the following:
    + A function that takes a single positive integer and returns it unchanged
    + A function that takes a single string of printable ASCII (codepoints 32 to 126 inclusive) and returns it unchanged
    + A full program that takes a single positive integer from stdin and prints to stdout unchanged, with an optional trailing newline (and possibly other outputs that cannot be suppressed in your language)
    + A full program that takes a single line of printable ASCII from stdin and prints to stdout unchanged, with an optional trailing newline (and possibly other outputs that cannot be suppressed in your language)
* Different programs using different I/O methods is acceptable.
* **Any single byte cannot appear in two or more programs**, though it may appear more than once in a single program. You may freely use multi-byte characters, as long as every byte value consisting of each multi-byte character follows this exact rule.
* The programs must be independent of each other.
* If an empty program satisfies the condition above, you can include it only once in your answer.
* Symbol independent languages such as Lenguage (including partially independent ones such as Headsecks) are disallowed.
* If your language accepts flags, all programs in an answer must use a single combination of flags (e.g. one answer for "Keg" programs without flags, a separate answer for "Keg `-hr`" programs). According to this meta, a language with different flag combination is a different language.

## Examples

In Python 3, all of `lambda a:a`, `print(input())`, `int`, and `str` are valid identity programs independently, but only two of them can be used in an answer since the last three programs share the character `t`.

## Scoring

The submission with the largest number of programs wins.

# Answer
# 05AB1E, ~~130~~ ~~133~~ ~~144~~ ~~148~~ ~~150~~ ~~151~~ ~~155~~ ~~156~~ ~~157~~ 159 programs

Uses the custom 05AB1E encoding for all programs.
All programs are a TIO-link to verify them.

**Either type of input is fine:**

1) (empty program): Implicit input is output implicitly
2,3) (a space), `\n` (a newline): The whitespaces are ignored; implicit input is output implicitly (with trailing newline)
4) `w`: Unbound no-op; implicit input is output implicitly (with trailing newline)
5) `I`: Explicit input is output implicitly (with trailing newline)
6) `¹`: Explicit first input is output implicitly (with trailing newline)
7) `$`: Push 1 and the input, after which the top input is output implicitly (with trailing newline)
8) `Î`: Push 0 and the input, after which the top input is output implicitly (with trailing newline)
9) `,`: Implicit input is output explicitly with trailing newline
10) `=`: Implicit input is output explicitly with trailing newline (without popping)
11) `?`: Implicit input is output explicitly without trailing newline
12) `q`: Exit program; implicit input is output implicitly (with trailing newline)
13,14) `D`, `Ð`: Duplicate / triplicate the implicit input and output the top implicitly (with trailing newline)
15) `r`: Reverse the values on the stack (which is empty); implicit input is output implicitly (with trailing newline)
16,17) `s`, `Š`: Swap / triple swap two / three implicit inputs; the top is output implicitly (with trailing newline)
18) `Δ`: Loop until the result no longer changes; the implicit input is used, it loops twice, and the unmodified input is output implicitly (with trailing newline)
19) `:`: Replace the implicit input-string with the implicit input-string, after which the unmodified input is output implicitly (with trailing newline)
20,21,22,23) `J`, `»`, `O`, `P`: Join the empty stack without delimiter / join the empty stack with newline delimiter / sum the empty stack / take the product of the empty stack, after which the implicit input is output implicitly (with trailing newline)
24,25) `U`, `V`: Pop the implicit input, and store it in variable `X` or `Y` respectively, after which the implicit input is output implicitly (with trailing newline)
26) `©`: Store the implicit input in variable `®` (without popping), after which it is output implicitly (with trailing newline)
27) `ˆ`: Pop the implicit input, and add it to the global array, after which the implicit input is output implicitly (with trailing newline)
28) `i`: If-statement, if the (implicit) input is 1 it enters it. But whether the input is 1 and it enters the if-statement or not, the implicit input is output implicitly (with trailing newline) either way
29) `v`: For-each over each character/digit of the implicit input (but don't push any, since we don't use `y`). After the loop, the implicit input is output implicitly (with trailing newline)
30,31) `}`, `]`: Close the inner-most or all if-statement(s)/loop(s), for which there are none right now. The implicit input is output implicitly (with trailing newline)
32) : Filter the implicit input to the front of the implicit input; it will remain unmodified and is output implicitly (with trailing newline)
33) : Transliterate the characters of the implicit input to the characters of the implicit input; it will remain unmodified and is output implicitly (with trailing newline)
34) `´`: Clear the global array (which is already empty). After which the implicit input is output implicitly (with trailing newline)
35) `§`: Cast the implicit input to a string, after which it is output implicitly (with trailing newline)
36) `Ã`: Keep all values of the implicit input in the implicit input, after which the unmodified result is output implicitly (with trailing newline)
37) `é`: Sort the implicit input by length. Since it's a single string/integer, the characters/digits will remain at the same position, after which the unmodified input is output implicitly (with trailing newline)
38,39) `.`, `Å`, `ž`: All three are used to open up more 2-byte operations, but on their own they're unbound no-ops. So the implicit input is output implicitly (with trailing newline).
40) `\`: Discard the top item on the stack (which is already empty), after which the implicit input is output implicitly (with trailing newline)
41) `¼`: Increase the counter\_variable by 1. After which the implicit input is output implicitly (with trailing newline)
42) `½`: If the implicit input is `1`, increase the counter\_variable by 1. After which the implicit input is output implicitly (with trailing newline)
43) `ë`: Else-statement, which is a no-op without if-statement. So the implicit input is output implicitly (with trailing newline)
44) `ÿ`: Used for string interpolation; outside of a string it's a no-op. So the implicit input is output implicitly (with trailing newline)
45) `šн`: Convert the implicit input implicitly to a character-list, and prepend the implicit input at the front. Then pop and push the first item of this list, which is output implicitly (with trailing newline).
46) `ªθ`: Convert the implicit input implicitly to a character-list, and append the implicit input at the end. Then pop and push the last item of this list, which is output implicitly (with trailing newline).
47) `η¤`: Get all prefixed of the implicit input. Push its last item (without popping), after which the top of the stack is output implicitly (with trailing newline).
48) `ðý`: Join the empty stack with space delimiter, after which the implicit input is output implicitly (with trailing newline).
49) `õK`: Remove all empty strings from the implicit input, after which the unmodified result is output implicitly (with trailing newline).
50) `¸``: Wrap the implicit input into a list, and then pop and dump the contents of that list to the stack, after which it is output implicitly (with trailing newline)
51) `ʒX`: Start a filter, and push variable `X`, which is 1 (truthy) by default. So all characters/digits in the implicit input will remain, and the unmodified input is output implicitly (with trailing newline)
52) `RR`: Reverse the implicit input, and reverse it back. After which the unmodified input is output implicitly (with trailing newline).
53) `ÂÂ`: Bifurcate (short for Duplicate & Reverse copy) twice, after which the unmodified input at the top of the stack is output implicitly (with trailing newline)
54) `ÁÀ`: Rotate the implicit input once towards the right, and then back towards the left. After which the unmodified input is output implicitly (with trailing newline).
55) `Ć¨`: Enclose the implicit input, appending its own first character/digit, and then remove the last character/digit again. After which the unmodified input is output implicitly (with trailing newline).
56) `Σ9`: Sort the characters/digits in the implicit input by 9 (so they'll all stay at the same positions), after which the unmodified input is output implicitly (with trailing newline).
57) `8ì¦`: Prepend an `8` in front of the implicit input, and then remove the first character again. After which the unmodified input is output implicitly (with trailing newline)
58) `āĀÏ`: Push a list in the range \[1, implicit input-length\] (without popping). Python-style truthify each value in this list (so they'll all becomes 1s). Only keep the characters/digits of the implicit input at the truthy (1) indices, after which the unmodified result is output implicitly (with trailing newline).
59) `""«`: Append an empty string to the implicit input, after which the unmodified input is output implicitly (with trailing newline).
60,61) `‘‘Û`, `’’Ü`: Trim all leading / trailing empty strings of the implicit input, after which the unmodified input is output implicitly (with trailing newline).
62) `““¡`: Split the implicit input on an empty string, after which the unmodified input is output implicitly (with trailing newline).
63) `₆¢`: Count the amount of 36 in the implicit input. Not sure why, but when using a multi-character value with the count, there seems to be a bug and it results in the unmodified string, instead of the actual amount of `36` substrings in the string I was expecting.. So this will output the unmodified input implicitly (with trailing newline).

**Only string input:**

64 through 125) `ǝαβив!%&(*+-/÷;<>BLbcefhjmnoptxz~‰£°±·¿ÃÆÈÉÌÍÑÒÓÕÖ×ØÝãäçèîôöùú`: All these are integer operations (see the Wiki-page linked in the title to see what each does). They are no-ops for the (implicit) input-string(s); after which the unmodified input at the top of the stack is output implicitly.
126) : Extend/shorten the implicit input-string to a size equal to the implicit input-string, after which it is output implicitly (with trailing newline).
127) `δ`: Apply double-vectorized. For integer inputs, it will implicitly convert to a \\$\[1, a\]\\$ range before applying double-vectorized. For strings, the implicit input is output implicitly.
128) `Λ`: Apply the Canvas with three options. For the digits `0` through `7`, it will output the digit in a certain direction and length, depending on the input. For any other input, it will be a no-op outputting the implicit input implicitly (with trailing newline).
129) : If the top of the stack is `1`, it will print index `N`. So this will output `0` for input `1`, but will output the implicit input itself implicitly (with trailing newline) for any other input.
130) : If the top of the stack is `1`, it will print item `y`. So this will output an empty string for input `1`, but will output the implicit input itself implicitly (with trailing newline) for any other input.
131) `œW`: Get all permutations of the implicit input-string. Then push the minimum (without popping), which for string inputs will simply use the very first string. Then output this unmodified input at the top of the stack implicitly (with trailing newline).

**Only string input, and the output is a character-list:**

132) `S`: Convert the implicit input to a list of characters and output it implicitly (with trailing newline).
133,134) `ε`, : Map over each character in the implicit input, and output the resulting character-list implicitly (with trailing newline).
135) : Push the length of the implicit input. Uninterleave the implicit input using this length as block-size. After which the resulting character-list is output implicitly (with trailing newline).
136) `øøø¬`: Zip/transpose three times; swapping rows/columns. If it's a matrix, it will do as expected. If it's a string or list, it will use the implicit input as a pair-and-zip/tranpose. Since we're doing it three times, the following will happen: `"abc"``["aa","bb","cc"]``[["a","aa"],["b","bb"],["c","cc"]]``[["a","b","c"], ["aa","bb","cc"]]`. Then we'll push the first inner list (without popping), after which this list at the top of the stack is output implicitly (with trailing newline).
137) `ü1`: `ü` is the overlapping builtin. It can be used with any other builtin to execute that builtin on every overlapping pair. But it can also be used with a single digit to create overlapping pair (2), triplets (3), quartets (4), etc. Apparently it also works with 1 to just convert the (implicit) input-string into a character-list, which is output implicitly (with trailing newline).

**Only character-list input:**

138) `í`: Reverse each character in the implicit input-list, after which the unmodified input-list is output implicitly (with trailing newline).
139) `˜`: Flatten the implicit input-list, after which the unmodified input-list is output implicitly (with trailing newline).
140) `ζζΩ`: Zip/transpose the (implicit) input-list twice: `["a","b","c"]``[["a","a"],["b","b"],["c","c"]]``[["a","b","c"],["a","b","c"]]`. And then pop and push a random item of this list of lists, which are both the unmodified input-list. After which it will be output implicitly (with trailing newline).

**Only integer input:**

141,142,143,144) `E`, `F`, `G`, `ƒ`: Start a ranged loop with the implicit input (`E` = \\$\[1, a\]\\$; `F` = \\$\[0, a)\\$; `G` = \\$\[1, a)\\$; `ƒ` = \\$\[0, a\]\\$), and output the implicit input implicitly (with trailing newline) afterwards.
145) `ï`: Convert the implicit input to an integer, after which the unmodified input is output implicitly (with trailing newline).
146) `ò`: Round to the nearest integer (which it already is), after which the unmodified input is output implicitly (with trailing newline).
147) `þ`: Only keep the digits of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
148) `#`: Split the implicit input-integer by spaces (it has none), after which the unmodified input is output implicitly (with trailing newline).
149,150,151) `u`, `l`, : Convert the implicit input-integer to uppercase / lowercase / titlecase, after which the unmodified input is output implicitly (with trailing newline).
152) `¶м`: Remove all newline characters of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
153) `‚ß`: Pair the implicit input-integer with the implicit input-integer, and then pop and push its minimum. After which it is output implicitly (with trailing newline).
154) : Trim leading and trailing lowercase alphabets of the implicit input-integer, after which the unmodified input is output implicitly (with trailing newline).
155) `|M`: Push all inputs as list. Push the largest value on the stack (including in all inner lists/matrices). After which the top of the stack is output implicitly (with trailing newline).
156) `∞@0k`: Push an infinite positive list \[1,2,3,...\]. Check for each value if the (implicit) input is larger than or equal to this value (1 if truthy; 0 if falsey). And then get the 0-based index of the first 0 in this infinite list. After which it is output implicitly (with trailing newline).
157) `µ¾Ê`: Continue looping until the counter\_variable (default 0) is equal to the implicit input-integer. Push the counter\_variable each iteration, and check that it's NOT equal to the implicit input-integer. If this is truthy, the counter\_variable will implicitly be increased by 1 after every iteration. When it becomes falsey, it means it's equal to the input-integer, and thus the loops stops, after which the counter\_variable is output implicitly (with trailing newline) as result.
158) `Œà`: Push all substrings of the implicit input-integer, and then pop and push its maximum. After which this top of the stack is output implicitly (with trailing newline).
159) `Z)Z`: Get the largest digit of the implicit input-integer (without popping). Then wrap all values on the stack into a list, which is the input itself and its max digit. And then get the maximum again of this integer-pair (without popping), which will be the input itself. Then output the input at the top of the stack implicitly (with trailing newline).

**Unused characters / builtins:**

I'm pretty sure nothing useful is left anymore now..

```
Integer constants: 234567Tт₁₂₃₄₅Y®N•
Empty list constant: ¯
Empty string constant (if used twice): ”
(Partially) uniquify / sort builtins: Ù{êÔγ
Convert from binary/hexadecimal to integer (which works on any input unfortunately): CH
Checks resulting in truthy/falsey (0/1): Θ≠Qad›‹Ëå
Recursive environment (which I can't close without `}` nor `]`): λ
Infinite loop (which I can't stop without `#` nor `q`): [
(Compressed) string/integer builtins, which result in errors on their own: '„…ƵŽ
Ord (convert to codepoint integers): Ç
Convert to a list and cycle infinitely: Þ
Only leave the letters (which won't work if the input contains anything else): á
Get the second or third input (we are only allowed to take a single input): ²³
Palindrome / mirror: ûº
Cartesian product: â

```
> 19 votes

# Answer
# perl -pe, 85 86 87 programs

```
perl -pe 000
perl -pe 111
    ...
perl -pe 999

perl -pe aaa
perl -pe bbb
    ...
perl -pe zzz

perl -pe AAA
perl -pe BBB
    ...
perl -pe ZZZ

perl -pe '__'
perl -pe '$$'
perl -pe '%%'
perl -pe '@@'
perl -pe ';;'
perl -pe '**'
perl -pe '##'
perl -pe '""'
perl -pe "''"
perl -pe '``'
perl -pe '//'
perl -pe '::'
perl -pe '??'    #  Only if your perl is old enough (pre 5.22)

perl -pe '  '    #  Spaces (or tabs, or newlines, etc)

perl -pe '()'
perl -pe '[]'
perl -pe '<>'
perl -pe '{}'

perl -pe '\&\'

perl -pe ''      #  Empty program

```

They all copy their input to output.

## How does it work?

`perl -pe` reads the input line by line, and executes the given program, where `$_` contains the read line. After executing the program, it prints whatever is left in `$_`. None of the given programs modify `$_`, all statements are just noops.

In short, all digits, all upper case letters and all but 3 lower case letters can used single (or double, triple, etc). They're either numbers or strings in void context. Since `m`, `s`, and `q` used single may be commands, (and for `q`, this is also the case when used double), using them all as triples will do.

Many other characters can be used, sometimes single, or otherwise double. But if we can use them single, double will work too, hence we used doubles. `__` is just a string. `$$`, `@@`, `%%`, and `**` are variables. `;;` are two command separators. `""` is an empty string, and so is `''`. Double backticks just execs a empty command. `##` is a comment. `::` is an alternative way of spelling the package `main`. `//` is an empty regexp. `??` is the weird regexp operator you never needed, or probably never knew about (it repeats the last successful match).

Any of the whitespace characters (space, newline, tab, etc) can use used as well.

This leaves a few characters I could not use by themselves, and I had to pair them with another: `[]` is an empty array. `()` is an empty list. `<>` reads line from the input. `{}` is an empty block.

`\&\` is a reference to (non-existing, but Perl is fine with that) subroutine named `\`.

And of course, the empty program qualifies as well (thanks to David G. for pointing that out).

This leaves `!`, `+`, `,`, `-`, `.`, `=`, `^`, `|`, `~` as an exercise for the reader.

That's 10 (digits) + 52 (lower + upper case letters) + 6 (white space) + 13 (other characters used by themselves) + 5 (programs with 2 different characters) + 1 (empty program) = 87 programs.
> 11 votes

# Answer
# R, ~~11~~15 programs

This is a very interesting challenge for R, we get to use lots of different features of the language!

firstly, in R, any expression that isn't assigned somewhere is printed by default, so the empty program counts (it will return an integer unchanged, for example)

`c` can be treated as a function of one argument that will return it unchanged.

`I` adds a class attribute, but this does not affect the printing.

`t` will return its argument as a 1x1 matrix (I hope this counts as "unchanged" for the purposes of the problem).

`min` will return its argument unchanged if that is a single integer.

`as.raw` will return a hexadecimal integer unchanged (from my reading of the problem, I *think* that's acceptable.)

`+` as a unary function of one integer will return it unchanged.

`1*` as a program will then generate a prompt for the second argument: entering it will return the entered integer unchanged.

`--`, similarly to `1*`, will generate a prompt for a number which is then negated twice and therefore printed unchanged. (Edit: `T%x%` will do the same, taking the Kronecker product of the entered number with `TRUE==1` --- thanks Robin Ryder)

\`(\` and `'{'` both return their argument (they are formal functions in R). They need the quotes to function, but luckily R lets you use different kinds of quotes.

`"\u73\u75\u6D"` will also work as a function; the escapes evaluate to "s", "u" and "m" respectively which gives `sum`, which will return its argument unchanged if it is a single integer.

Lastly, everyone always forgets about complex numbers but `Re` and `Mod` will return the real part and modulus of the argument respectively. If that argument is a positive integer then they are no-ops.

Thanks to Giuseppe for the `min` and brackets ideas and to Robin Ryder for some other suggestions!
> 7 votes

# Answer
# Charcoal, ~~12~~ 15 programs

Edit: Added three more programs which are no-ops only on numeric input.

Try it online! Lowercases the implicit input, which has no effect for numeric input.

Try it online! Uppercases the implicit input, which has no effect for numeric input.

```
θ

```

Try it online! Link is to verbose version of code. Prints the default input.

Try it online! Link is to verbose version of code. Prints the explicit string input.

Try it online! Link is to verbose version of code. Prints the explicit input.

```
ＩＮ

```

Try it online! Link is to verbose version of code. Casts the explicit numeric input to string so that it can be printed.

```
∨⁰

```

Try it online! Prints the logical OR of 0 and the implicit input.

```
∧χ

```

Try it online! Prints the logical AND of 10 and the implicit input.

```
⮌⮌

```

Try it online! Prints the implicit input reversed twice.

```
⁺ω

```

Try it online! Prints the empty string concatenated with the implicit input.

```
×¹

```

Try it online! Prints the implicit input repeated once.

```
﹪%s

```

Try it online! Formats the implicit input as a string.

```
⊟⊞Ｏυ

```

Try it online! Pushes and pops the implicit input to a list before printing it.

```
⎇℅ψφ

```

Try it online! Prints the implicit input if the null byte's ordinal is zero.

```
⭆⊖²⊖⊕

```

Try it online! Increments and decrements one implicit (numeric) input, then joins the results together.
> 6 votes

# Answer
# Brachylog, 88 programs

I doubt this is the longest I can get it, as I'm only posting this now because I need to take a break from making more of these, and if character lists are admissible for strings I know this can be expanded even further. The reason so many one-character solutions exist is that Brachylog has a lot of variables, constraint predicates, and flow control commands, plus a fair number of nondet predicates that happen to have the exact input as their *first* output.

1. The empty program, for integers or strings.

2 - 27. Any uppercase ASCII letter, for integers or strings.

28. `İ` for integers.

29.  for strings.

30 - 42. Any one of `ȦḂḞĠḢṄṖṘẆẊẎŻ`, for integers or strings.

43. A space, for integers or strings.

44. A newline, for integers or strings.

45. `?`, for integers or strings.

46. `.`, for integers or strings.

47. `&`, for integers or strings.

48. `|`, for integers or strings.

49. , for integers.

50. `w`, printing an integer from stdin.

51. , printing an integer from stdin with a trailing newline.

52. `p`, for strings.

53. `s`, for strings.

54. , for integers or strings.

55. `!`, for integers or strings.

56. A backtick, for integers or strings.

57. , for strings.

58. , for strings.

59. `()`, for integers or strings.

60. `{}`, for integers or strings.

61. `↔↔`, for strings.

62. `↺↻`, for strings.

63. `∈h`, for strings.

64. , for strings.

65. `ṅṅ`, for integers.

66. `gṛ`, for integers or strings.

67. , for integers. (can't believe I forgot this earlier, but I can't be bothered to renumber everything)

68. `ḋ×`, for integers.

69. `+₀`, for integers.

70. , for integers. (I didn't notice the restriction to positive!)

71. `ȧ`, for integers. (again, specifically positive)

72. `ṫị`, for integers.

73. `ċ₂`, for strings.

74. `÷↙Ḋ`, for integers.

75. `ḅc`, for strings.

76. `<<<-₃`, for integers.

77. , for strings.

78. `f⌉`, for integers.

79. `dᵗ`, for strings.

80. `=ᵐ`, for strings.

81. `≠ˢ`, for strings.

82. `;1/`, for integers.

83. `^₁`, for integers.

84. `jḍt`, for strings.

85. `~⌋⌋`, for integers or strings.

86. `⟦bl`, for integers.

87. `⟧k∋ᶜ`, for integers.

88. , for integers.
> 6 votes

# Answer
# Brain-Flak, 252 programs

The first 5 programs are:

```
[]
()
<><>
#{}

```

and the empty string. These programs have 9 unique characters total.

Each of the remaining 247 programs consist of an individual byte other than `(){}<>{}#`.

## How?

In brain-flak, an empty program prints it's input. Any character other than `#(){}[]<>` has no affect on the behavior of the program.

Try it online!
> 6 votes

# Answer
## Haskell, ~~5~~ 6 programs

### 1:

```
id

```

Haskell has an identity function, so that is a good start. It uses `i` and `d` which are not terribly valuable anyway.

### 2:

```
k x=x

```

A simple definition of an identity. It uses `=` which is going to make it hard for us to define any new functions (instead we will have to build them). And it also uses the space which is would be useful otherwise.

### 3:

```
\z->z

```

This is a lambda of the last version. This marks the end of the straight forward identities.

### 4:

```
(*1)

```

Multiplies the input by 1, which is an identity for members of the `Num` class. This uses up the very valuable parentheses.

### 5:

```
abs

```

As pointed out by H.PWiz since the input is positive `abs` is an identity

### 6:

```
fromEnum

```

This is an identity on integers.

---

At this point we still have a lot of room we could use `<$>` or `$` (replacement for space or parentheses), however I can't get anything to fit the `t` in `Just` is a problem for things like `subtract`, `const` and `repeat` which would be useful.
> 6 votes

# Answer
# APL (dzaima/APL), 38 functions/programs

The code to be counted is parenthesised below. The first two entries are full programs, the rest are tacit prefix functions, except `{⍵}` which is a prefix lambda.

```
(⎕) ⍝ prompt for numeric input and implicitly print it
(⍞) ⍝ prompt for string and implicitly print it
(⍮)I ⍝ 1-element with (no visual difference on simple scalar)
(⌷)S ⍝ materialise (no-op on anything but certain objects)
(∧)I ⍝ LCM reduction (no-op on scalar)
(∨)I ⍝ GCD reduction (no-op on scalar)
(⌽)I ⍝ mirror (no-op on scalar)
(⍉)I ⍝ transpose (no-op on scalar; TIO's version has a bug that has since been fixed)
(⊖)I ⍝ flip (no-op on scalar)
(+)I ⍝ complex conjugate (no-op on real number)
(∊)S ⍝ enlist (no-op on strings)
(↑)S ⍝ mix (no-op on simple arrays)
(↓)I ⍝ split (no-op on simple scalars)
(⊢)S ⍝ identity
(⊣)S ⍝ identity
(⌈)I ⍝ ceiling (no-op on integer)
(⌊)I ⍝ floor (no-op on integer)
(⍕)I ⍝ stringify (no-op on string)
(⊂)I ⍝ enclose (no-op on simple scalar)
(⊃)I ⍝ first (no-op on simple scalar)
(∪)I ⍝ unique (no-op on simple scalar)
(|)I ⍝ absolute value (no-op on positive numbers)
(,)I ⍝ ravel (no-op on strings)
(⍪)I ⍝ table (no visual difference on scalars)
(⍷/)I ⍝ use find (arbitrary otherwise unused function) to reduce (no-op on scalar)
(1⌿)S ⍝ replicate all elements to 1 copy each (no-op on string)
(9○)I ⍝ real part (no-op on real number)
(⍟*)I ⍝ natural logarithm of e to the power
(⍬,)S ⍝ prepend the empty list (no-op on string)
(⊥⊤)I ⍝ the base-2 evaluation of the base-2 representation
(--)I ⍝ negate the negation
(÷÷)I ⍝ reciprocate the reciprocal
(~∘8)S ⍝ remove all occurences of number 8 (no-op on string)
({⍵})S ⍝ user-defined identity function
(!⍣0)I ⍝ apply the factorial zero times
(''⍴)I ⍝ reshape to 0D (no-op on scalar)
(.5×2×)I ⍝ half the double
(⍳∘≢⍛⊇⍨)S ⍝ use all the indices to permute the argument (this one is supposed to say ⍤ instead of ∘ but TIO isn't updated)
```

Try it online!
> 6 votes

# Answer
# Husk, 1 program + 24 functions

Programs:

1. `ḟ=⁰N` \- Find an element that equals the last command-line argument in the infinite list of natural numbers. Try it online

Functions:

1. `I` \- the identity function
2. `+0` \- Add 0
3. `*1` \- Multiply by 1
4. \- Double and then halve
5. `ĠK` \- Scan right without an initial value. The `K` combinator just discards the second argument, so the list remains the same.
6. `←;` \- Make a singleton list, then get the first element. Try it online
7. `__` \- Negate twice
8. \- Ceiling (identity for integers)
9. \- Floor (identity for integers)
10. `i` \- Round (identity for integers)
11. `a` \- Absolute value (identity for positive numbers)
12. `√□` \- Square root of square
13. ```` \- Swap arguments of binary function twice
14. `\\` \- Reciprocal twice (Try it online!)
15. `LR"3"` \- Repeat `"3"` `n` times, then take the length, giving back n. Can be something other than 3
16. \- Remove the empty list (Try it online!)
17. `cc` \- Convert integer to character, convert character back to integer
18. `dd` \- `d` can both get the base 10 digits or interpret digits in base 10
19. \- Bitwise and with itself
20. \- Prepend default value, then get tail
21. `s` \- Show (for strings)
22. `↔↔` \- Swap pair/reverse list/reverse digits twice
23. `!4∞` \- Get fourth (arbitrary) element of infinite list of copies of argument
24. `ΣC2` \- Cut into sublists of size 2, concatenate them (for lists of size \> 1)
> 6 votes

# Answer
# Stack Cats, 19 programs

All programs that are exactly mirrored in Stack Cats function exactly as cat programs. Therefore, we can score one program for each valid symmetric character by having there be two of them, and we can score one program for each pair of matching characters. These character sets are:

```
!"*+-:=ITX^_|
(){}[]<>\/

```

Unfortunately, most other characters cause syntax errors in the existing interpreters. However, the empty program is also symmetric, so it also produces a cat program.

Sample symmetric program:

```
II

```

Try it online!

Sample matching program:

```
{}

```

Try it online!

Empty program example:

Try it online!
> 5 votes

# Answer
# AWK, ~~21~~ ~~22~~ ~~24~~ ~~25~~ ~~26~~ 27 programs

*Edit: thanks to Abigail for duplicate-letter-spotting, for the suggestion that led to `l^l`!, and for ~~+2~~ +3 more programs; and thanks to cnamejj for +1 program*

Awk will print the input line by default if a condition evaluates to TRUE.

non-zero values that evaluate to TRUE:

```
1
2
3
4
5
6
7
8
9

```

experessions that evaluate to TRUE:

```
$0 # only if input is not equal to the digit zero (so Ok for positive integer)
a~a
c==r
d---d
++f
!h
"j"
'k'
//
m^m
q**q

```

built-in variables that evaluate to TRUE:

```
NR
OFMT
SUBSEP

```

functions that evaluate to TRUE

```
log
exp
int i
sub(v,v)

```

Try it online!
> 5 votes

# Answer
# Ruby, 4 programs

```
->x{x}

```

The basic stabby lambda form. Try it online!

```
def f e;e;end

```

The classic way of defining functions in Ruby. Try it online!

```
puts(ARGF.to_a.sum(""))

```

Takes the input stream `ARGF` (points to STDIN if no program arguments are present), turns it into an array, combines it again (using `sum` because `join` shares an `n` with the previous program) and outputs it. Try it online!

```
b=*$<
STDOUT<<b*''

```

`$<` is an alias for `ARGF`. Same as above, but uses the splat operator `*` to turn it into an array, and joins it using the array join operator `*`. Try it online!
> 4 votes

# Answer
# Python 3, 4 programs

Python turned out to be much harder than I thought, with only 4 so far.

```
int
abs
repr
(1).__mul__

```

Try it online!
> 4 votes

# Answer
# Keg, `-hr`, `-lp` 17 programs

There'll be more soon.

```
#

```

Try it online!

```
,

```

Try it online!

```
.

```

Try it online!

Try it online!

```
0+

```

Try it online!

```
1*

```

Try it online!

```
¿

```

Try it online!

Try it online!

```
∑)

```

Try it online!

```
:

```

Try it online!

```
"

```

Try it online!

```
±±

```

Try it online!

Try it online!

```
;⑨

```

Try it online!

```
⑵½

```

Try it online!

```
④_

```

Try it online!

```
⑩᠈

```

Try it online!
> 3 votes

# Answer
# Scala, 9 functions

```
x=>x

```

A lambda function.

```
math.abs

```

A utility function from the math package.

For the following functions, we use the fact that methods on objects can be converted to functions if no arguments are given.

```
1*
0+
2-2|      // bitwise or with (2-2)
~(8&4)&   // bitwise and with ~(8&4)
3^3^      // bitwise xor with (3^3)
Nil:::    // concat with an empty sequence

```

```
_ ##

```

Here, the underscore is syntactic sugar for a lambda argument. It calls the method `##` on it, which calculates a hash code, but is an identity function for integers.
> 3 votes

# Answer
# Brainetry, 1 program

1 is the maximum score attainable by the Brainetry programming language. The programs below are cat programs, they take any user input and output it unchanged.

```
a b c d e f
a b c d e f g h
a b c d e f g
a b c d e f
a b c d e f g h i

```

Brainetry is partially symbol independent but it needs spaces to understand what instruction each line refers to, so a program with no spaces can only be composed of empty lines and lines with one word, corresponding to the `«` and `»` instructions, which are not useful for this challenge.

The program above was golfed from this other program:

```
This program you are currently reading
has the particularity of explaining itself. In fact,
this program has one simple mission :
Take some input provided by you
and throw it right back at your face !!!

```
> 3 votes

# Answer
# PHP, 6 programs (functions)

```
abs
fn($n)=>$n
iNtvAl
chop
HeBreV
TRIm

```

Try it online!

We're taking advantage of PHP looseness about functions lower/upper case and types (all these fall into first case: taking an integer and return it unchanged), still searching for more
> 2 votes

# Answer
# Clojure, 8 functions

They are:

```
+
*
/
->
do
max
str
(fn[n]n)

```

Arithmetic operations in Clojure are variadic functions that when given only one argument return it unchanged, and thus work as identity functions for numerics.

Minus is an exception, because with one argument it becomes unary negation. But in its place we can use threading macro `->`, which with no further functions to apply returns the supplied value as is.

`do` is a special form that is normally used to group several expressions into one and returns the value of the last one (in our case - the only one).

`max` of one entry is obviously equal to the entry itself.

`str` converts the argument to string, and so is the identity for strings.

Finally, the last one is an explicitly written out identity function.

Many important letters are now exhausted, and with `()` used up we aren't going anywhere further in a Lisp. I haven't included several other possible functions because they collide with those above:

```
identity
min
and
or

```
> 2 votes

# Answer
# Rust, 2 functions

```
|x|x
i8::abs

```

Sadly, the colon is needed for all other ways to define a function.
> 2 votes

# Answer
# J, 13 functions

## Either

`[` and `]` return their arguments.

`>` removes their argument from a box. Strings and integers don't have boxes.

## Rank 0 Array

(characters or integers)

`=/` acts on a more than length 1 array. Rank 0 arrays are always length 1.

## Positive Integers

`|` is magnitude, which is `abs(x)` in Python. Does nothing for positive integers.

`+` is complex conjugate, which negates the imaginary part.

`----` negates the number 4 times.

`%%%%` takes the reciprocal of the number 4 times.

`**` is a hook that becomes `y*(*y)`. For positive integers, `*y` always returns 1. That means `(**)y` is `y*1`.

`^#` is a hook that becomes `y^(#y)`. For rank 0 arrays, `#y` always returns 1. That means `(^#)y` is `y^1`.

`<.` rounds down a number to the nearest integer. The nearest integer from an integer is the integer itself.

`1&!` returns how many ways you can pick 1 ball from a bag of `y` balls, which is `y`.

`0}~` works.
> 2 votes

# Answer
# Zsh, 4 functions/math functions

```
()((argv))                 # bind as a math function
int                        # math function from zsh/mathfunc
echo -E - $@               # string arg to stdout
<&0                        # stdin to stdout

```

Try it online!

This is with `zmodload zsh/mathfunc` for `int`.

This is not the only combination of 4 functions, but it is the shortest set I found that only uses a single `zsh/mathfunc` function.

Either `echo` or `print` can use `$'\xHH'` notation to replace conflicting characters, in which case `ceil` can also be substituted in place of `int`.
> 2 votes

# Answer
# Vyxal, 108 bytes, 67 answers

1. (Empty) Try it Online!
2. (Space) Try it Online!
3. (Newline) Try it Online!
4. `#` Try it Online!.
5. `?` Try it Online!.
6. `_` Try it Online!.
7. `:` Try it Online!.
8. `D` Try it Online!.
9. Try it Online!.
10. `£` Try it Online!.
11. Try it Online!.
12. Try it Online!.
13. Try it Online!.
14. `¤j` Try it Online!
15. `÷Ṡ` Try it Online!.
16. `1/` Try it Online!.
17. Try it Online!
18. `¹` Try it Online!
19. Try it Online!
20. `ƒh` Try it Online!
21. `²√ṙ` Try it Online!
22. `‹›` Try it Online!
23. `ɾL` Try it Online!
24. `øCĖ` Try it Online!
25. Try it Online!
26. `±` Try it Online!
27. Try it Online!
28. `ɖt` Try it Online!
29. Try it Online!
30. `,` Try it Online!
31. Try it Online!
32. `ḣJ` Try it Online!
33. `ṫ+` Try it Online!
34. `v` Try it Online!
35. Try it Online!
36. Try it Online!
37. `(₈)!` Try it Online!
38. `I` Try it Online!
39. `$` Try it Online!
40. `Ŀ` Try it Online!
41. `NN` Try it Online!
42. `S` Try it Online!
43. `V` Try it Online!
44. `Yy` Try it Online!
45. `^` Try it Online!
46. `ei` Try it Online!
47. `g` Try it Online!
48. `G` Try it Online!
49. `s` Try it Online!
50. Try it Online!
51. Try it Online!
52. `ȧ` Try it Online!
53. `ġ` Try it Online!
54. Try it Online!
55. Try it Online!
56. `@a|` Try it Online!
57. `Aẋ` Try it Online!
58. `§` Try it Online!
59. `ε` Try it Online!
60. `µ` Try it Online!
61. `wṄ` Try it Online!
62. `↵⁋` Try it Online!
63. `ṘṘ` Try it Online!
64. Try it Online!
65. `Π` Try it Online!
66. Try it Online!
67. Try it Online!
68. `[` Try it Online!
69. Try it Online!
70. Try it Online!
71. Try it Online!
72. `ꜝꜝ` Try it Online!
73. `⇧⇩` Try it Online!
74. `¬Ǔ` Try it Online!
75. `¥ǔ` Try it Online!
76. `꘍꘍` Try it Online!

This took well over two hours.
> 2 votes

# Answer
# str, 19 programs

This is a very flexible language, because the empty program works, and there are a lot of no-op functions, or things that can be combined into no-ops. All of these are programs taking strings as input.

1. The empty program
2. A space character
3. A tab character
4. A newline character
5. `.` (this and the whitespace above explicitly do nothing)
6. `;` (the `;` character is used as a separator and does nothing by itself)
7. `3~` (push a value, then swap it. The language only pays attention to the top value of the stack for each character)
8. `2$` (push a value, then discard it)
9. `e:` (concatenate each character with the empty string)
10. `oq` (explicitly print each character, then tell the language not to implicitly print it)
11. `1x` (repeat each character one time)
12. `bu` (move each character to the buffer, then back to the stak)
13. `yc` (convert to a number, then back to a string)
14. `m` (convert to a string, which it already is)
15. `XY` (increment by one codepoint, then decrement again)
16. `w` (unlike all the above programs, this adds a trailing newline. I have no idea why this works)
17. `0-` (subtracts 0 from each character)
18. `_` (`_` is the reverse function, except it operates on each character individually, so does nothing here)
19. `d` (duplicates each character, but the implicit output only prints one character per input, so this amounts to nothing)
> 1 votes

# Answer
# Python 3, 5 solutions (a program, three functions and a default-value variable)

I see there's already a Python 3 answer, but I thought I'd try and make another one anyway. Or should it have been a comment?

* `exec("p\x72\x69\x6e\x74(\x69\x6epu\x74())")` \# reads a line from standard input and writes it to standard output, the code has most letters escaped so they aren't directly included, and then the quotes unescape them and exec runs them
* `str` \# returns an argument as a string
* `lambda a:a` \# returns an argument
* `''.join` \# returns a string with nothing inserted between the characters
* `_` equals the previous line (this one only works in the interactive interpreter, but the other ones work there too, so it should probably be okay). I think I saw some solution to another puzzle here using a default variable like that as an input, so hope that's okay. Otherwise this is four solutions, like the other answer.
> 1 votes

# Answer
# \>\<\>, 3 programs

\>\<\> has exactly two characters that can be used for output. `n` prints an integer.

Program 1:

`n;`

The other output character is `o`, printing an ascii character. Since we have already spent the program terminator `;` and programs are required to halt, we can trigger the "something smells fishy..." by division by zero

Program 2:

`io00,`

But yet another program is still possible. A `n` or `o` character can be obtained by reflection, which only `p` can perform.

Program 3:

`ab*aa-:p4f*1-1aa-p`

The useable IO instructions in \>\<\> are then depleted.
> 1 votes

# Answer
# Elixir, 5 functions

```
+
abs
round
ceil
&(&1)

```

Well, unary `+` is technically an operator, but I think it should count, as it really quacks like a function in Elixir. For instance, it can be captured and passed as an argument to a higher-order function in the same way as a named function, and even the syntax for overriding unary operators is like defining normal functions.

The next three are numerical functions that work as identity for positive integers. These are all defined in `Kernel` module (`ceil` available from version 1.8+), which is imported by default, and thus callable directly without qualifying the module name.

Finally, the last one is a shorthand form of the explicit identity function.

As always, there are other unused candidates that share characters with those above. In particular, the letter `n` is rather "popular":

```
floor
trunc
to_string
Function.identity
fn n->n end

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~14~~ ~~15~~ 16 functions

Verify: with `Re` or with `Ramp`

Mathematica only has so many ways to define a function.

1. `#&`. A function that returns its first argument.
2. `$$`. A function of one variable that returns that variable.  is U+F4A1.
3. `z|->z`. Identical to #2. `|->` was added in 12.2.
4. `f_//f=f`. Defines a function `f` that returns its argument.
5. `\043\046`. Escape sequences for `#&`.
6. `⌊⌋〚I+I I I〛`. The floor function `Floor[][[0]]` = `Floor`. `⌊⌋〚〛` are U+230A, U+230B, U+301A, and U+301B, respectively.
7. `((1')(1'))[[1'[1]]]` The exponent function `Times[1', 1'][[1'[1]]]` = `Power[0&, 2][[0]]` = `Power`. Returns the argument when called with only one argument.

---

But there are also a good number of built-ins up to the task.

8. `D`. Computes the derivative, but acts as identity when passed only one argument.
9. `N`. Converts the argument to a numeric (approximate) value. For `Integer`s, returns the `Rational` corresponding to that integer.
10. `Or`. Logical or. Returns the argument when called with only one argument.
11. `And`. Logical and. Returns the argument when called with only one argument.
12. `LCM`. Computes the least common multiple of its arguments.
13. `Sow`. Returns its argument. Additionally, allows that value to be collected by an enclosing `Reap`.
14. `Exit`. A function that returns an integer via exit code.

Note that `Run` returns 256\*(return code) on TIO instead. Try it online!
15. `Plus`. Returns the sum of its arguments.

---

The final function can be either of:

* `Re`. Returns the real part of a number.
* `Ramp`. The ramp function. Returns nonnegative numbers unchanged.
> 1 votes

# Answer
# Vyxal, 1 function and 9 programs

Functions:

1. `λ;` \- A lambda that does nothing.

Programs:

1. The empty program \- Nothing happens to the input, so it remains on top of the stack (and gets popped off at the end).
2. `#` \- Basically the same as the empty program, except it has an (empty) comment too.
3. `:` \- Duplicate the input. Since we only care about the top of the stack, this can be treated as an identity function even though it leaves trash behind.
4. `D` \- In the same vein as the previous program, this triplicates the input.
5. `SE` \- Convert to string, then evaluate.
6. \- Double, then halve.
7. `,` \- Print the input.
8. `¤$F` \- Finally, an almost non-trivial program! This one pushes the empty string, swaps with the input, then keeps all the characters in the input that aren't in the empty string (which is all of them). It also works with normal lists, but errors.
9. \- Round an integer.
> 1 votes

# Answer
# Julia, 12 functions

```
X->X
==(==)=(==)
*
+
&
|
⊻
Real
sum
prod
big
Int

```

Try it online!

More identity functions!
> 1 votes

# Answer
# Java, 2 functions

```
x->x

```

A lambda function.

```
Function.identity()

```

This returns the identity function.

Without the letters *e* and *t*, we can't use any of the `{byte,char,short,int,long}Value`, `valueOf` or `toString` methods.
> 0 votes

# Answer
# CJam, 3 programs + 20 functions

Programs first, these work just as you'd expect:

```
r

```

TIO: Integer stdin input. Technically, CJam has no integer input, but reading and returning a space-separated string is no different if you're just sending an integer.

```
l

```

TIO: Line stdin input

```
q

```

TIO: Line stdin input. Can actually accept more than one line, as demonstrated here, but if you just give it one that's okay too.

Bonus unused program:

```
114c~

```

TIO: Integer stdin input. There's only 3 ways to get stdin in CJam, so we've got a pretty hard limit there. However! We can use `~` to execute a string as code, so we can sneak a fourth one in. Unfortunately, this uses up too many useful bytes for our functions later.

Functions next. A reasonable definition for a CJam function is a piece of code whose input and output are the stack. I'm not 100% certain if this is actually allowed, though, so I've separated them here.

```

```

Int or string: no op is a no op.

```

```

Int or string: so is a space. Imagine StackExchange actually is rendering the space.

```

```

Int or string: newline is a no-op. You'd think there'd be a bunch of these, but CJam has an annoying habit of throwing errors on characters it doesn't recognize rather than ignoring them.

```

```

Int or string: tab is our last no-op. Hooray! (Imagination once again necessary.)

```
9;

```

Int or string: Pushes and discards a nine

```
()

```

Int: decrements, then increments.

```
s

```

String: converts to a string

```
i

```

Int: converts to an int

```
`

```

String: converts to a string representation.

```
1*

```

Int: multiplies by one

```
T+

```

Int: adds zero

```
X/

```

Int: divides by one

```
U-

```

Int: subtracts zero

```
e0

```

Int: multiplies by 10^0

```
mo

```

Int: rounds to nearest int

```
z

```

Int: takes absolute value, fine since positive is specified

```
V|

```

Int: bitwise or with 0

```
~~

```

Int: bitwise negates twice

```
KJ<^

```

Int: Ooh, four characters at once? Yeah, but it all amounts to an XOR with 0.

```
_&

```

Int: bitwise AND with itself

There's probably a couple others, but I'm running out of useful characters now, so I think I'll stop here. Feel free to add more, or point out if I accidentally used something twice (though I'm fairly sure I didn't)
> 0 votes

# Answer
# JavaScript, 4 functions

```
Number

```

Casts its argument to a number format. Leaves numbers unchanged.

```
BigInt

```

Casts its argument to a BigInt. Leaves BigInts unchanged. A BigInt is technically an integer.

```
x=>x

```

The identity function expressed using a lambda.

```
[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]][([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+[![]]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]+(+(!+[]+!+[]+!+[]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]])+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]])()((+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]])[+!+[]]+([]+[])[(![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(!![]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]()[+!+[]+[+!+[]]]+([]+[])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[!+[]+!+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([]+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]][([][[]]+[])[+!+[]]+(![]+[])[+!+[]]+((+[])[([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[+!+[]]+(!![]+[])[+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]+[])[+!+[]+[+!+[]]]+(!![]+[])[!+[]+!+[]+!+[]]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]])[+!+[]])

```

JSFk for above.
> 0 votes

---
Tags: code-challenge, restricted-source
---


title: Yet another coin flipping problem

text:
# Question
Title: Yet another coin flipping problem
**Problem**

Starting with a set of 10 coins at the start where all coins are tails up, and given n number of integers \\$x\_1, x\_2, x\_3... x\_n\\$ representing n rounds of coin flipping.

At each round, we randomly flip \\$x\_i\\$ number of coins at random. i.e Coins that were heads become tails, and vice versa. Within each round, every coin can be flipped at most once, i.e no repeats.

**Objective** Write the shortest function that takes as input a list of integers, and calculates the expected number of heads at the end of all rounds.

Assume that the inputs will always correct, i.e every element is between 0 to 10.

Example 1:

```
# 3 coins chosen at random were flipped over one round, hence E(Heads) = 3
Input = [3]
Output = 3

```

Example 2:

```
# 5 coins chosen at random were flipped in the first round
# At the second round, only 1 was random flipped with 50% chance of
# picking a head/tail. E(Heads) = 0.5*6 + 0.5*4

# Hence E(Heads) = 5
Input = [5, 1]
Output = 5

```

# Answer
> 4 votes
# Python 2, 40 bytes

```
r=0
for c in input():r+=c-r*c/5.
print r

```

Try it online!

Let \\$Z\_i, 1 \le i \le 10 \\$ be random variables indicating the state of the \\$i\\$-th coin after all flips, \\$1\\$ for heads and \\$0\\$ for tails. The number we are interested in is:

$$ E \left\[ \sum\_{i=1}^{10} Z\_i \right\] = \sum\_{i=1}^{10} E \left\[ Z\_i \right\] = 10 E\left\[ Z\_1 \right\] $$

(We can do these two equalities because the expected value is linear and all \\$Z\_i\\$ are identically distributed)

This means it is enough to compute the expected value for a single coin, which leads to the following program, where the formula can be simplified to the above:

```
r=0.0
for c in input():r=r*(10-c)/10+(1-r)*c/10
print r*10

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 10 bytes

Uses a formula I got by plugging sympy into my Python solution.

```
5(/æ¦PO5(*

```

Try it online!

$$ \sum\_{A \subseteq X, A \ne \emptyset} (-5)^{1-\left| A \right|} \prod\_{a\in A} a = -5 \sum\_{A \subseteq X, A \ne \emptyset} \prod\_{a\in A} {a \over -5} $$

where \\$X\\$ is the multiset \\$\left\\{ x\_1, x\_2, \cdots, x\_n\right\\}\\$.

```
5(/         # divide each value by -5
   æ¦       # get all non-empty subsets
     P      # take the product of each subset
      O     # sum all values
       5(*  # multiply result by -5

```

---

A direct port of the Python answer is the same length:

```
Îv1y5/-*y+

```

Try it online!

# Answer
> 2 votes
# JavaScript (V8), 29 bytes

```
x=>x.reduce((a,b)=>a+b-a*b/5)

```

Try it online!

Based on ovs's answer.

# Answer
> 1 votes
# Jelly, 7 bytes

```
÷5CPC×5

```

Try it online!

$$ 5\times(1-\prod\_{i=1}^n 1-{x\_i \over 5}) $$

Read this from right to left to get the Jelly code. The formula is derived from the same sympy output as the 05AB1E answer. This has a nice symmetry to it as `C×5` is the inverse of `÷5C`.

---

# Jelly, 8 bytes

Port of my Python answer

```
+_×÷5ɗɗ/

```

Try it online!

# Answer
> 1 votes
# Vyxal, 10 bytes

```
λ₌+*5/-;dR

```

Try it Online!

port of 05AB1E answer’s formula

and also, wholesomely rekted by lyxal with 5 bytes saved

# Answer
> 0 votes
# MathGolf, 9 bytes

```
0ë{‼+*5/-

```

Port of *@Yousername*'s JavaScript answer, which is based on *@ovs*' answers.

Try it online.

**Explanation:**

```
0         # Start with 0
 ë        # Push the input-integers as float-array
  {       # Foreach over these floats:
   ‼      #  Apply the following two commands separated to the stack:
    +     #   Sum the top two values
    *     #   Multiply the top two values
     5/   #  Divide the product by 5
       -  #  And then subtract it from the sum
          # (after the loop, the entire stack is output implicitly as result)

```

# Answer
> 0 votes
# Charcoal, 16 bytes

```
≔⁰ηＦθ≧⁻×ι⊖∕η⁵ηＩη

```

Try it online! Link is to verbose version of code. Explanation: Port of @ovs' Python solution, except with a slightly rearranged formula `r-=c*(r/5-1)` which saves a byte when written in Charcoal.

```
≔⁰η

```

Start with zero heads.

```
Ｆθ

```

Loop through the numbers of flips.

```
≧⁻×ι⊖∕η⁵η

```

Calculate the expected number of heads.

```
Ｉη

```

Output the expected number of heads.

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


title: Implement a 2-tag system simulator

text:
# Question
Title: Implement a 2-tag system simulator
To quote http://brainfuck.org/utm.b:

> A tag-system transforms strings over an alphabet `A = {a[1], a[2], ... a[n], a[n+1]}` as follows: a positive integer `m` is chosen, and so is a function `P` that maps each `a[i]` for `1<=i<=n` to a string `P(a[i])` over the alphabet `A`. Now:
>
> 1. if the string being transformed has fewer than `m` elements, the whole process stops now.
> 2. `m` elements are removed from the beginning of the string
> 3. Call the first element removed `a[k]`; if `k=n+1` the whole process stops now.
> 4. `P(a[k])` is appended to the string.
> 5. steps 1-5 are repeated.

A more extensive definition is at https://en.wikipedia.org/wiki/Tag\_system.

We will call `a[n + 1]` the "Halting symbol". Alphabet symbols (symbols in `a`) are ASCII alphanumeric chars.

2-tag systems are those where `m=2`.

The simulator should take two inputs.

1. A definition for `P`, which doubles as a definition for the alphabet. The definition format is given below.
2. An "initial word" to be transformed.

If it halts, it should output the "halting word", the word that is shorter then 2 alphabet symbols long or which has the halting symbol in its front.

## IO

If possible, the input should be read from stdin or passed to a function in the following format (Or something equivalent).

> symbol:listofsymbols symbol:listofsymbols symbol:listofsymbols \[and so on\]
> initialword

The `listofsymbols` may be assumed to contain only valid symbols. Any symbol that is not explicitly defined should be treated as the halting symbol.

## The test cases (from Wikipedia) are:

```
input:
  a:bc b:a c:aaa
  aaaa
output:
  a

input:
  a:ccbaH b:cca c:cc
  baa
output:
  Hcccccca
#This test case uses H as the halting symbol, but it might as well be using any alphanumeric ASCII char other than the defined a, b, and c.

```

## Example implementation in Nim:

```
import tables, strutils
proc runTag(P: Table[char, string], inputstr: string): string =
  var haltingword: string;
  var str = inputstr
  while true:
    haltingword = str
    if str.len() < 2:
      break
    var cur = str[0]
    str.delete(0..1)
    if not P.hasKey(cur):
      break
    str.add(P[cur])
  return haltingword

var ruleinput = readLine(stdin).split(' ')
var rules: Table[char, string]
for i in ruleinput:
  var pair = i.split(':')
  rules[pair[0][0]] = pair[1]
var str = readLine(stdin)

echo runTag(P=rules, inputstr=str)

```

# Answer
> 5 votes
# 05AB1E, ~~20~~ 19 bytes

```
[Dg#¬UI.ΔнXQ}Ä#θ«¦¦

```

Inputs in the order `string, map`, where the map are key-value pairs as space-delimited strings.

Try it online or verify both test cases.

**Explanation:**

```
[               # Start an infinite loop:
 D              #  Duplicate the current string (or the implicit first input-string in
                #  the first iteration)
  g             #  Pop and get its length
   #            #  If its length is 1: stop the infinite loop
                #  (after which the duplicated string is output implicitly as result)
   ¬            #  Else: get the first character (without popping the string)
    U           #  Pop and store this head in variable `X`
     I          #  Push the second input-list of pairs
      .Δ        #  Find the first which is truthy for:
        н       #   Where its first item (the key)
         XQ     #   Equals head `X`
       }        #  Close the find-first (this will result in -1 if none were found)
        Ä       #  Get the absolute value (no-op for a pair of strings)
         #      #  If this is 1: stop the infinite loop
                #  (after which the string is output implicitly as result)
         #      #  Else: the `#` will act as a 'split-on-spaces' instead
          θ     #  Pop and leave last item (the value)
           «    #  Append it to the string
            ¦¦  #  And remove the first two characters

```

# Answer
> 6 votes
# Python 3.8 (pre-release), 56 bytes

```
f=lambda a,d:a[:len(a)>1]in d and f(a[2:]+d[a[0]],d)or a

```

Try it online!

-4 thanks to @JonathanAllan

-3 thanks to @Neil

Normal recursive approach

Takes a string and a dictionary of transformations

# Answer
> 5 votes
# PowerShell Core, ~~68~~ 60 bytes

```
for($a,$d=$args;$a[1]-and($u=$d[$a[0]])){$a=$a+$u|% Su* 2}$a

```

Try it online!

Takes two parameters:

* the string to process
* a dictionary of char / strings

### Explanations

```
for($a,$d=$args;   # Sets the variables $a, the string to process and $d the dictionary of transformations
$a[1]-and          # While there is more than 1 character left
($u=$d[$a[0]])){   # And there is a transformation for the first character of $a, store the transformation in $u
$a=$a+$u|% Su* 2}  # Concatenates $a and $u and takes all the characters from the second position
$a                 # return $a when it is 1 char long or we hit a halting symbol

```

-2 bytes thanks to *wasif*!
-6 bytes thanks to *Zaelin Goodman*!

# Answer
> 3 votes
# Jelly, 29 bytes

Feels clunky to me at present.

```
ZḢiȧị¥⁸0ị
;1ịç@ɗ¥⁹ḊḊʋḊȦ$¡ƬẠƇṪ

```

A dyadic Link that accepts the initial word on the left and the production rules (\\$P\\$) on the right and yields the result.

**Try it online!** (Each production rule is `[chr, [chr, ...]]`, but a list of these cannot be passed as an argument to a program so the footer translates them from a list of `[[chr], [chr, ...]]`)

### How?

```
ZḢiȧị¥⁸0ị - Link 1, get new characters (or zero): rules, R; character, C
Z         - transpose (R)
 Ḣ        - head -> alphabet
  i       - first 1-indexed index of (C) in (alphabet) or, when C=Halt, zero
     ¥⁸   - last two links as a dyad, f(I=that, R)
    ị     -   (I) index into (R)
   ȧ      -   (I) logical AND (that) -> relevant rule or zero
       0ị - tail -> new characters or zero

;1ịç@ɗ¥⁹ḊḊʋḊȦ$¡ƬẠƇṪ - Link: initial word, W; rules, R
               Ƭ    - collect up, starting with W, while no duplicates found with:
              ¡     -   repeat...
             $      -   ...number of times: last two links as a monad, f(current):
           Ḋ        -     dequeue
            Ȧ       -     has elements and none are zero (found when processing a halt)
          ʋ         -   ...what: last four links as a dyad, f(current, R)
       ⁹            -     right argument, R
      ¥             -     last two links as a dyad, f(current, R)
     ɗ              -       last three links as a dyad, f(current, R)
 1                  -         one
  ị                 -         index into (current) -> head character
   ç@               -         call Link 1 as a dyad, f(R, character)
;                   -       (current) concatenate (that)
        Ḋ           -     dequeue
         Ḋ          -     dequeue
                 Ƈ  - keep those for which:
                Ạ   -   all truthy (are not the result of processing a halt)
                  Ṫ - tail

```

# Answer
> 3 votes
# Python 3, 56 bytes

```
def f(a,d):
 try:x,y,*z=a;a[:]=*z,*d[x];f(a,d)
 except:0

```

Try it online!

This function take input as a list of chars, and a dict of char to list of chars. And it returns by modify `a` in-place.

---

And if terminating the function by an exception is allowed, it could be even shorter:

# Python 3, 40 bytes

```
def f(a,d):x,y,*z=a;a[:]=*z,*d[x];f(a,d)

```

Try it online!

# Answer
> 3 votes
# Pip, 27 bytes

```
W#Sb&a~@b.s.C KXWb:b@>2.$1b

```

Try it here! Or, here's a 28-byte equivalent in Pip Classic: Try it online!

The tag definitions and the initial word are taken as command-line arguments. Each definition is given as alphabet symbol + space + string, and definitions are separated by any non-space non-alphanumeric symbol. For example:

```
a bc;b a;c aaa

```

This will need to be quoted so the command-line treats it as a single argument.

### Explanation

```
W#Sb&a~@b.s.C KXWb:b@>2.$1b
                             ; a, b are cmdline args; s is space; XW is `\w` (implicit)
W                            ; While
 #                           ;  length of
  Sb                         ;  longest suffix of b (the current word)
                             ;  is nonzero (i.e. length of b is at least 2)
    &                        ; and
       @b                    ;  first character of b
         .s                  ;  concatenated to a space
           .                 ;  concatenated to the following regex...
               XW            ;   word character: \w
              K              ;   with Kleene star operator: \w*
            C                ;   wrapped in a capture group: (\w*)
     a~                      ;  matches somewhere in a (the definitions)
                             ; do:
                 b:          ;   Assign to b
                   b@>2      ;   all but the first two characters of b
                       .$1   ;   concatenated to the contents of the regex capture group
                          b  ; Output the final value of b

```

# Answer
> 3 votes
# jq, 62 bytes

```
.P as$P|.w|until(length<2//(.[:1]|in($P)|not);.[2:]+$P[.[:1]])

```

Takes input as a JSON object with keys `P` and `w`. The value of `P` is an object whose keys are alphabet symbols and whose values are their associated strings. The value of `w` is the initial word. Try it online!

### Explanation

```
.P as $P |    Store the P mapping in the variable $P
.w |          The rest of the program will manipulate the input word
until (       Until this condition is true...
  length < 2    The length of the word is less than 2
  // (          or:
    .[:1] |       The first character of the word
    in($P) |      Is a key in $P
    not)          Make that "is NOT a key in $P"
  ;           ...update the word to be the following:
  .[2:] +       The word minus its first two characters, plus
  $P[           the value in $P at this key:
    .[:1]         The first character in the word
  ])
              When the loop exits, return the final value of the word

```

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

```
p=>g=a=>p[[x,y,...z]=a,x]&&y?g([...z,...p[x]]):a

```

Try it online!

# Answer
> 1 votes
# Charcoal, 35 bytes

```
ＳθＷＳ⊞υιＷ∧⊖ＬθΦυ⁼§θ⁰§κ⁰≔⭆⟦θ⊟ι⟧Φκ›ν¹θθ

```

Try it online! Link is to verbose version of code. Takes input as the string to be transformed followed by a list of transformations in the form `symbol:stringofsymbols`. Explanation:

```
Ｓθ

```

Input the string to be transformed.

```
ＷＳ⊞υι

```

Input the list of transformations.

```
Ｗ∧⊖ＬθΦυ⁼§θ⁰§κ⁰

```

Repeat while the string is longer than a single character and the first character is the first character of one of the transformations.

```
≔⭆⟦θ⊟ι⟧Φκ›ν¹θθ

```

Remove the first two characters from the string and the matching transformation and concatenate the result.

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


title: Simplify K projections

text:
# Question
Title: Simplify K projections
## Background

**K** functions have a feature called **projection**, which is essentially partial application of values to a function. The syntax for projections is a natural extension of the regular function call syntax:

```
f[1;2;3]    / call a ternary function f with three arguments 1, 2, 3
f[1;2;]     / the third argument is missing,
            / so it evaluates to a unary derived function instead
f[1;2;][3]  / calling the derived function with 3 calls f with 1, 2, 3
            / so this is equivalent to calling f[1;2;3]

```

Projections can supply any number of arguments and missing slots, and omit trailing semicolons. The function is evaluated only when all missing slots are filled and the number of arguments is at least the function's arity. For the sake of this challenge, let's assume the arity of `f` is *infinity*, i.e. it is never actually evaluated.

The right side shows how ngn/k prettyprints projections. You can freely experiment with ngn/k online interpreter.

```
f[1]        / -> f[1]
f[1;2]      / -> f[1;2]
f[;2]       / -> f[;2]
f[;2][1]    / -> f[1;2]

```

A projection also decides the minimum number of arguments `f` will be actually called with. For example, `f[1;]` specifies that the first arg is `1` and the second arg will come later. It is different from `f[1]`, and the two are formatted differently.

```
f[1]    / -> f[1]
f[1;]   / -> f[1;]

```

You can create projections out of projections too, which is the main subject of this challenge. Given an existing projection `P` and the next projection `Q`, the following happens:

* For each existing empty slot in `P`, each (filled or empty) slot in `Q` is sequentially matched from left to right, replacing the corresponding empty slot in `P`.
* If `Q` is exhausted first, the remaining slots in `P` are untouched.
* If `P` is exhausted first, the remaining slots in `Q` are added to the end.

```
f[;;1;;]      / a projection with five slots, 3rd one filled with 1
f[;;1;;][2]   / -> f[2;;1;;]
              / 2 fills the first empty slot
f[;;1;;][2;3;4]    / -> f[2;3;1;4;]
              / 2, 3, 4 fills the first three empty slots
              / (1st, 2nd, 4th argument slot respectively)
f[;;1;;][2;;4]     / -> f[2;;1;4;]
              / the second empty slot (2nd arg slot) remains empty
f[;;1;;][2;;4;;6]  / -> f[2;;1;4;;6]
              / Q specifies five slots, but P has only four empty slots
              / so the 6 is added as an additional (6th overall) slot

```

## Challenge

Given a series of projections applied to `f`, simplify it to a single projection as described above.

The input is given as a string which represents the function `f` followed by one or more projections, where each projection specifies one or more (filled or empty) slots. You may further assume that

* the substring `[]` does not appear in the input (it means something slightly different),
* each filled slot (specified argument) contains a single integer between 1 and 9 inclusive, and
* the entire input does not have any spaces.

Standard rules apply. The shortest code in bytes wins.

## Test cases

All the examples are replicated here, and a "stress test" is presented at the bottom.

**Basic tests**

```
f[1] -> f[1]
f[1;] -> f[1;]
f[1;2] -> f[1;2]
f[;2] -> f[;2]
f[;2][1] -> f[1;2]
f[1;2;3] -> f[1;2;3]
f[1;2;] -> f[1;2;]
f[1;2;][3] -> f[1;2;3]

f[;;1;;] -> f[;;1;;]
f[;;1;;][2] -> f[2;;1;;]
f[;;1;;][2;3;4] -> f[2;3;1;4;]
f[;;1;;][2;;4] -> f[2;;1;4;]
f[;;1;;][2;;4;;6] -> f[2;;1;4;;6]

```

**Stress tests (input)**

```
f[;1]
f[;1][;2]
f[;1][;2][3]
f[;1][;2][3][;;;4]
f[;1][;2][3][;;;4][;5]
f[;1][;2][3][;;;4][;5][6;]
f[;1][;2][3][;;;4][;5][6;][7]
f[;1][;2][3][;;;4][;5][6;][7;;]
f[1;;;;;;;;;;;;;]
f[1;;;;;;;;;;;;;][2][3]
f[1;;;;;;;;;;;;;][2][3][;;;;;4;;;;;;;;]
f[1;;;;;;;;;;;;;][2][3][;;;;;4;;;;;;;;][5;6;7;8;9;1][2;3;4;5][6;7]

```

**Stress tests (output)**

```
f[;1]
f[;1;2]
f[3;1;2]
f[3;1;2;;;;4]
f[3;1;2;;5;;4]
f[3;1;2;6;5;;4]
f[3;1;2;6;5;7;4]
f[3;1;2;6;5;7;4;;]
f[1;;;;;;;;;;;;;]
f[1;2;3;;;;;;;;;;;]
f[1;2;3;;;;;;4;;;;;;;;]
f[1;2;3;5;6;7;8;9;4;1;2;3;4;5;6;7;]

```

# Answer
# Stax, <sup>~~37 34~~</sup> 32 bytes

```
Ñgí⌡²☼☺≈AU▀≤L♠╫$U∩─.ù·○╓╥ò±E♦τèZ

```

Run and debug it

-2 reducing splitting code

## Explanation

```
2t1T.][/  {';/m{s{c{c{B}z?}?ms+k';*:}'fs+
2t1T.][/                                  get all argument bodies
          {';/m                           split all on semicolons
               {s{c{c{B}z?}?ms+k          reduce by:
                s                          swap with prev
                 {c{c{B}z?}?m              map elements in prev to:
                  c{      }?                if non-empty, leave elem as is
                    c{B}z?                  else remove first element of next and push
                                            (pushes [] if empty)
                             s+           append the rest elements
                                ';*       join with semicolons
                                   :}     put in square brackets
                                     'fs+ prepend 'f'

```

# Stax, 37 bytes

```
Ö☺τσj↔₧♂√V{▐9,=☺|╢Δ‼$≥ä₧ÿºÉ/♂y╩▲S╞♫┘{

```

Run and debug it

uses an assign at index builtin, slightly longer.
> 5 votes

# Answer
# 05AB1E, 46 bytes

```
¦¤¡¨ε¦';¡}Å»U0ìD_OXg-(©di®Å0«}0X.;}θ';ý0K"f[ÿ]

```

05AB1E is not the right language for this challenge.. :/

Try it online or verify all test cases.

**Explanation:**

Step 1: Transform the input to something more usable: Try it online.

```
¦                  # Remove the leading "f" from the (implicit) input-string
 ¤                 # Get its last character "]" (without popping)
  ¡                # Split it on this "]"
   ¨               # Remove the trailing empty item
    ε              # Map over each inner string
     ¦             #  Remove the leading character (the "[")
      ';¡         '#  Split it on ";"
    }              # Close the map

```

We now have a list of lists of digits and empty strings.

Step 2: Reduce this list of lists according to the challenge: Try it online.

```
Å»                 # Cumulative left-reduce (which unfortunately keeps track of steps):
  U                #  Pop and store the current list in variable `X`
   0ì              #  Prepend a 0 before each item in the result-string
                   #  (so all empty strings become 0s)
   D_O             #  Get the amount of 0s in this list (duplicate; ==0; sum)
      Xg           #  Push the length of the current list `X`
        s-         #  Subtract the amount of 0s from this length
          ©        #  Store it in variable `®` (without popping)
           di    } #  Pop, and if this value is >= 0:
             ®Å0   #   Push a list with `®` amount of 0s
                «  #   And append this to the result-list
    0X.;           #  Then replace each zero ("0","00","000",etc.) in this list one by
                   #  one with the values from list `X`
 }θ                # And after the cumulative left-reduce, pop and keep the last list

```

Step 3: Format this resulting list to a format similar as the input:

```
';ý               '# Join the list with ";" delimiter
   0K              # Remove all 0s from the string
     "f[ÿ]        "# Push string "f[ÿ]", where `ÿ` is automatically replaced with the
                   # string
                   # (after which the result is output implicitly)

```
> 5 votes

# Answer
# Python 3.8 (pre-release), 126 bytes

```
lambda s,D=[]:f'f[{";".join([D:=[j or next(i,"")for j in D]+[*i]for k in s[2:-1].split("][")if(i:=iter(k.split(";")))]*0+D)}]'

```

Try it online!

Ungolfed:

```
def f(s):
  D=[]
  for k in s[2:-1].split(']['):
    i = iter(k.split(';')) # next projection
    D = [j or next(i,'') for j in D] # replace empty slots with arguments from i
    D += [*i] # add the rest of i
  return 'f['+';'.join(D)+']'

```
> 4 votes

# Answer
# K (ngn/k), ~~65~~ 59 bytes

```
{"f[",|x,|y/{.![a*+\a:~#'x;x],(1+!#y)!y}/y\'-1_'1_z\}."];["

```

Thanks to ngn for cutting 4 bytes here and here.

Try it online!

# K (k9 2021.09.01), 54 bytes

```
{"f[",|x,|y/{!?(?x*+\x!:~#'x),?+\y!1}/y\'1_z\x_}."];["

```
> 4 votes

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

```
v=>v.match(/(?<=[[;])\d*|\[/g).map(g=n=>1/n?o[++i]?g(n):o[i]=n:i=-1,o=[])&&`f[${o.join`;`}]`

```

Try it online!

-1 byte by Arnauld.
> 3 votes

# Answer
# Jelly, 33 bytes

```
ṣ”[Ṗ€ṣ€”;VṆ€k$ḟ0;ɗ"Ẏɗ/j”;ḟ0Ø[j”f;

```

A monadic Link that accepts a list of characters and yields a list of characters.

**Try it online!**

### How?

```
ṣ”[Ṗ€ṣ€”;VṆ€k$ḟ0;ɗ"Ẏɗ/j”;ḟ0Ø[j”f; - Link: list of characters, S
ṣ”[                               - split (S) at '['
   Ṗ€                             - pop (i.e. remove ']' from) each
     ṣ€”;                         - split each at ';'
         V                        - evaluate as Jelly code
                                     -> list of projections with zeros at empty slots
                     /            - reduce by:
                    ɗ             -   last three links as a dyad, f(P, Q):
             $                    -     last two links as a monad, f(P):
          Ṇ€                      -       logical NOT each
            k                     -       partition (P) after truthy indices (of that)
                                            -> P split after each empty slot
                  "               -     zip (across [t in that] and [q in Q]) with:
                 ɗ                -       last three links as a dyad, f(t, q):
               0                  -         zero
              ḟ                   -         (t) filter discard (zeros)
                ;                 -         concatenate (q)
                   Ẏ              -     tighten (to a flat list)
                      j”;         - join with ';'
                         ḟ0       - filter discard zeros
                           Ø[j    - "[]" join (that)
                              ”f; - 'f' concatenate (that)

```
> 3 votes

# Answer
# Scala, 183 bytes

```
_.drop(2).init split "\\]\\["map(_ split ";")reduce{(p,q)=>val(b,a)=((q,q take 0)/:p){case((q,p),x)=>if(q.size<1|x!="")(q,p:+x)else(q drop 1,p++q.take(1))}
a++b}mkString("f[",";","]")

```

Try it in Scastie!

A pretty horrible solution, but I'll work on it later. Explanation coming soon.

```
_                  //The input
 .drop(2)          //Drop the "f["
 .init             //Drop the "]" at the very end
  split "\\]\\["   //Split the projections up
  map(_ split ";") //Split each projection into its parts
  reduce{ (p, q) => //Reduce the projections by this function, which does the real work
   val(b,a)=((q,q take 0)/:p){case((q,p),x)=>if(q.size<1|x!="")(q,p:+x)else(q drop 1,p++q.take(1))}
a++b}mkString("f[",";","]")

```
> 2 votes

# Answer
# Retina 0.8.2, 131 bytes

```
(f.(\d;)*(;(\d;)*)*)(;[^]]*].(?<-3>;)*(?(3)^))(\d);?
$1$6$5
}`\[\]

}`(f(.(\d|((?=;)))(?=[];]))*);?(].(?<-4>;)*)([^]]+)?
$1$#6$*;$6

```

Try it online! Explanation: Uses .NET balancing groups to shuffle arguments into slots. The first two lines shuffle arguments from the second application into free slots in the first. The middle two lines delete an empty application resulting from the first two lines. The last two lines append trailing arguments or slots from the second application to the first, however the test assumes that there are no arguments left to shuffle or empty applications, which is why an extra loop is needed.
> 1 votes

---
Tags: code-golf, string, parsing, functional-programming
---


title: Convert to a non-adjacent form

text:
# Question
Title: Convert to a non-adjacent form
Consider a form of binary where digits can be any of \\$1\\$, \\$0\\$ and \\$-1\\$. We'll still call this "binary" because we convert the digits from base two. For example,

$$\begin{align} \[1, 0, -1, 1\]\_2 & = 1 \times 2^3 + 0 \times 2^2 + -1 \times 2^1 + 1 \times 2^0 \\ & = 8 - 2 + 1 \\ & = 7 \end{align}$$

We'll call a representation of a number in this format a "non-adjacent form" if no non-zero digits are adjacent. \\$\[1, 0, -1, 1\]\_2\\$ is not a non-adjacent form of \\$7\\$, as the last two digits are adjacent and non-zero. However, \\$\[1,0,0,-1\]\_2\\$ is a non-adjacent form of \\$7\\$.

You should take a positive integer and convert it to a non-adjacent form. As every number has an infinite number of these forms (but only by prepending leading zeroes), you should output the form with no leading zeros. If the standard binary format of the input is a non-adjacent form (e.g. \\$5 = 101\_2\\$), you should output that. You can output a list of integers, or a single string, or any other format the clearly shows the output. You may optionally choose to use any three distinct characters in place of `1`, `0` and `-1`.

This is , so the shortest code in bytes wins.

# Answer
> 7 votes
# K (ngn/k), ~~19~~ 12 bytes

```
-/'2\-2!3 1*

```

Try it online!

Uses Prodinger's algorithm on Wikipedia:

```
Input   x
Output  np, nm
xh = x >> 1;
x3 = x + xh;
c = xh ^ x3;
np = x3 & c;
nm = xh & c;

```

And then the last three steps are not used because the `& c` part of `np` and `nm` erases the 1 bits where both are 1, but we're doing `-/'` so it doesn't matter. (Observation thanks to @m90)

How it translates to K:

```
-2!3 1*    given x, create (3x,x) and floor-divide both by 2
           which gives (x3,xh)
2\         convert to base 2, which gives a two-column matrix
           with lsb being the last row
           1st column is np, 2nd column is nm, but both-1 bits not handled
-/'        evaluate np - nm to get a vector of -1, 0, 1s

```

# Answer
> 6 votes
# Jelly, ~~13~~ 9 bytes

```
;0+HBU_/U

```

Try it online!

-4 bytes (`^/&$` removed) thanks to @m90's observation that we don't need to clear shared 1 bits.

Look ma, no Unicode!

Literal translation of Prodinger's algorithm. x3 goes before xh, and `U` is used twice to align the binary representations of the two.

# Answer
> 4 votes
# JavaScript, 35 bytes

```
f=n=>n?f(n+n%4/3>>1)+'OPON'[n%4]:''

```

Try it online!

Output `O` for `0`, `P` for `1`, `N` for `-1`.

-2 bytes by Arnauld.

---

Alternatively, as suggested by Arnauld, using `1` for `1`, ~~`2` for `0`,~~ `0` for `0`, and, `3` for `-1`:

# JavaScript, 31 bytes

```
f=n=>n?f(n+n%4/3>>1)+n%2*n%4:''

```

Try it online!

# Answer
> 2 votes
---

## Python 3, ~~176~~ 103 bytes

Literal translation of Prodinger's algorithm. By no means the shortest python 3 answer that should be attainable. it's been a while on here so looking forward to getting back into it!

```
x=int(input())
h=x>>1
t=h+x
c=h^t
p=bin(t&c)
m=bin(h&c)
n=[]
j=len(p)-2
k=len(m)-2
for i in range(j):n.append(int(p[i+2]))
for i in range(k):n[j-k+i]=-int(m[i+2])*(m[i+2]==0)or 1
print(n)

```

If anyone can help shorten it I'd appreciate it, there must be an easier way to concatenate the two positive and negative value lists.

Using m90's answer it can be shortened vastly predominately by using zip!

```
enter code x=int(input())
print([*[int(x)-int(y)for x,y in zip(*[f".{x//2+z:0{len(bin(x*3))-3}b}"for z in[x,0]])]])

```

# Answer
> 2 votes
# 05AB1E, ~~21~~ 15 bytes

```
0‚¬2÷+2вí`(0ζRO

```

-6 bytes thanks to *@m90*, thanks to his observation that `& c` only changes `[1,1]` to `[0,0]`, which doesn't matter when we're subtracting them.

Try it online or verify some more test cases.

**Explanation:**

```
0‚        # Pair the (implicit) input with 0
  ¬       # Get the first item of this pair (the input) without popping
   2÷     # Integer-divide it by 2
     +    # Add it to both the input and 0 in the pair
          # (we now have the pair [input+input//2, input//2])
      2в  # Convert both inner values to a binary-list
í         # Reverse each inner list
 `        # Pop and push both lists separated to the stack
  (       # Negate all values in the top list
   0ζ     # Zip the two lists together with 0 as filler
     R    # Reverse the list of pairs back again
      O   # Sum each inner pair together
          # (after which the resulting list is output implicitly)

```

# Answer
> 2 votes
# Ruby, ~~41~~ 40 bytes

```
f=->n{n>0?f[(n-w=n%2*(2-n%4))/2]+[w]:[]}

```

Try it online!

# Answer
> 1 votes
# C (clang), ~~103~~ \\$\cdots\\$ ~~96~~ 94 bytes

```
m;i;f(n){int r[n];for(i=!n,n+=*r=m=n/2;n;n/=2,m/=2)r[i++]=n%2-m%2;for(;i--;)putchar(r[i]+49);}

```

Try it online!

*Saved 2 bytes thanks to ceilingcat!!!*

Inputs positive integer \\$n\\$.
Outputs \\$n\\$ converted to its non-adjacent form using \\$2\\$ for \\$1\\$s, \\$1\\$ for \\$0\\$s, and \\$0\\$ for \\$-1\\$s.

# Answer
> 1 votes
# Python 3, 51 bytes

```
f=lambda x,s="":x and f(round(x/2))+".+.-"[x%4]or""

```

Try it online! Outputs using `.` for `0`, `+` for `1` and `-` for `-1`. Explanation: Port of @tsh's JavaScript solution, except that Python has Banker's rounding which saves a byte in Python 3. Or I could have just use Python 2 I guess.

# Answer
> 1 votes
# Charcoal, 23 bytes

```
ＮθＷθ«←§.+.-θ≔÷⁺¬﹪⊕θ⁴θ²θ

```

Try it online! Link is to verbose version of code. Outputs using `.` for `0`, `+` for `1` and `-` for `-1`. Explanation: Another port of @tsh's JavaScript solution.

```
Ｎθ

```

Input the number to convert.

```
Ｗθ«

```

Repeat until it is zero.

```
←§.+.-θ

```

Output the previous digit using cyclic indexing. The digits are output right-to-left so that the final output is in the correct order.

```
≔÷⁺¬﹪⊕θ⁴θ²θ

```

Divide by two, rounding to even.

---
Tags: code-golf, binary, base-conversion
---


title: Game of Life, but on a 4-8-8 tiling

text:
# Question
Title: Game of Life, but on a 4-8-8 tiling
## Background

The 4-8-8 tiling looks like this:

For the purpose of this challenge, we take the orientation of the tiling as exactly shown above. In plain English words, we take the tiling so that it can be seen as a rectangular grid of alternating octagons and squares, the upper left corner being an octagon.

In order to define a Game of Life on this tiling, we use a simplified definition of neighborhood: cell B is a neighbor of cell A if the two cells share an edge. An octagon has at most 8 neighbors and a square has at most 4. We assume the cells outside the given grid are simply non-existent (or alternatively, hardwired as all dead).

Other than the grid differences, we use the rules of Game of Life as-is:

* An off-cell is turned on if it has exactly three on-neighbors, and is kept off otherwise.
* An on-cell is kept on if it has exactly two or three on-neighbors, and is turned off otherwise.

## Challenge

Given a rectangular grid of on- and off-cells on the 4-8-8 tiling as defined above, calculate the next generation in Game of Life.

The on- and off-cells can be represented by any two distinct, consistent values respectively. The rectangular grid may be represented in any suitable format supported by your language. The output format doesn't need to be the same as the input format. The grid can be assumed to have at least two rows and two columns.

Standard rules apply. The shortest code in bytes wins.

## Test cases

Generated using this Python program.

For simplicity, the grid is represented as a list of lists of zeros (off) and ones (on). Some test cases have multiple steps, which means if your program is given the first state, it should produce the second, and if given the second, it should produce the third, etc.

```
[[1, 1],
 [1, 1]] -> unchanged

[[1, 1],
 [0, 1]] -> unchanged

[[1, 1],
 [1, 0]] ->
[[1, 0],
 [0, 1]] ->
[[0, 0],
 [0, 0]]

[[0, 0, 0],
 [1, 1, 1],
 [0, 0, 0]], ->
[[0, 0, 0],
 [0, 1, 0],
 [0, 0, 0]]

[[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]] ->
[[0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0]] -> back to first

[[1, 0, 0, 1, 1],
 [1, 1, 0, 1, 0],
 [0, 0, 1, 0, 0],
 [0, 1, 0, 1, 1],
 [1, 1, 0, 0, 1]] ->
[[1, 0, 1, 1, 1],
 [1, 1, 1, 1, 0],
 [1, 1, 0, 1, 1],
 [0, 1, 1, 1, 1],
 [1, 1, 1, 0, 1]] ->
[[1, 1, 0, 1, 1],
 [1, 0, 1, 0, 1],
 [0, 1, 0, 1, 0],
 [1, 0, 1, 0, 1],
 [1, 1, 0, 1, 1]] ->
[[1, 0, 1, 0, 1],
 [0, 0, 0, 0, 0],
 [1, 0, 0, 0, 1],
 [0, 0, 0, 0, 0],
 [1, 0, 1, 0, 1]] ->
[[0, 0, 0, 0, 0],
 [0, 1, 0, 1, 0],
 [0, 0, 0, 0, 0],
 [0, 1, 0, 1, 0],
 [0, 0, 0, 0, 0]] -> all zeros

```

# Answer
# JavaScript, 99 bytes

```
a=>a.map((r,y)=>r.map((c,x)=>((g=i=>i--&&((i%2|x+~y&i!=4)&a[~-(y+i/3)]?.[x+i%3-1])+g(i))(9)|c)==3))

```

```
f=

a=>a.map((r,y)=>r.map((c,x)=>((g=i=>i--&&((i%2|x+~y&i!=4)&a[~-(y+i/3)]?.[x+i%3-1])+g(i))(9)|c)==3))

print = (a, contain) => {
  let t = contain.appendChild(document.createElement('div'));
  t.className = 'grid';
  a.map(r => {
    let tr = t.appendChild(document.createElement('div'));
    tr.className = 'row';
    r.map(c => {
      tr.appendChild(document.createElement('div')).className = c ? 'on cell' : 'off cell';
    });
  });
}

test = (a, n, contain) => {
  contain ??= document.body.appendChild(document.createElement('div'));
  contain.className = 'testcase';
  print(a, contain);
  if (n) test(f(a), n - 1, contain);
};

test([[true, true],
 [true, true]], 1);

test([[true, true],
 [false, true]], 1);

test([[true, true],
 [true, false]], 2);

test([[false, false, false],
 [true, true, true],
 [false, false, false]], 1);

test([[false, false, false, false, false],
 [false, true, true, true, false],
 [false, false, false, false, false]], 2);

test([[true, false, false, true, true],
 [true, true, false, true, false],
 [false, false, true, false, false],
 [false, true, false, true, true],
 [true, true, false, false, true]], 5);
```

```
body { background: #ccc; }
.grid { display: flex; flex-direction: column; padding: 10px; }
.grid + .grid { margin-top: 10px; }
.row { display: flex; }
.cell { width: 23px; height: 23px; position: relative; padding: 0; }
.on { --cell-color: white; }
.off { --cell-color: black; }
.cell::before { content: " "; display: block; position: absolute; }
.cell::before {
  width: 16px; height: 16px;
  top: 4px; left: 4px;
  background-image:
    linear-gradient(to bottom, var(--cell-color), var(--cell-color)),
    linear-gradient(to right, gray, gray);
  background-position: 1px 1px, top left;
  background-repeat: no-repeat;
  background-size: 14px 14px, 16px 16px;
}
.row:nth-child(2n) .cell:nth-child(2n)::before,
.row:nth-child(2n+1) .cell:nth-child(2n+1)::before {
  width: 34px; height: 34px;
  top: -5px; left: -5px;
  background-image:
    linear-gradient(to bottom, gray 0, gray 1px, transparent 1px, transparent 33px, gray 33px, gray 34px),
    linear-gradient(to right, gray 0, gray 1px, transparent 1px, transparent 33px, gray 33px, gray 34px),
    linear-gradient( 135deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px),
    linear-gradient(-135deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px),
    linear-gradient(  45deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px),
    linear-gradient( -45deg, transparent 0, transparent 7px, gray 7px, gray 8px, var(--cell-color) 8px, var(--cell-color) 20px);
  background-position: top center, left center, top left, top right, bottom left, bottom right;
  background-repeat: no-repeat;
  background-size: 16px 34px, 34px 16px, 20px 20px, 20px 20px, 20px 20px, 20px 20px;
}
.testcase { padding: 10px; }
.testcase + .testcase { border-top: 1px solid gray; }
```
> 5 votes

# Answer
# JavaScript (ES6), 109 bytes

```
a=>a.map((r,y)=>r.map((n,x)=>[...'0124689',10].map(i=>n+=x-~y&1|i&5&&(a[y+~-(i/4)]||0)[x+i%4-1]<<1)|n>4&n<8))

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES2020), 139 bytes

```
x=>x.map((y,i)=>y.map((v,j)=>(v+=(g=(a,b)=>x[i+a]?.[j+b]*2|0)(0,1)+g(1,0)+g(n=-1,0)+g(0,n)+(i+j+1)%2*(g(1,1)+g(1,n)+g(n,1)+g(n,n)))>4&v<8))

```

Try it online! (Link uses a 142 byte version, as TIO doesn't support the ES2020 `?.` operator)

## Explanation

```
x=>x.map((y,i)=>y.map((v,j)=> // Map over each element of the grid:
  (v+=                          // Add to the value of the cell (0 or 1):
    (g=(a,b)=>x[i+a]?.[j+b]*2|0)  // Define a function g to get neighbor
                                  // values; 2 for alive, 0 for dead.
        (0,1)+g(1,0)              // Sum the neighbor values for the cells
      +g(n=-1,0)+g(0,n)           // above, below, left, and right.
      +                           // Add the product of:
        (i+j+1)%2                  // 1 for octagons, 0 for squares.
        *(g(1,1)+g(1,n)             // The sum of the values for the
         +g(n,1)+g(n,n))            // diagonal neighbors.
  )>4&v<8                       // 1 if the sum is >4 and <8, 0 otherwise.
))                              // This is true for:
                                // - 5 (1 (alive cell) + 4 (2 alive neighbors))
                                // - 6 (0 (dead cell) + 6 (3 alive neighbors))
                                // - 7 (1 (alive cell) + 6 (3 alive neighbors))

```
> 2 votes

# Answer
# MATL, ~~35~~ ~~33~~ ~~32~~ 31 bytes

```
t1Y6Z+G5B&*Z+G&n:w:!+o~*+E+5:7m

```

Try it online! Or verify all test cases.

### How it works

```
t      % Implicit input: binary matrix. Duplicate
1Y6    % Push [0 1 0; 1 0 1; 0 1 0]. This mask defines cells that are neighbours
       % of the central cell, whether the central cell is a square or an octagon
Z+     % 2D convolution, maintaining size. This counts neighbours according to
       % the above mask. (*)
G      % Push input again
5B     % Push 5, convert to binary: gives [1 0 1]
&*     % All pair-wise products: gives [1 0 1; 0 0 0; 1 0 1]. This mask defines
       % cells that are neighbours of octagons squares and not of squares
Z+     % 2D convolution, maintaining size. (**)
G      % Push input again
&n     % Push number of rows R, then number of columns C
:      % Range: gives row vector [1 2 ... C]
w      % SWap: moves R to top
:!     % Range, transpose: gives column vector [1; 2; ... ; R]
+      % Add, element-wise with broadcast
o~     % Modulo 2, negate. This gives a matrix the same size as the input with a
       % checkered pattern, where 1 indicates octagon and 0 indicates square
*      % Multiply, element-wise. This keeps the results (**) for cells that are
       % octagons, and sets the rest to 0
+      % Add (*) and (**). This gives the number of neighbours of each cell
E      % Multiply by 2
+      % Add to copy of the input that is at the bottom the stack. (***)
5:7    % Push range [5 6 7]
m      % Ismember. This gives 1 for cells at which (***) equals 5 (meaning the
       % cell was active and had 2 active neighbours), 6 (it was inactive and had
       % 3 active neighbours) or 7 (it was active and had 3 active neighbours)
       % Implicit display

```
> 2 votes

# Answer
# Jelly, 37 bytes

```
ŒJ§ị3ṗ2$’’A§ĠịƲḊ;\¤+"Ʋf€$œị⁸§ṁ,+¥=3o/

```

Try it online!

A monadic link taking and returning a 2D list of 0 and 1.
> 1 votes

# Answer
# Python 3, 136 bytes

Returns a 2d-list of booleans.

```
lambda c,E=enumerate:[[sum(sum([([0]+l)[x-y:x-y+3]for l in c[y+y%~y:y+2]],[])[x%2::1+x%2])-~x*v%2|v==3for x,v in E(r,y)]for y,r in E(c)]

```

Try it online!
> 0 votes

# Answer
# Charcoal, 65 bytes

```
ＷＳ⊞υιυＵＭυ⪪ι¹ＦＬυ«Ｊ⁰ιＦＬ§υι«§≔§υικ¬÷⁻⁷⁺ＩＫＫ⊗№⎇﹪⁺ικ²ＫＶＫＭ1³→»»Ｊ⁰¦⁰Ｅυ⪫ιω

```

Try it online! Link is to verbose version of code. Takes input as a newline-terminated list of strings of `0`s and `1`s. Explanation:

```
ＷＳ⊞υιυ

```

Input the strings and print them to the canvas.

```
ＵＭυ⪪ι¹

```

Split the strings into character lists so that they can be replaced.

```
ＦＬυ«

```

Loop over each of the lists.

```
Ｊ⁰ι

```

Jump to the start of its line.

```
ＦＬ§υι«

```

Loop over the cells of the list.

```
§≔§υικ¬÷⁻⁷⁺ＩＫＫ⊗№⎇﹪⁺ικ²ＫＶＫＭ1³

```

Look at the Von Neumann or Moore neighbourhood depending on the parity of the square, count the number of `1`s, double that, add on the current square, subtract from 7, integer divide by 3, and complement the result. This gives the new live state of the cell.

Move to the next cell.

```
»»Ｊ⁰¦⁰Ｅυ⪫ιω

```

Overwrite the canvas with the new states.
> 0 votes

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