title: Concatenative counting

text:
# Question
Title: Concatenative counting
Your challenge is to write **N** snippets of code such that, when you concatenate the first **K** ≥ 1 together, they produce the number **K**. The higher **N**, the better. Here's the catch: you may not use any character more than once across your snippets.

## Rules

* You may use the same character multiple times in one (and only one) snippet.
* These snippets must be concatenated *in the order they are presented*, without skipping any.
* You must write at least two snippets.
* All snippets must be in the same language.
* Remember: snippets **do not** have to be full programs or functions, nor do they have to function on their own. `-1` is a valid snippet in Java, e.g.
* All resulting concatenations must output the respective **K** value.
* The winner is the person with the highest **N** value. Tie-breaker is shortest overall program length in bytes.

## Example

Suppose your snippets were `AD`, `xc`, `123`, and `;l`. Then:

* `AD` should produce `1`
* `ADxc` should produce `2`
* `ADxc123` should produce `3`
* and `ADxc123;l` should produce `4`.

This program would have a score of **4**.

# Answer
> 10 votes
# Python 3, 1 112 056 snippets, 4 383 854 bytes

This is very similar to @WheatWizard's Python 2 answer. I started working on this shortly before it was posted, but sorting out Python's quirks regarding non-ASCII characters and long lines took some time. I discovered that Python reads lines 8191 bytes at a time, and when those 8191 bytes contain only a part of a multi-byte character, Python throws a *SyntaxError*.

The first snippet uses an encoding from Fewest (distinct) characters for Turing Completeness.

```
exec('%c'%(111+1)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(111+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(111)+'%c'%(111+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+1+1)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+1)+'%c'%(11+11+11+11+1+1+1+1+1)+'%c'%(11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11)+'%c'%(11+11+11+11+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1++++++++++1))

```

This monstrosity simply build the following string and executes it.

```
print(len(open(__file__).read())-1260)

```

The following snippets are all exactly one character long. The next three characters are `\n`, `\r`, and `#`. All remaining Unicode characters (except surrogates) follow in a specific order, so they align with the 8191-byte boundary.

The following script generates the appropriate programs for input **k** between **1** and **1112056**.

```
j = 4
s = "exec('%c'%(111+1)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(111+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(111)+'%c'%(111+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+11)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+1+1)+'%c'%(111+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1+1)+'%c'%(11+11+11+11+11+11+11+11+1+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+11+11+11+11+11+1)+'%c'%(11+11+11+1+1+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1+1)+'%c'%(11+11+11+11+1)+'%c'%(11+11+11+11+1+1+1+1+1)+'%c'%(11+11+11+11+1+1+1+1+1+1)+'%c'%(11+11+11+11+11)+'%c'%(11+11+11+11+1+1+1+1)+'%c'%(11+11+11+1+1+1+1+1+1+1++++++++++1))"
l = 1
c = \
        [
                None,
                [n for n in range(0x80) if chr(n) not in "\n\r#%'()+1cex"],
                [*range(0x80, 0x800)],
                [*range(0x800, 0xd800), *range(0xe000, 0x10000)],
                [*range(0x10000, 0x110000)]
        ]

k = int(input())
assert k in range(1, 1112057)
s += '\n\r#'[:k - 1]
k -= 4

while j:
                while k > 0 and c[j] and l + j < 8191:
                        s += chr(c[j].pop())
                        l += j
                        k -= 1
                if k < 1:
                        print(end = s)
                        break
                elif c[j] == []:
                        j -= 1
                else:
                        s += chr(c[8191 - l].pop())
                        print(end = s)
                        k -= 1
                        s = ''
                        l = 0

```

# Answer
> 13 votes
# Perl 5, ~~50,091~~ 151 snippets

First snippet:

```
use utf8; print length A

```

~~2nd through 26th snippets: `B` through `Z`~~

~~27th through 46nd snippets: `a` through `z`, excluding the characters in "length"
47th through 56th snippets: `0` through `9`
~~

~~57th snippet: `_`~~

~~The remaining snippets are the 50,105 individual Unicode characters which Perl regards as "word" characters, excluding the 14 distinct word characters in the initial snippet, in any order.~~

Well, it was a nice thought, but it turns out that after a certain length Perl gives you an "identifier too long" error. This is the longest combined program I was able to get Perl to digest:

```
use utf8; print length A012345679BCDEFGHIJKLMNOPQRSTUVWXYZ_abcdjkmoqsvwxyzĀāĂăĄąĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıĲĳĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňŉŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţ

```

The perldiag manual page says "Future versions of Perl are likely to eliminate these arbitrary limitations" but my Perl 5.18 has not done so.

Explanation:

In non-strict mode, Perl 5 interprets unquoted strings of word characters as "barewords," essentially quoting them for you automatically. They're usually best avoided, but they sure help here!

# Answer
> 10 votes
# JavaScript (ES6, V8 6.x), ~~52~~ ~~50298~~ ~~119526~~ ~~119638~~ ~~119683~~ 128781 snippets, ~~88~~ ~~149147~~ ~~575179~~ ~~575631~~ ~~576121~~ 612789 bytes

Farther below is a Stack Snippet that generates the full program, evaluates it, and creates a download link for the file. That snippet will continue to generate better answers as later versions of Unicode are supported by newer versions of JavaScript, which add new valid identifiers to the language.

### Using ASCII only

```
console.log(new Proxy({},{get:(n,{length:e})=>e>>(e/e)}).nn$$00112233445566778899AABBCCDDEEFFGGHHIIJJKKLLMMNNOOQQRRSSTTUUVVWWXXYYZZ__aabbccddffiijjkkmmppqqssuuvvzz)
```

## Explanation

This uses the metaprogramming technique of `Proxy` to enable a get handler trap on the object and access the property name as a string, returning the identifier's `length / 2` as its value.

With the first snippet starting as `new Proxy({},{get:(n,{length:e})=>e>>(e/e)}).nn`, each additional snippet added increments the string `length` of the identifier by `2` by making sure to `.repeat()` the respective code point twice for 2 byte utf-16 characters, and once for 4 byte utf-16 characters.

## Identifiers in JavaScript

In the ECMAScript Specification, an `IdentifierName` is defined with the following grammar:

> ```
> IdentifierName::
>   IdentifierStart
>   IdentifierName IdentifierPart
>
> IdentifierStart::
>   UnicodeIDStart
>   $
>   _
>   \UnicodeEscapeSequence
>
> IdentifierPart::
>   UnicodeIDContinue
>   $
>   _
>   \UnicodeEscapeSequence
>   <ZWNJ>
>   <ZWJ>
>
> UnicodeIDStart::
>   any Unicode code point with the Unicode property “ID_Start”
>
> UnicodeIDContinue::
>   any Unicode code point with the Unicode property “ID_Continue”
>
> ```

## Generating the answer

Initially using the "ID\_Continue" Unicode property, I wrote a Node.js script that generates the full answer. Now it's just a client-side script that uses a naive `eval()` to test for valid characters, iterating through all the unicode code points instead:

```
// first snippet
let answer = 'new Proxy({},{get:(n,{length:e})=>e>>(e/e)}).nn'

const used = Array.from(
  answer,
  c => c.codePointAt(0)
).sort(
  (a, b) => a - b
)

// create a O(1) lookup table for used characters in first snippet
const usedSet = Array.from(
  { length: Math.max(...used) + 1 }
)

for (const codePoint of used) {
  usedSet[codePoint] = true
}

// equal to 1 for first snippet
let snippets = eval(answer)
let identifier = ''

for (let codePoint = 0, length = 0x110000; codePoint < length; codePoint++) {
  const character = String.fromCodePoint(codePoint)

  // if unused
  if (usedSet[codePoint] === undefined) {
    // if valid `IdentifierPart`
    try {
      eval(`{let _${character}$}`)
    } catch (error) {
      // console.log(character)
      continue
    }

    // repeat so that `snippet.length === 2`
    identifier += character.repeat(2 / character.length)
    snippets++
  }
}

// number of snippets generated
console.log(`snippets: ${snippets}`)

const program = `console.log(${answer + identifier})`

// output of program to validate with
eval(program)

// download link to check number of bytes used
dl.href = URL.createObjectURL(new Blob([program], { type: 'text/javascript' }))
```

```
<a id=dl download=answer.js>Click to Download</a>
```

Running `stat -f%z answer.js` yields a byte count of 612802, but we subtract 13 bytes for the `console.log(` and `)` wrapping the actual submission.

## Encoding

The source is stored as utf-8, which is reflected in the enormous byte count of the answer. This is done because Node.js can only run source files encoded in utf-8.

JavaScript internally stores strings with utf-16 encoding, so the string "character length" returned in JavaScript is actually just half the number of bytes of the string encoded in utf-16.

# Answer
> 10 votes
# Python 2, score 32

```
for r in range(32):locals()[''.join(map(chr,range(65,66+r)[:26]+range(117,92+r)))]=r+1
print A

```

With subsequent snippets `B`, `C`, `D`, … `Y`, `Z`, `u`, `v`, `w`, `x`, `y`, `z`.

In a twist of dramatic irony, Python 3 supports Unicode identifiers, which would let us get very silly with this trick — but it can’t `print` without parentheses. I could cram digits into the identifier, too, but I don’t think this approach is very fun to squeeze more out of.

Try it online!

# Python 2, score 18, less cheat-y

```
print 0x10-1&0x1
print 0x10-1&0x12
print 0x10-1&0x123
print 0x10-1&0x1234
print 0x10-1&0x12345
print 0x10-1&0x123456
print 0x10-1&0x1234567
print 0x10-1&0x12345678
print 0x10-1&0x123456789
print 0x10-1&0x123456789A
print 0x10-1&0x123456789Ab
print 0x10-1&0x123456789Abc
print 0x10-1&0x123456789Abcd
print 0x10-1&0x123456789AbcdE
print 0x10-1&0x123456789AbcdEf
print 0x10-1&0x123456789AbcdEf^((()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==()))
print 0x10-1&0x123456789AbcdEf^((()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==()))|[[[]]>[]][[]>[]]
print 0x10-1&0x123456789AbcdEf^((()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==())+(()==()))|[[[]]>[]][[]>[]]<<False**False

```

Try it online!

# Answer
> 6 votes
# Python 2, score ~~6~~ 10

+3 thanks to pizzapants184
+1 thanks to WheatWizard

```
4/4
*2
-~0
+1
|5
^3
&776%6
and 8
if[]else[9][9>9]
.__xor__((""=="").__xor__((""=="")<<(""=="")))

```

Try it online!

# Answer
> 6 votes
# TI-Basic (83 series, OS version 1.15 or higher), score: ~~17~~ ~~18~~ ~~19~~ 24

(Tiebreaker: 53 bytes.)

You can get a very large score by abusing string length as usual: begin with ~~`length("A`~~ `length("length(` (as @Scrooble points out) and keep adding single-token snippets to the end. TI-Basic has over 700 of those, so that actually works pretty well. But here's another approach:

```
int(log(11
2
3
4
5
6
7
8
9
0
Xmax
Ymax
nMax
abs(Xmin
Ymin
ππ
eee
³
²
₁₀^(₁₀^(X
+e^(⁻e^(Y))))
/√(sub(Z!
°
randrandrand

```

Note that TI-Basic is tokenized, so (for example) the `e^(` command does not use any of the characters `e`, `^`, `(`.

Relies on an undocumented feature of the `sub(` command: in addition to finding substrings, it can also be used to divide a number by 100.

This works if it's running on a fresh calculator, which lets us assume that `X`, `Y`, `Z` are all zero, that the window variables are set to their standard values, that the calculator is in radian mode, and that `rand`'s first three outputs will be about `0.943`, `0.908`, `0.146`.

# Answer
> 4 votes
# PowerShell, 25 bytes, Score 5

```
' '.count*2+!""-(-1)|%{5}

```

Snippet 1: `' '.count` outputs `1`. It does this by taking the `.count` of an string, which is one because there is only one string. Try it online!

Snippet 2: `*2` outputs `2` because we take the `1` from the previous snippet and multiply it by two Try it online!

Snippet 3: `+!""` outputs `3` by adding the Boolean-not of an empty string. This implicitly casts the empty string to `$true`, which is again implicitly cast to `1`, so we're adding one Try it online!

Snippet 4: `-(-1)` outputs `4` by simply subtracting negative one Try it online!

Snippet 5: `|%{5}` outputs `5` by taking the previous number into a loop and each iteration of that loop (only one, because there's only one input number) outputs `5` Try it online!

*Thanks to Jan for an alternate means of coming up with `4` and a crafty way of coming up with `5`.*

# Answer
> 4 votes
# C, 10 snippets, 45 bytes

```
sizeof(char)              // sizeof(char) = 1
<<9/9                     // Multiply by two.
|1                        // 2 or 1 = 3
,4                        // Discard previous expression, return 4.
+!!8                      // Add one.
^3                        // 5 xor 3 = 6
&66                       // 3 and 66 = 2, 5 xor 2 = 7 (& has higher precedence)
??'0xF                    // Trigraph for '^'. 7 xor 15 = 8
-~-2                      // ~-2 = 1, 7 xor 14 = 9
*57%5                     // 1*57%5 = 2, 7 xor 13 = 10

```

Try it online!

# Answer
> 4 votes
# MATL, Score ~~8~~ 15, ~~64~~ 123 bytes

```
rg             % 1 Random number, make boolean (1)
Q              % 2 Increment
Yq             % 3 Nth prime
a,E]           % 4 any (convert to boolean 1. Do twice: Multiply by 2
T+             % 5 Add True
F~_-           % 6 Subtract negative (not(false)) = 6-(-1)
:sI/           % 7 Range 1:6, sum (21), divide by 3
A8*            % 8 All elements (True). Multiply by 8
d9             % 9 Clear stack, push 9
x10            % 10 Clear stack, push 10
WBPf           % 11 Raise 2^10. Convert to binary [1 0 ... 0], flip [0 0 ... 1]. Find
23ZP           % 12 Push 23, and calculate the distance between 11 and 23
yyyyyyyyyyyyyyyyyyyyyyyyhhhhhhhhhhhhhhhhhhhhhhhhz  % 13. Duplicate and count elements
tttttttttttttvvvvvvvvvvvn  % 14 Duplicate and count elements
OOOOOOOOOOOOOON&           % 15 Add bunch of zeros, output size of stack

```
* Got to 12 with help from Luis Mendo! Using `11,23ZP` was his idea, along with changing `3` with `I` for snippet 7.
* Got to 15 with more help from Luis. `OO...N&` was his idea.

~~More to come.~~ I don't know the MATL functions by heart, so I had to go back and forth and back and forth in the documentation... :)

Try it online!

# Answer
> 3 votes
# , score 10

```
é1
<C-a>
r3
DÉ4
ñóä/5ñ
ddá6
xÁ7
C8<esc>
R9<C-c>
ø.<cr>ÎA0

```

Try it online!

# Answer
> 2 votes
# Jelly, 253 bytes, score 250

```
L}“L

```

Subsequent 1-char snippets:

```
¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż

```

Note:  may also be replaced by `\n`, they're the same byte in Jelly's codepage.

After you append all those snippets, you can then append the 2-char snippet `”‘`.

+1 thanks to Dennis.

Try it online!

# Answer
> 2 votes
# Lenguage, 1 112 064 snippets

The **n**th snippet consists of **23n-1** repetitions of the **n**th non-surrogate Unicode character, up to and including the **1 112 064**th and last non-surrogate character of the current Unicode standard.

Output is in unary (using the null byte as digit) for simplicity. Decimal is possible, but it will make the programs even longer. With unary, we can test the first programs.

For **n = 1**, we get **4** repetitions of **U+0000**. This is equivalent to the brainfuck program `.`, which prints one null byte.

For **n = 2**, we get **32** repetitions of **U+0001**, for a total of **36** characters. This is equivalent to the brainfuck program `..`, which prints two null bytes.

For **n = 3**, we get **256** repetitions of **U+0002**, for a total of **292** characters. This is equivalent to the brainfuck program `...`, which prints three null bytes.

And so forth, up to **n = 1 112 064**.

# Answer
> 2 votes
# BASIC (ZX Spectrum), score 244 (new score 247) \[is this cheating?\]

Snippet 1:

```
2356 PRINT PEEK (PEEK 23635+256*PEEK 23636+2)+256*PEEK (PEEK 23635+256*PEEK 23636+3)-56-66

```

Snippet 2: `:`

Snippet 3: `REM`

Snippets 4-244: Single-character snippets, using all characters not in snippets 1, 2 and 3.

**Explanation**

*Characters*

On Spectrum, `PRINT` is a single character (code 245). The snippet 1 uses 11 different characters: `2`, `3`, `5`, `6`, `+`, `-`, `*`, `(`, `)`, `PRINT` and `PEEK` What you see as spaces are a part of characters `PRINT` and `PEEK`, so the space itself hasn't been used. I decided to give the line number 2356 because these are the only digits present in the code.

Characters 13 and 14 are not allowed. That means there are 243 characters left for snippets 2-244, starting with `:` and `REM` to avoid the code that would produce error or do anything else.

*How it works*

This is why I'm not sure whether this answer is by the book.

23635 is the memory location for 16-bit system variable PROG, stored as LH. (The value is usually 23755. But apart from wrong result if it happens not to be the case, using this number directly, even though it would shorten the code, would cost me extra digit characters.) The value of PROG is the memory location where the program itself is stored. The first two bytes are the line number stored as HL, the following two bytes are the length of the line stored as LH. That's how the program looks up its own line's length, so something appropriate needs to be subtracted

**Saving characters**

Considering how numbers are stored, the line could have ended with -114 so that snippet 1 would produce 1. But I didn't want to use extra digits, so I instead took away two 2-digit numbers, which then had to add up to 122; 56 and 66 did nicely.

The code is a bit ugly with all nesting and calculating value of PROG (`PEEK 23635+256*PEEK 23636`) twice. But if I stored it and then used the stored value, it would cost extra characters / snippets - the line could start like

```
2356 LET p=PEEK 23635+256*PEEK 23636: PRINT PEEK (s+2)...

```

which would use 4 additional characters: `LET`, `p`, `=` and `:`.

Maybe I'll engineer this so that all numbers are calculated from numbers that use only 1 digit and gain 3 snippets.

**EDIT:**

Here is the new snippet 1 (that's how a long single line gets wrap-displayed on the Spectrum, so if you want to test the code , that will help you see that you typed it correctly):

```
1111 PRINT +PEEK (PEEK (11111+11
111+1111+(1+1+1)*(111-11)+1+1)+(
111+111+11+11+11+1)*PEEK (11111+
11111+1111+(1+1+1)*(111+1-11))+1
+1)+(111+111+11+11+11+1)*PEEK (P
EEK (11111+11111+1111+(1+1+1)*(1
11-11)+1+1)+(111+111+11+11+11+1)
*PEEK (11111+11111+1111+(1+1+1)*
(111+1-11))+1+1+1)-111-111-111-1
11-111-111

```

I could gain another snippet by avoiding the `+` and just make do with `-`. I'm not going to try it, this was enough of an ordeal.

# Answer
> 2 votes
# dc, score 13, 58 bytes

```
I3%                   #I is the default input radix, 10, mod 3 yields 1
1+                    #Add one
2^2^2^Z               #2^8=256, Z pushes the number of digits to the stack
6*v                   #Square root of 18 = ~4.24, at precision 0 we get 4
c5                    #Start getting lazy, clear the stack and push 5
_F-E-                 #Subtract negative 15, then subtract 14
ss7                   #Lazy, 'drop' the value by storing it, push 7
SS8                   #Lazy, 'drop' the value by storing it, push 8
d::9                  #Lazy, 'drop' the value by storing it, push 9
;;kA                  #Recall element 9 from nonexistant array ; which is zero, set precision, push A (10)
iB                    #Set input radix to 10, push B (11)
oD                    #Set output radix to 11, push D (13, or 12 in base 11)
 4CCCCCCr/4C/CC/4/    #We have division and the digits 4 and C left, this might not be the optimal way to get us to 13 but it does the job

```

Try it online! (Note, the TIO version adds an `f` after each snippet to print the entire stack, showing that each snippet only leaves a single value on the stack; also I forgot the leading space on the last snippet which doesn't matter functionally when they're broken apart by line breaks but does count to my character usage)

Each additional snippet concatenation leaves the desired value and only the desired value on the stack. After hitting 12, I had kind of run out of ways to eat the stack. I tried to use math operations early on since they gobble up the stack and as we get into larger numbers it gets trickier to manage that way. When all is said and done, I have only the digit 0 left to play with and very little in the way of stack-popping, so I think 13 is pretty close to maxed out. I'm sure there are many similar (and likely shorter) ways of accomplishing this in dc, this just kind of fell into place. Note that cygwin handles A-F mixed in with 0-9 differently from most versions of dc, `44C4r/CC 4//` works for the final snippet in cygwin.

# Answer
> 2 votes
# Klein 011, 9 snippets

**Snippet 1**

```
!@1!aaaaaaaaaaaaaaaaaaaaa/a

```

Try it online!

**Snippet 2**

```
2((2|bbb0b2bbbb4bbbbbbbb

```

Try it online!

**Snippet 3**

```

c\*3ccccccccccccccccccccc\ccccccccc3c6cccc9
c\

```

Try it online!

**Snippet 4**

```
ddddddddddddddddddddddd>$d:d:++-$:+:+++$:?:-$-+++

```

Try it online!

**Snippet 5**

```
ee

```

Try it online!

**Snippet 6**

```
fff

```

Try it online!

**Snippet 7**

```
ggggg

```

Try it online!

**Snippet 8**

```
hh

```

Try it online!

**Snippet 9**

```
iiiii

```

Try it online!

## Explanation

This was a really fun challenge for Klein. Klein's unique topology allows for a lot of interesting stuff to be done. As you might notice answers 5-9 are just adding filler (letters do nothing in Klein so I used them as filler) to the code to stretch out the bounding box. This causes the ip to take a different path through earlier parts of the code because of Klein's unique topology.

I'm going to make a full explanation later, but for now here is a easier to understand version of the program with all of the letters replaced with `.`s.

```
!@1!...................../.2((2|...0.2....4........
.\*3.....................\.........3.6....9
.\.......................>$.:.:++-$:+:+++$:?:-$-+++.................

```

Try it online!

# Answer
> 2 votes
# \>\<\>, Score: ~~Infinity~~ 1,112,064-6 = 1,112,058

### Snippet 1 (6 bytes)

```
"l4-n;

```

This snippet outputs the amount of characters after the ; plus one. This can be extended to ~~infinite~~ very large amount of snippets of one character each. A quick google tells me there are 1,112,064 possible Unicode characters, minus the 6 I’ve already used.

Try It Online

# Answer
> 1 votes
# , score: 79

Credit to Sean's Perl answer for the inspiration; this abuses some quirks of the R interpreter.

First snippet:

```
nchar(scan(,""))
a

```

subsequent snippets are the characters in:

```
bdefgijklmopqtuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@$%^&*_+|\[]{}:?><;

```

Try it online!

The `scan` function reads data from the file `""` which defaults to `stdin()`.

The docs for `stdin()` indicate that:

> When R is reading a script from a file, the *file* is the ‘console’: this is traditional usage to allow in-line data (see ‘An Introduction to R’ for an example).

Hence, the subsequent data become the file. This can be trivially expanded, and can work with multiple different encodings.

# Answer
> 1 votes
# Pyke, 256 bytes, score 254

Please note that these are hex codes of the actual bytes, separated by spaces, since there the null byte (`\x00`) is included.

Starting snippet:

```
6C 22 00

```

Subsequent 1-char snippets:

```
01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F 60 61 62 63 64 65 66 67 68 69 6A 6B 6D 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF

```

Try it here!

# Answer
> 1 votes
# Java 8, 7 snippets (19 bytes)

```
1
*2
-~0
>4?4:4
|5
^3
7%7

```

Just a start, will continue working on it.

Try it here.

**Explanation:**

Execution precedence is perhaps made clearer when I add parenthesis:

```
((1*2)-~0)>4?4:4|(5^(37%7))

```
* `a*b`: Multiply `a` with `b`
* `~a`: `-a-1`
* `a>b?x:y`: `if(a>b){ x }else{ y }`
* `a|b`: Bitwise-OR `a` with `b`
* `a^b`: Bitwise-XOR `a` with `b`
* `a%b`: `a` modulo-`b`

# Answer
> 1 votes
# TeX, score 61 (possibly 190)

First snippet:

```
\def\len#1{\expandafter\glen\string#1=}
\def\glen#1{\tlen}
\def\tlen#1{\if#1=\let\tlen\end\number\count1\else\advance\count1by1\fi\tlen}
\count1=-1
\catcode33=11
\catcode34=11
\catcode36=11
\catcode37=11
\catcode'46=11
\catcode40=11
\catcode41=11
\catcode42=11
\catcode43=11
\catcode44=11
\catcode45=11
\catcode46=11
\catcode47=11
\catcode56=11
\catcode57=11
\catcode'72=11
\catcode'73=11
\catcode60=11
\catcode62=11
\catcode63=11
\catcode64=11
\catcode'133=11
\catcode'135=11
\catcode'136=11
\catcode'137=11
\catcode'140=11
\catcode124=11
\catcode126=11
\len\t

```

Other 60 snippets: in any order, each containing one character out of

```
!"$%&()*+,-./:;<>?@[]^_`|~89ABCDEFGHIJKLMNOPQRSTUVWXYZhjkqwz

```

Explanation: `\len`, which is invoked at the end, converts a control sequence into a string, each character (including `\`) is one character token of that string; then `\glen` gobbles token `\`, then `\tlen` counts remaining tokens. It therefore outputs the length of that control sequence (not including `\`).

Characters from other snippets extend the control sequence which is initially just `\t`. A multi-character control sequence has to be made up of letters only, but they all count as letters because they have all been assigned category code 11 (using ASCII codes so that the characters themselves don't appear in the first snippet).

I decided to use octal codes for some characters which cost me one symbol, `'` but saved me two digits, 8 and 9, so I gained one snippet. Possibly could have gained a couple more if I didn't need `\expandafter`.

**Output**

Possible alteration: wrap `\number\count1` into `\message{}` so the output doesn't go into `.dvi` output but instead to console output and `.log`. It doesn't cost any extra letters.

**190**

Unfortunately TeX works with ASCII and not Unicode (or does it now?), but my solution could possibly be extended to include 129 more single-character snippets containing the characters with codes 127-255. Maybe even some characters before 32. Character 32 (space) didn't work, otherwise I'd put it into a snippet as well - didn't need it in the first snippet. Of course, each of these additional characters would have to be `\catcode`d into a letter in the first snippet.

# Answer
> 1 votes
# Python 2, 110 snippets

Here is the complete snippet:

```
print((((len(open(__file__).read())-44.))))

#	 !"$%&'*+,/012356789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^`bcghjkmqsuvwxyz{|}~

```

Try it online!

The first snippet is

```
print((((len(open(__file__).read())-44.))))

```

And then the next 109 snippets are the next 109 bytes.

This is pretty "cheaty" as Lynn puts it. The first snippet opens the file and subtracts 44 from its length, then each other snippet adds 1 to the length of the file without changing the logic of the program as a whole. thus increasing the result of the output by 1.

# Answer
> 0 votes
# Pyth, 124 snippets

```
l"x00x01x03x04x05x06x07x08
x0bx0c
x0ex0fx10x11x12x13x14x15x16x17x18x19x1ax1bx1cx1dx1ex1f !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijkmnopqrstuvwxyz{|}~x7f

```

Try it online!

*Unprintable characters where escaped using three printable characters (`x..`). The first snippet is three bytes long, every snippet after that grows in length by one.*

# Answer
> 0 votes
# Beatnik, 22 bytes, score 20

```
K A
E
I
L
N
O
R
S
T
U
a
e
i
l
n
o
r
s
t
u

```

Assuming the word "snippet" allows you to push the value on the stack.

# Answer
> 0 votes
# Octave, Score 86

```
nnz n

```

Followed by:

```
!$&()*+./0123456789:<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmopqrstuvwxy{|}~

```

This exploits the fact that Octave treats everything after a function name as a string input. So `nnz n` returns the number of non-zero elements in the string `'n'`. We get to 86 by adding the other printable ASCII-characters. `',"%#` doesn't work.

# Answer
> 0 votes
## Julia 0.6, 111217

The following script creates the full program:

```
A = "macro length(a);length(string(a))end;@length a"
B0 = join(([Char(x) for x in Iterators.flatten((0x000001:0x00d7ff, 0x00e000:0x10ffff)) if Base.isvalid(Char(x)) && Char(x) ∉ A && Base.isidentifier("a$(Char(x))") ]));
B = normalize_string(B0, stripmark=true, decompose=true);
B = join(unique(b for b in B))
while (n = search(B, '·')) > 0
    B = B[1:prevind(B,n)]*B[nextind(B,n):end]
end
while (n = search(B, '`')) > 0
    B = B[1:prevind(B,n)]*B[nextind(B,n):end]
end

open("concount.jl", "w") do f
    write(f, A)
    write(f, B)
end

```

### Explanation

The macro

```
 macro length(a);length(string(a))
 end
 @length a

```

followed by all distinct unicode characters allowed in identifiers, computed with `isidentifier`. Some diacritial marks mess up counting so I removed them.

# Answer
> 0 votes
# APL (Dyalog), score 12

*+1 score thanks to @dzaima*

First to third snippets:

```
(~⍴⍬)
+≢'a'
,⍕1

```

Then each of `234567890`.

Try it online!

# Answer
> 0 votes
# Pip, 57 bytes, score = 16

```
!u
2
RT9
#m
5
(EX3Y8)
7
y
A'<tab>
t
11
+o
-v
PI@`\...`@`..$`
"F"FB:4*4
Ok=k6

```

Note that `<tab>` represents a literal tab character (ASCII 9). Try it online!

Each snippet is a full program that outputs the desired number. Most of them work on the principle that the last expression in a Pip program is autoprinted: for example, in snippet 5, the previous code is evaluated, but the only part that matters is the `5`. Exceptions to this are:

* Snippet 3 works fine in isolation as `RT9` (square root of 9), but coming after snippet 2 it actually parses as `2RT9` (2nd root of 9)--which, of course, amounts to the same thing.
* Snippet 6 gets the 8th character (0-indexed) of e^3, which happens to be 6. But it also yanks the number 8 into the `y` variable. Snippet 8 then outputs the value of `y`.
* Snippet 12 takes the 11 from the previous snippet and adds `o` (preinitialized to 1). Snippet 13 takes that result and subtracts `v` (preinitialized to -1).
* Snippet 16 outputs `1` without a newline (`Ok=k`, where `k=k` evaluates to the default truthy value of 1), and then autoprints `6`.

Other interesting stuff:

* Snippet 14 uses regex operations to extract `14` from the value of pi.
* Snippet 15 converts the string `"F"` from hexadecimal.

# Answer
> 0 votes
# Zsh, score \>50 000 (1 112 046?), 16 + Σ(UTF-8 codepoint lengths) bytes

```
exec echo   $((${#:-$(<$0)}-33))
#

```

Zsh handles multibyte encodings by default. The base snippet has 18 unique characters, 34 total. Every other codepoint (save for the null byte) can be added onto this. As I write this, my script testing these is on codepoint ~50 000, total file size 150K, going at about 30 snippets/second. Run my full test script yourself here. You may want to adjust it to start at some later codepoints.

Try the first 2000 snippets online!

**More snippets are possible by using this technique.**

---
Tags: number, code-challenge, source-layout
---


# Question
Title: Shortest Program To Find Lowest Common Ancestor of Two Nodes in a Binary Tree
Any two separate nodes in a binary tree have a common ancestor, which is the root of a binary tree. The lowest common ancestor(LCA) is thus defined as the node that is **furthest from the root** and that is the ancestor of the two nodes.

The following are binary trees and the lowest common ancestors of the some of their nodes.

The LCA of 13 and 15 is 14.

The LCA of 47 and 49 is 48.

The LCA of 4 and 45 is 40.

The LCA of 13 and 14 is 14.

The LCA of 15 and 47 is 40.

**Challenge**

Write the shortest program possible that accepts as input the root of a binary tree and references to any two nodes in the binary tree. The program returns a reference to the LCA node of the two inputted nodes.

**Assumption**

Assume there is a least common ancestor present for any two nodes in the binary tree.

**Input**

The **root of a binary tree** and **references to any two nodes in the binary tree that the lowest common ancestor must be found for**. The root of the binary tree may be in the form of a reference to the root object or even a list that is a valid representation of a binary tree.

**Output**

**If using a pointer-based representation** of a tree returns **a reference** to the node that is the LCA of the two inputted nodes.

**If using a list representation** returns **the node\_id** for the lowest common ancestor of the two inputted nodes.

**Definition of a Binary Tree**

A tree is an object that contains a value and either three other trees or pointers to them.

The structure of the binary tree looks something like the following:

```
typedef struct T
{
   struct T *l;
   struct T *r;
   struct T *p; //this is the parent field
   int v;
}T;

```

If using a list representation for a binary tree and since certain node values in the binary tree may reappear, the list representation must have an additional node\_id parameter that looks something like this:

```
[[node_id,node_value],left_tree, right_tree, parent_tree]

```

# Answer
> 4 votes
# with ape package, 12 bytes

```
ape::getMRCA

```

Built-in. Called as `ape::getMRCA(tree, c(node1, node2))`.

# Answer
> 2 votes
# Python 2, ~~155~~ 151 bytes

```
def f(a,b,T):g=lambda U:U and(U[0]in[a,b]or T[0]in[a,b]or g(U[1])or g(U[2]));L,R=map(g,T[1:]);return(L and R)and T[0]or L and f(a,b,T[1])or f(a,b,T[2])

```

Try it online!

This assumes that nodes are defined as

```
[node_id, left_node, right_node]

```

as it seems silly to define the nodes as

```
[node_id, not_neccessarily_unique_node_value, left_node, right_node, parent_node]

```

because both the `other_not_neccessarily_unique_node_value` and `parent_node` are completely ignored in this problem.

The `g` function evaluates whether `U` is a ancestor of the nodes identified by either `a` or `b`.

Starting with the root node, if `g` is true of both the left child and the right child OR this node is either the `a` node\_id or the `b` node\_id, then this node is the LCA. Otherwise, exactly one of the two children - the left child or the right child - is then either the LCA or has the LCA as a child.

# Answer
> 1 votes
# Ruby, 86 bytes

```
f=->t,x,y=p{t==x ?(!y||f[x,y])&&t:t&&(f[t.l,x,y]||f[t.r,x,y]||y&&(f[t,x]&&f[t,y])&&t)}

```

Try it online!

If I understand correctly, sorting by value isn't guaranteed and we're returning node references so the value isn't actually used for anything. We're just checking a node's `l` and `r` values to see if they contain `x` and `y`. The function returns a falsey value if either of the provided nodes isn't in the tree so that it can be called recursively.

# Answer
> 1 votes
# Jelly, ~~15~~ 13 bytes

```
œiⱮn/œpḢƊḢœị⁸

```

Try it online!

A dyadic link taking the tree as left argument and the two node ids as right argument. Returns the full node of the lowest common ancestor.

Node ids are floating point. On TIO I’ve used vaguely hierarchical ids, but the actual numbers are arbitrary.

# Answer
> 0 votes
## Haskell, ~~72~~ 70 bytes

```
a#b|let g t@(i:%c)=(g=<<c)++[i|t!a,t!b];(i:%c)!e=i==e||any(!e)c=head.g

```

The tree data structure is `data T = (Int,Int) :% [T]`, i.e. a pair `(<id>,<value>)` and a list of child trees per node. Needs no link to parent within the node. Returns the `(<id>,<value>)` pair of the LCA.

Try it online!

# Answer
> 0 votes
# Wolfram Language (Mathematica), 53 bytes

```
Head@#&@@Cases[{#},a_/;!a~FreeQ~#2&&!a~FreeQ~#3,∞]&

```

Try it online!

`FirstCase` seems to be traversing the tree in a different order than `Cases`...

Function which takes the tree and two node values, and returns the value of the lowest common ancestor.

Represents the tree as an expression, where the head contains the value, and uses `Null` (or anything else that is guaranteed to not be a node) to represent the absense of a leaf.

For the example tree given, the structure looks like this:

# Answer
> 0 votes
# Charcoal, 38 bytes

```
Ｗ∧η⊞Ｏυη≔§⊟Φθ⁼§κ⁰η⁴ηＷ¬№υζ≔§⊟Φθ⁼§κ⁰ζ⁴ζＩζ

```

Try it online! Link is to verbose version of code. Takes input as a list of `[id, value, leftid, rightid, parentid]`, where a `0` value means no id. Explanation:

```
Ｗ∧η⊞Ｏυη≔§⊟Φθ⁼§κ⁰η⁴η

```

Walk the tree up from the first input node id, saving the found ids in the predefined empty list.

```
Ｗ¬№υζ≔§⊟Φθ⁼§κ⁰ζ⁴ζ

```

Walk the tree up from the second input node id until one of the ids matches.

```
Ｉζ

```

Print the matching id. (If strings were acceptable as ids, the  would not be necessary, but if both strings and numbers had to be supported, then that would cost an extra byte.)

# Answer
> 0 votes
# 05AB1E, 10 bytes

```
ΔDʒ˜ÃQ}`}н

```

Try it online!

First input is a tree in the format described in this answer, because I have no idea how the format in the question is supposed to work. Second input is a pair of node ids.

Explanation:

```
Δ       }     # repeat until top of stack doesn't change
 Dʒ   }       #  filter a copy of tree by
   ˜          #   flatten
    Ã         #   list intersection with the second input
     Q        #   equals the second input
       `      #  dump all results on the stack
         н    # get the first element (the node id)

```

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


title: Attacking the Hydra

text:
# Question
Title: Attacking the Hydra
Instead of being a skillful warrior capable of slaying Hydras (see here and here), this time you are a warrior that has no prior knowledge on how to kill one or which weapons to use against the creature.

In this problem, whenever you cut a single head off, two will grow in the same place. Since you don't have the mechanism to cut many heads off simultaneously, the number of heads will only grow. In this case, our Hydra can start with `N` (N ⩾ 1) heads. Let's call the first encounter a generation and we will represent the heads from the first generation as **0**, the heads created after the first blow as **1**, and so on.

**Input**

You will be given an integer `N` representing how many heads the Hydra initially have and a list of size `N` containing in which index (in the examples I will use 0-indexed format) you will cut a head off. You can always assume the indexes given are valid - remember that the list (i.e.: the heads) will grow as you cut heads off.

**Example**

**Input**: `N = 4` and `[0,4,2,5]`

**Generation 0 - Attack index 0**

```
0 0 0 0     =>     1 1 0 0 0
^                  ^ ^

```

**Generation 1 - Attack index 4**

```
1 1 0 0 0     =>     1 1 0 0 2 2
        ^                    ^ ^

```

**Generation 2 - Attack index 2**

```
1 1 0 0 2 2     =>     1 1 3 3 0 2 2
    ^                      ^ ^

```

**Generation 3 - Attack index 5**

```
1 1 3 3 0 2 2     =>     1 1 3 3 0 4 4 2
          ^                        ^ ^

```

**Last generation**

```
1 1 3 3 0 4 4 2

```

As you can see, the indexes given are related to the list of the previous generation.

**Output**

You are required to output the last generation.

**Test cases**

```
N = 1 and [0] => [1,1]
N = 2 and [0,0] => [2,2,1,0]
N = 2 and [0,1] => [1,2,2,0]
N = 2 and [1,0] => [2,2,1,1]
N = 2 and [1,1] => [0,2,2,1]
N = 4 and [0,4,2,5] => [1,1,3,3,0,4,4,2]
N = 6 and [0,0,0,0,0,0] => [6, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0]
N = 6 and [5,6,7,8,9,10] => [0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 6]
N = 10 and [1,7,3,12,9,0,15,2,2,10] => [6, 6, 9, 9, 8, 1, 3, 3, 0, 0, 10, 10, 2, 5, 5, 0, 0, 4, 7, 7]

```

This is so shortest answer in bytes wins!

# Answer
> 11 votes
# Python 2, 59 bytes

```
H,a=input()
H*=[0]
for i in a:H[i:i+1]=[max(H)+1]*2
print H

```

Try it online!

Very clever -1 thanks to xnor.

# Answer
> 9 votes
# Python 2, 60 bytes

```
n,a=input()
h=[0]*n
for c in a:h[c:c+1]=[max(h)+1]*2
print h

```

Try it online!

# Answer
> 5 votes
# Stax, ~~12~~ 11 bytes

```
î╓≡╧▄#¥oWä)A

```

Run and debug it at staxlang.xyz!

Thanks to recursive for one byte of savings!

### Unpacked (13 bytes) and explanation:

```
z),{i^c\&:fFm
z)               Push initial array of zeroes to stack
  ,              Push array of attacks to stack
   {       F     For each attack, push it and then:
    i^c\           Push [x,x], where x is the generation number
        &          Set the head at the attack index to this new array
         :f        Flatten
            m    Print the last generation

```

The challenge explicitly says "you are required to output the last generation," so my guess is this consensus doesn't hold here. If it does, though, **ten bytes** can be managed by leaving the result on an otherwise-empty stack:

```
z),Fi^c\&:f

```

# Answer
> 5 votes
# Haskell, ~~63~~ 57 bytes

```
foldl(\y(x,n)->take n y++x:x:drop(n+1)y).(0<$)<*>zip[1..]

```

Try it online!

# Answer
> 4 votes
# Oracle SQL, 325 bytes

```
select listagg(ascii(substr(l,level,1)),', ')within group(order by level)
from(select * from t
model dimension by(1 i)measures(l,r)
rules iterate(1e5)until(r[1]is null)
(l[1]=regexp_replace(l[1],'.',chr(:n-length(r[1])+1)||chr(:n-length(r[1])+1),1,ascii(substr(r[1],1,1))+1),r[1]=substr(r[1],2)))
connect by level<=length(l);

```

Test in SQL\*Plus.

```
SQL> set heading off
SQL>
SQL> create table t(l varchar2(4000), r varchar2(4000));

Table created.

SQL>
SQL> var n number;
SQL> exec :n := 10;

PL/SQL procedure successfully completed.

SQL>
SQL> insert into t
  2  values(rpad(chr(0),:n,chr(0)), chr(1)||chr(7)||chr(3)||chr(12)||chr(9)||chr(0)||chr(15)||chr(2)||chr(2)||chr(10));

1 row created.

SQL>
SQL> select listagg(ascii(substr(l,level,1)),', ')within group(order by level)
  2  from(select * from t
  3  model dimension by(1 i)measures(l,r)
  4  rules iterate(1e5)until(r[1]is null)
  5  (l[1]=regexp_replace(l[1],'.',chr(:n-length(r[1])+1)||chr(:n-length(r[1])+1),1,ascii(substr(r[1],1,1))+1),r[1]=substr(r[1],2)))
  6  connect by level<=length(l);

6, 6, 9, 9, 8, 1, 3, 3, 0, 0, 10, 10, 2, 5, 5, 0, 0, 4, 7, 7

```

PS. Works for numbers up to 255.

# Oracle SQL, 214 bytes, generic case

```
select l from t model dimension by(1i)measures(rpad('0',(n-1)*2+1,',0')l,r,n,1k)rules iterate(1e9)until(k[1]=n[1]+1)
(l[1]=regexp_replace(l[1],'\d+',k[1]||','||k[1],1,regexp_substr(r[1],'\d+',1,k[1])+1),k[1]=k[1]+1)

```

Test in SQL\*Plus.

```
SQL> create table t(n,r) as
  2  select regexp_count(r,',')+1 n, r from
  3  (select cast('1,7,3,12,9,0,15,2,2,10' as varchar2(4000)) r from dual)
  4  /

Table created.

SQL> select l from t model dimension by(1i)measures(rpad('0',(n-1)*2+1,',0')l,r,n,1k)rules iterate(1e9)until(k[1]=n[1]+1)
  2  (l[1]=regexp_replace(l[1],'\d+',k[1]||','||k[1],1,regexp_substr(r[1],'\d+',1,k[1])+1),k[1]=k[1]+1)
  3  /

L
--------------------------------------------------------------------------------
6,6,9,9,8,1,3,3,0,0,10,10,2,5,5,0,0,4,7,7

```

# Answer
> 3 votes
# JavaScript (ES6),  ~~61 59~~  51 bytes

*Thanks to @Shaggy for pointing out that `n` is always the length of the array, saving 8 bytes in both versions*

Expects the array in 0-indexed format. Ignores `n`.

```
a=>a.map(i=>b.splice(i,1,++g,g),b=a.map(_=>g=0))&&b

```

Try it online!

---

# JavaScript (Node.js),  ~~64~~  56 bytes

Using `reduce()` and `flat()`:

```
a=>a.reduce((b,i,g)=>b.flat(1,b[i]=[++g,g]),a.map(_=>0))

```

Try it online!

# Answer
> 3 votes
# Zsh, 41 bytes

We ignore N, as stated by the rules.

```
for i;a+=(0)
for i;a[i]=($[++j] $j)
<<<$a

```

Try it online!

Pretty standard: Make an array of 0s to start, print it to finish. The `a[i]=(a b)` method of both changing and inserting is new to me, happy I found a use for it.

---

**OR, also 41 bytes**:

```
a[#]=
for i;a[i]=($[++j] $j)
<<<${a/#%/0}

```

This one is less standard. We take advantage of a few neat tricks:

* `${a/#%/0}`: This is replacement, but `#` and `%` tell zsh to anchor the match at the start and end. Since it's empty, we replace all empty elements with 0.
* `a[#]=`: This effectively declares an empty array of size `$#` in Zsh. It's like `char *a[argc]` in C. If we don't do this, we won't get the trailing zeroes we need.

Try it online!

# Answer
> 3 votes
# Scala, 104 bytes

```
def^(l:Seq[Int],r:Seq[Int]):Seq[Int]=if(r.size>0)^(l.patch(r(0),Seq.fill(2)(l.max+1),1),r.drop(1))else l

```

Try it online!

Seems to be the longest answer so far. :)

`List.fill(2)(l.max+1)` can be replaced with `List(l.max+1,l.max+1)` but length remains the same.

# Answer
> 2 votes
# Japt, 14 bytes

```
rÈhY[°TT] c}Uî

```

Try it

# Answer
> 2 votes
# PHP, 101 bytes

```
function h($n,$a){$h=array_fill(0,$n,0);foreach($a as$b)array_splice($h,$b,0,$h[$b]=++$x);return $h;}

```

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), ~~94~~ ~~89~~ 85 bytes

```
a=>b=>b.Aggregate(new int[a-(a-=a)].ToList(),(c,d)=>{c.Insert(d,c[d]=++a);return c;})

```

Saved 2 bytes thanks to Andrew Bauhmer

Try it online!

# Answer
> 1 votes
# Perl 5 `-pal`, 48 bytes

```
@h=($i=0)x@F;splice@h,$_,1,(++$i)x2for@F;$_="@h"

```

Try it online!

Takes array as space-separated list from STDIN. Doesn't input `n`.

# Answer
> 1 votes
# Retina 0.8.2, 69 bytes

```
\d+
$*_
r`_\G
,0
+`^((,*)_)(_)*(.*,,(?<-3>\d+,)*)\d+
$2$4$.1,$.1
^,+

```

Try it online! Link includes test cases. 1-indexed. Takes input as `...list,N`. Does not require the list to be of length `N`. Explanation:

```
\d+
$*_

```

Convert all of the inputs to unary, but using `_`, so that it doesn't get confused with later uses of the digit `1`. (Retina 1 would do this automatically for a 2-byte saving.)

```
r`_\G
,0

```

Replace `N` with an array of `N` zeros, but don't alter the list.

```
+`

```

Process all elements of the list.

```
^((,*)_)(_)*(.*,,(?<-3>\d+,)*)\d+

```

Find the next element of the list and the equivalent position in the array. `$1` = current generation (as a length), `$2` = commas from previous generations, `$3` = current index - 1, `$4` = first `$3` heads.

```
$2$4$.1,$.1

```

Replace the head at the current index with two copies of the current generation in decimal.

# Answer
> 1 votes
# Pyth, 16 bytes

```
u.nXGH,=+Z1ZE*]0

```

Try it online!

Interestingly, it turns out I can't use `s` to flatten the list as it is actually shorthand for `+F`, which performs `+` on the leftmost two elements of the list until all elements have been processed. This means that the first few elements might simply be summed, depending on where the last replacement occurred.

```
u.nXGH,=+Z1ZE*]0Q   Implicit: Q=input 1 (N), E=input 2 (array), Z=0
                    Trailing Q inferred
              ]0    [0]
             *  Q   Repeat Q times
u           E       Reduce E, with current value G and next value H, starting with the above:
       =+Z1           Increment Z in-place
      ,  Z Z          Pair the updated Z with itself
   XGH                In G, replace the element with index H with the above
 .n                   Flatten
                    Implicit print

```

# Answer
> 1 votes
# Jelly, 13 bytes

```
;`ɼṁœP@j‘ɼɗƒ@

```

Try it online!

Monadic link that takes the 1-indexed list of heads to cut as its argument and returns the final generation.

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
-IvN>D‚yǝ˜

```

Try it online!

```
   -             # subtract the input from itself (yields a list of 0s)
    Iv           # for each number y in the input
      N          # push the 0-based loop count
       >         # add 1 to get the generation number
        D        # duplicate
         ‚       # wrap the two copies in a list
          yǝ     # replace the element at index y with that list
            ˜    # flatten

```

---
Tags: code-golf
---


title: Lazy brainfuck programmer

text:
# Question
Title: Lazy brainfuck programmer
## Background

Joe is working on his new Brainfuck answer on Codegolf. The algorithm he's using to solve the challenge is a bit complicated, so Joe came up with idea of simplifying his Brainfuck notation to make programming easier and faster.

## The challenge

Let's look at snippet written by Joe a moment ago:

```
0+++++1+++++0[3+0-]+1[3-2+1-]2[1+2-]3[0-3[-]]

```

This program was meant to check for equality of #0 and #1 cells in memory. Your task is to create a preprocessor for Joe, that will replace **single digits** from input with '\>' and '\<' characters, so the memory pointer will slide to cell specified.

## Input

You may take input from any source - function parameter, standard input, or any other device. The input might be in form of a stream, string, or a byte array.

The input may contain characters from all over the ASCII range, but can't contain brainfuck memory pointer instructions (`<` & `>`).

All the digits you see in the input are expected to be placed here just for your program.

## Output

As Joe didn't write his preprocessor yet, he had to make the code interpretable by hand. That's the result he got:

```
+++++>+++++<[>>>+<<<-]+>[>>-<+<-]>[<+>-]>[<<<->>>[-]]

```

There are pretty much no restrictions on output - if the input has braces unbalanced, just copy them over in unbalanced amount to the output.

## Bonus tasks

If you think the challenge is too boring in current form, you might want to complete these tasks aswell for slight byte count reduction, and more fun obviously:

* Optimize out nonsense related to memory operations, like digits at the end of input or clustered digits (just take the last one) **\- 20% of byte amount when completed**
* Minify Brainfuck output (remove clustered `+-`, `><`, non-brainfuck, comments and other kind of stuff) **\- 20% of byte amount when completed**

## Rules

* Standard loopholes are forbidden by default
* Default I/O rules apply
* Programs are scored by their size in bytes.
* Solving additional tasks reduces the score.
* If anything is unclear, please let me know down in the comments
* Scoring of bonus tasks may increase (but not decrease!) in the future.

## Opening bid - C, 144 bytes

```
p,c,x;void g(v){x=v?'<':'>';if(v<0)v*=-1;while(v--)putchar(x);}main(){while((c=getchar())!=-1)if(isdigit(c)){c-=48;g(c-p);p=c;}else putchar(c);}

```

This program should make pretty much everything clear on the input and output side of this challenge, it doesn't implement any bonus tasks though.

# Answer
# Jelly, 18 bytes

```
V©_¥®N,$Ø<xµ¹e?ØD)

```

A full program. Assumes (like everyone else has) that no actual Brainfuck evaluation has to be made (no balancing of unbalanced brackets)

**Try it online!**

### How?

```
V©_¥®N,$Ø<xµ¹e?ØD) - Main Link: list of characters, s
                 ) - for each character, c, in s:
               ØD  -   digits = "0123456789"
              ?    -   if...
             e     -   ...condition: (c) exists in? (digits)
           µ       -   ...then: monadic link:
    ®              -            recall from register (initially 0)
   ¥               -            last two links as a dyad i.e. f(c, ®):
V                  -              evaluate (c)
 ©                 -              (copy to the register)
  _                -              subtract (®)  i.e. x = value(c) - register
       $           -            last two links as a monad i.e. f(x):
     N             -              negate (x)
      ,            -              pair with (x)  -> [-x,x]
        Ø<         -            list of characters = "<>"
          x        -            repeat (vectorises) - negatives act like 0
            ¹      -   ...else: identity - i.e. f(c) -> c
                   - implicit (smashing) print

```
> 3 votes

# Answer
# JavaScript (ES6), 63 bytes

```
s=>s.replace(/\d/g,n=>'<>'[+(p<n)].repeat(p<n?n-p:p-n,p=n),p=0)

```

Try it online!
> 2 votes

# Answer
# Japt v2.0a0, ~~20~~ 16 bytes

```
r\d@Tî< +'>pT=Xn

```

Try it

Saved 4 bytes porting a comment by tsh on Arnauld's solution which I've been told results in valid BF output.

```
r\d@Tî< +'>pT=Xn     :Implicit input of string
r                    :Replace
 \d                  :Digits (RegEx /\d/g)
   @                 :Pass each match X through a function
    Tî<              :  T (initially 0) time repeat "<"
        +            :  Append
         '>p         :  Repeat ">"
            T=Xn     :    Convert X to an integer and assign it to T for the next match

```
> 2 votes

# Answer
# Perl 6, 48 bytes

```
{$!=0;S:g{\d}=['<','>'][$/>$!]x abs +$!-($!=$/)}

```

Try it online!

Substitutes all digits with the appropriate character repeated the difference between the previous amount of times
> 2 votes

# Answer
# Python 3.6, ~~93~~ ~~90~~ ~~83~~ ~~79~~ 77 bytes

```
p=0
for s in input():
 try:a=int(s)-p;s='>'*a+'<'*-a;p+=a
 except:0
 print(s)

```

Try it online

Thanks to @JonathanAllan for -2 bytes.

---

Old version 90 bytes:

```
p=0
for s in input():
 if '/'<s<':':a=int(s);print('>'*(a-p)+'<'*(p-a));p=a
 else:print(s)

```

Thanks to @EmbodimentofIgnorance for -3 bytes.
> 1 votes

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

```
εDdi®α„><®y©@è×]J¦

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~103~~ 99 bytes

```
x=>{int i=48;foreach(var g in x)Write(g<58&g>47?new string(g-i<0?'>':'<',Math.Abs(i-(i=g))):g+"");}

```

Try it online!
> 0 votes

# Answer
# Retina 0.8.2, 27 bytes

```
\d(\D*)
$*>$1$&$*<
+`<>|<$

```

Try it online! Explanation:

```
\d(\D*)

```

Match a digit and then all intervening non-digits.

```
$*>$1$&$*<

```

Slide the memory pointer to the desired cell, then after the intervening code, slide it back to the initial cell.

```
+`<>|<$

```

Cancel out any overlapping slides and delete any trailing slides.
> 0 votes

# Answer
# Pyth, 34 bytes

```
VzI}N."09IÒ"p*\<Zp*\>KsN=ZK.?pN)

```

With unprintable string `\x96\x02` between `."09I` and `Ò`

Explained:

```
Vz                                  # For N in input
  I}N."09IÒ"                        # If N is in the packed string 1234567890
               p*\<Z                # Print Z * "<"
                    p*\>KsN         # K = int(N) and print ">" * K
                           =ZK      # Z = K
                              .?pN) # Else print N

```
> 0 votes

---
Tags: code-challenge, brainfuck, code-generation
---


title: Hidden sentences in the license plates

text:
# Question
Title: Hidden sentences in the license plates
### Introduction:

*Inspired by both Perfect License Plates and How many points does my license plate give?*

Just like in the challenges above, me and my little brother had a game of our own with license plates as kids. We tried to create (random/funny) sentences with the (numbers and) letters of the license plates.

For example, I can still remember the license plate of our old car from over ten years ago, because of the silly sentence we had created with it:

```
71-NN-BT
71 Nare Nonnen Bijten Tijgers   [Dutch for: 71 Nasty Nuns Biting Tigers]

```

### Input:

* A license plate, which for the sake of this challenge will always start with two digits `[0-9]`, followed by four uppercase letters `[A-Z]`.
* Three fixed lists (see below): consisting of Dutch plural nouns; Dutch adjectives; and Dutch verbs.

### Output:

Using the list of Dutch plural nouns, adjectives and verbs below as input, create a random Dutch sentence with the given license plate using the following rules:

* Start with the numbers, followed by a space;
* And the four letters should either be used in the pattern `adjective noun verb noun` or `noun verb adjective noun` (50/50 random).
This would mean that the sentence mentioned earlier ("*Nare Nonnen Bijten Tijgers*" / "*Nasty Nuns Biting Tigers*") is in the pattern `adjective noun verb noun`, and this alternative sentence "*Nonnen Negeren Blote Theekopjes*" / "*Nuns Ignoring Naked Teacups*" is in the pattern `noun verb adjective noun`).

### Lists of words

Formatted pastebin thanks to *@Arnauld*.

**Nouns:**

```
Aanbeelden [Anvils]
Aardbeien [Strawberries]
Apen [Monkeys]
Appels [Apples]
Auto's [Cars]
Bananen [Bananas]
Bessen [Berries]
Bloemen [Flowers]
Bomen [Trees]
Bijen [Bees]
Cadeaus [Presents]
Cavia's [Guinea pigs]
Cheerleaders [Cheerleaders]
Circusdieren [Circus animals]
Citroenen [Limons]
Dinosaurussen [Dinosaurs]
Dieren [Animals]
Documenten [Documents]
Doctoren [Doctors]
Dolfijnen [Dolphins]
E-mails [Emails]
Edelstenen [Gemstones]
Eekhoorns [Squirles]
Enqûetes [Enquetes]
Ezels [Donkeys]
Fabrieken [Factories]
Fietsen [Bicycles]
Flessen [Bottles]
Fontijnen [Fountains]
Foto's [Photographs]
Giraffen [Girafs]
Glazen [Glasses]
Gummen [Erasers]
Guppy's [Guppies]
Gymschoenen [Gym shoes]
Haaien [Sharks]
Homo's [Gay men]
Honden [Dogs]
Hoofden [Heads]
Horloges [Watches]
Idioten [Idiots]
Idolen [Idols]
IJsklontjes [Ice cubes]
Illusies [Illusions]
Imperia [Empires]
Jassen [Jackets]
Jokers [Jokers]
Jongleurs [Jugglers]
Jurken [Dresses]
Juwelen [Jewels]
Kabels [Cables]
Katten [Cats]
Kauwgomballen [Gum-balls]
Knoppen [Buttons]
Konijnen [Rabbits]
Leesboeken [Reading books]
Leeuwen [Lions]
Legercommandanten [Commander-in-chieves]
Lesbies [Lesbians]
Lummels [Oafs]
Maagden [Virgins]
Mannen [Men]
Mensen [People]
Mieren [Ants]
Muren [Walls]
Neuzen [Noses]
Nieuwkomers [Novices]
Nonnen [Nuns]
Noten [Nuts]
Nummerborden [License plates]
Oceanen [Oceans]
Ogen [Eyes]
Olifanten [Elephants]
Oren [Ears]
Orkanen [Huricanes]
PC's [PCs]
Pizza's [Pizzas]
Politieagenten [Police officers]
Postbezorgers [Mail men]
Potloden [Pencils]
Quads [ATVs]
Quaggamosselen [Quagga mussels]
Querulanten [Querulants]
Quiëtisten [Quietists]
Quizzen [Quizzes]
Radio's [Radios]
Ramen [Windows]
Regiseuren [Film directors]
Rekenmachines [Calculators]
Relschoppers [Hooligans]
Schepen [Ships]
Slakken [Snails]
Slangen [Snakes]
Stegosaurussen [Stegosauruses]
Stoelen [Chairs]
T-rexen [T-rexes]
Tafels [Tables]
Theekopjes [Teacups]
Tijgers [Tigers]
Tovenaars [Wizards]
Uien [Unions]
Uilen [Owls]
Universa [Universes]
Universiteiten [Universities]
USB-sticks [USB-sticks]
Vliegtuigen [Planes]
Vrachtwagens [Trucks]
Vrienden [Friends]
Vrouwen [Women]
Vulkanen [Vulcanos]
Walvissen [Whales]
Wespen [Wasps]
Wormen [Worms]
Worstelaars [Wrestlers]
Wortels [Carrots]
X-assen [X-axes]
X-chromosomen [X-chromosomes]
Xenonlampen [Xenon lamps]
Xylofonen [Xylophones]
Xylofonisten [Xylophonists]
Y-assen [Y-axes]
Y-chromosomen [Y-chromosomes]
Yoghurtdranken [Yugurt drinks]
Yogaleraren [Yoga teachers]
Yogaleraressen [Female yoga teachers]
Zeeën [Seas]
Zeehonden [Seals]
Zeepbellen [Soap bubbles]
Zwanen [Swans]
ZZP'ers [Freelancers]

```

**Verbs:**
*X has some duplicated verbs, because there aren't enough verbs starting with an X in Dutch..*

```
Accepteren [Accepting]
Activeren [Activating]
Amputeren [Amputating]
Amuseren [Amuzing]
Assisteren [Assisting]
Bakken [Baking]
Bedreigen [Threatening]
Bellen [Calling]
Bevruchten [Fertilizing/Impregnating]
Bijten [Biting]
Castreren [Castrating]
Categoriseren [Categorizing]
Centrifugeren [Centrifuging]
Claimen [Claiming]
Coachen [Coaching]
Dagvaardigen [Prosecuting]
Daten [Dating]
Degraderen [Downgrading]
Dienen [Serving]
Dwarsbomen [Thwarting]
Electroniseren [Eletronizing]
Eren [Show respect for]
Erven [Inherit]
Eten [Eating]
Exploderen [Blow up]
Factureren [Invoicing]
Fokken [Breeding]
Föhnen [Blow-drying]
Fotographeren [Photographing]
Frituren [Frying]
Gooien [Throwing]
Graderen [Grading]
Grijpen [Grabbing]
Groeperen [Making groups of]
Groeten [Greeting]
Hacken [Hacking]
Hallucineren [Hallucinating]
Haten [Hating]
Helpen [Helping]
Huren [Renting]
Importeren [Importing]
Inspireren [Inspiring]
Ironiseren [Ridiculing]
Irriteren [Irritating/Annoying]
Isoleren [Isolating]
Jagen op [Hunting on]
Jatten [Stealing]
Jennen [Teasing]
Jongleren met [Juggling with]
Justeren [Adjusting]
Klonen [Cloning]
Koken [Cooking]
Kopen [Buying]
Kraken [Cracking]
Kussen [Kissing]
Labelen [Labeling]
Leasen [Leasing]
Lonken [Ogling]
Loven [Praising]
Lusten [Having a taste for]
Maken [Creating]
Martelen [Torturing]
Merken [Labeling]
Meten [Measuring]
Mollen [Breaking]
Negeren [Ignoring]
Neuken [Having sex with]
Neutraliseren [Neutralizing]
Normaliseren [Normalizing]
Notificeren [Notifying]
Observeren [Observing]
Oliën [Oiling]
Ontbloten [Denuding]
Ontsmetten [Disinfecting]
Ordenen [Sorting]
Penetreren [Penetrating]
Pesten [Bullying]
Plagen [Teasing]
Porren [Poking]
Produceren [Producing]
Quadrilleren met [Quadrille-dancing with]
Quadrupleren [Quadrupling]
Queruleren over [Grumbling about]
Quoteren [Giving a rating to]
Quotiseren [Distributing]
Raadplegen [Consulting]
Redden [Saving]
Reinigen [Cleaning]
Ruilen [Trading]
Roken [Smoking]
Schieten [Shooting]
Schoppen [Kicking]
Schudden [Shaking/Shuffling]
Slaan [Hitting]
Stoppen [Stopping]
Tackelen [Assaulting]
Telen [Cultivating]
Tellen [Counting]
Temperen [Tempering]
Torpederen [Torpedo-ing]
Unificeren [Uniformising]
Unlocken [Unlocking]
Upgraden [Updrading]
Urineren [Urinating]
Utiliseren [Making use of]
Verbinden [Binding]
Verjagen [Scaring away]
Verkopen [Selling]
Vermoorden [Killing]
Verwijderen [Deleting]
Wassen [Washing]
Wekken [Awakening]
Wijzigen [Modifying]
Wreken [Avenging]
Wurgen [Strangling]
Xeroxen [Photocopying]
Xoipen [Sending over the internet]
Xeroxen [Photocopying]
Xoipen [Sending over the internet]
X-en [X-ing]
Yammeren [Yammering]
Yellen [Cheerleading]
Yielding [Calculating percentages of]
YouTube-streamen [YouTube-streaming]
Youtuben [YouTubing]
Zegenen [Blessing]
Zieken [Nagging]
Zien [Seeing]
Zoeken [Searching]
Zoenen [Making out with]

```

**Adjectives:**

```
Abstracte [Abstract]
Achterlijke [Morron]
Afrikaanse [African]
Amerikaanse [American]
Angstaanjagende [Scary]
Baby [Baby]
Blauwe [Blue]
Blote [Naked]
Boze [Angry]
Broze [Fragile]
Charmante [Charming]
Chinese [Chinese]
Chocolade [Chocolade]
Coole [Cool]
Corrupte [Corrupt]
Dagdromende [Daydreaming]
Dansende [Dancing]
Dikke [Fat]
Dode [Dead]
Dunne [Skinny]
Echte [Real]
Effectieve [Effective]
Elektrische [Electronic]
Enorme [Enormous]
Europese [European]
Felle [Bright]
Fictieve [Fictive]
Fietsende [Cycling]
Fluisterende [Whispering]
Fluitende [Whistling]
Gele [Yellow]
Glow-in-the-dark [Glow-in-the-dark]
Grijze [Grey]
Groene [Green]
Grote [Big]
Harige [Hairy]
Harde [Hard]
Homosexuele [Gay]
Horde [Troop of]
Hyperactieve [Hyperactive]
Idiote [Idiotic]
IJzere [Iron]
IJzige [Frosty]
Instelbare [Adjustable]
Ivoren [Ivory]
Jaloerse [Jealous]
Jammerende [Whining]
Japanse [Japanese]
Jokkende [Fibbing]
Jonge [Young]
Kale [Bald]
Kapotte [Broken]
Kleine [Little]
Knappe [Handsome]
Koude [Cold]
Lelijke [Ugly]
Lege [Empty]
Levende [Living]
Lopende [Walking]
Luie [Lazy]
Maffe [Weird]
Massieve [Massive]
Middeleeuwse [Medieval]
Milde [Mellow]
Mythische [Mythical]
Naakte [Naked]
Nachtelijke [Nocturnal]
Nare [Nasty]
Nucleaire [Nuclear]
Normale [Normal]
Ongelovige [Infidel]
Oranje [Orange]
Oude [Old]
Overheerdende [Prevailing]
Oxiderende [Oxidizing]
Paarse [Purple]
Platte [Flat]
Pratende [Talking]
Piraten [Pirate]
Puzzelende [Puzzling]
Quiteense [Female resident of the city of Quito]
Quad-rijdende [ATV-driving]
Quasi [Quasi]
Queue-stotende [(Billiard) cue thumping]
Quiche-etende [Quiche-eating]
Rennende [Running]
Rode [Red]
Romantische [Romantic]
Ronde [Round]
Roze [Pink]
Saaie [Boring]
Schattige [Cute]
Scherpe [Sharp]
Springende [Jumping]
Stoffige [Dusty]
Tongzoenende [French kissing]
Transformerende [Transforming]
Transparente [Transparent]
Treiterende [Tormenting]
Triomferende [Victorious]
Ultieme [Supreme]
Unieke [Unique]
Uniseks [Unisex]
Uiteenlopende [Various]
Uitmuntende [Outstanding]
Vage [Vague]
Verdrietige [Sad]
Vierkante [Square]
Vliegende [Flying]
Vrolijke [Jolly]
Warme [Warm]
Waterige [Aquatic]
Wijze [Wise]
Witte [White]
Wraakzuchtige [Vindicitive]
Xenofobische [Xenophobic]
Xhosa-sprekende [Xhosa-speaking]
XTC-verslaafde [XTC-addicted]
XXX [XXX]
Xylofoonspelende [Xylophone-playing]
Yahoo-zoekende [Yahoe-searching]
Yammerende [Yammering]
Yellende [Cheerleading]
YouTube-streamende [YouTube-streaming]
Youtubende [YouTubing]
Zachte [Soft]
Zingende [Singing]
Zwarte [Black]
Zwemmende [Swimming]
Zwevende [Floating]

```

### Challenge rules:

* You aren't allowed to use the same random noun twice in one sentence.
* You have to take the license plate input either as string or array/list of characters. You can choose to input without delimiter however, so all these are valid input-formats: `NN-CC-CC`; `NN CC CC`; `NN CCCC`; `NNCCCC`; `N N C C C C`; etc.
* The list of words can be in any reasonable format. Can be three separate lists; maps with the first letters as keys; one or multiple separate text files to read from; all possible. (You are allowed to take the input with or without the English translations added, as long as you output the Dutch sentence.)
* Output can be printing to STDOUT or returning a string.
* The lists above and the resulting sentences will only be in Dutch (with optionally the English translations added behind every word / the entire sentence).
NOTE: The original idea was to have the lists being part of the code, and *@JonathanAllan* suggested to use just Dutch instead of English, since there are quite a few languages with build-in English libraries. Later in the Sandbox, this switched to having the lists as input, and since I was already halfway through finishing the lists, I kept them Dutch. I've still added the English translations of each word in the list, so you can easily translate what your random output means.
* Because all the nouns are plural, we can assume the numbers will be in the range `02-99`.
* The numbers `02-09` may be outputted with or without leading zero.
* You are allowed to take the input license plate as lowercase instead of uppercase.

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

### Some possible test cases (but feel free to use your own as well).

```
71-NN-BT
80-XW-IK
13-UU-EF
12-AA-AA
99-ZX-YW
73-TH-QQ
04-DJ-IO

```

What are some of your favorite random sentences?

# Answer
# Jelly,  ~~37~~  35 bytes

```
ṙ2X¤;⁸ṪW¤i’¥Ðḟ"⁹ṫ3¤ŒpŒQẠ$ÐfXK⁹ḣ2¤,K

```

A dyadic link taking a list of lists (of lists of characters): `[[verbs],[adjectives],[nouns]]` on the left and the numberplate (format = `NNCCCC`) on the right and returning a list of characters.

**Try it online!**

### How?

```
ṙ2X¤;⁸ṪW¤i’¥Ðḟ"⁹ṫ3¤ŒpŒQẠ$ÐfXK⁹ḣ2¤,K - Link: list of lists of lists, words; list, plate
   ¤                                - nilad followed by link(s) as a nilad:
 2                                  -   literal two
  X                                 -   random integer in [1,z] -------- gets 1 or 2
ṙ                                   - rotate left by - words [v,a,n] -> [a,n,v] or [n,v,a]
        ¤                           - nilad followed by link(s) as a nilad:
     ⁸                              -   chain's left argument, words
      Ṫ                             -   tail - get the nouns
       W                            -   wrap in a list
    ;                               - concatenate - add another noun list to the end
                                    - (call this allWordLists) - either [a,n,v,n] or [n,v,a,n])
                  ¤                 - nilad followed by link(s) as a nilad:
               ⁹                    -   chain's right argument, plate
                 3                  -   literal three
                ṫ                   -   tail from index - get the four letters
                                    - (call this letters)
              "                     - zip with the dyadic operation:
            Ðḟ                      -   filter discard if:
           ¥                        -     last two links as a dyad:
         i                          -       first index of (a letter in a word in a wordList in allWordLists)
          ’                         -       decrement (if not found i yields 0, so this result is only 0 when the first index is the head of the list)
                                    - ...this gives us a list of lists of words beginning with the appropriate letters ordered either as [a,v,n,n] or [n,v,a,n]
                   Œp               - Cartesian product of the filtered lists
                         Ðf         - filter keep if:
                        $           -   last two links as a monad:
                     ŒQ             -     distinct sieve (1s at 1st occurrences, 0s elsewhere)
                       Ạ            -     all truthy - i.e. all distinct?
                           X        - random choice from the resulting list - get one four word choice
                            K       - join with spaces
                                ¤   - nilad followed by link(s) as a nilad:
                             ⁹      -   chain's right argument, plate
                               2    -   literal two
                              ḣ     -   head to index - get the two digits
                                 ,  - pair
                                  K - join with a space

```
> 3 votes

# Answer
## Perl 5, 89 bytes

**88 bytes code + 1 for `-p`.**

Requires the numberplate to be in the format `## A A A A` and the lists need to be formatted like `("A","B",...)`. If this is pushing the limits of acceptable, please let me know.

```
@$_=eval<>for n,v,a;s!\pL!(grep/^$&/,@{(rand>.5?(a,n,v,n):(n,v,a,n))[$-++]})[rand 5]!egi

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), ~~124~~ ~~120~~ 118 bytes

Takes input in currying syntax `(s)(a)` where ***s*** is a string in `"NNCCCC"` format and ***a*** is the array of arrays of words `[nouns, verbs, adj]`.

```
s=>a=>s.replace(/\D/g,c=>' '+(g=a=>a.sort(R)[0][0]==c?a.shift(i/=4):g(a))(a[i&3]),i=(R=_=>Math.random()-.5)()<0?18:36)

```

### Test cases

```
let f =

s=>a=>s.replace(/\D/g,c=>' '+(g=a=>a.sort(R)[0][0]==c?a.shift(i/=4):g(a))(a[i&3]),i=(R=_=>Math.random()-.5)()<0?18:36)

const NOUNS = ["Aanbeelden","Aardbeien","Apen","Appels","Auto's","Bananen","Bessen","Bloemen","Bomen","Bijen","Cadeaus","Cavia's","Cheerleaders","Circusdieren","Citroenen","Dinosaurussen","Dieren","Documenten","Doctoren","Dolfijnen","E-mails","Edelstenen","Eekhoorns","Enqûetes","Ezels","Fabrieken","Fietsen","Flessen","Fontijnen","Foto's","G-spots","Giraffen","Glazen","Gymschoenen","Gummen","Haaien","Homo's","Honden","Hoofden","Horloges","Idioten","Idolen","IJsklontjes","Illusies","Imperia","Jassen","Jokers","Jongleurs","Jurken","Juwelen","Kabels","Katten","Kauwgomballen","Knoppen","Konijnen","Leesboeken","Leeuwen","Legercommandanten","Lesbies","Lummels","Maagden","Mannen","Mensen","Mieren","Muren","Neuzen","Nieuwkomers","Nonnen","Noten","Nummerborden","Oceanen","Ogen","Olifanten","Oren","Orkanen","PC's","Pizza's","Politieagenten","Postbezorgers","Potloden","Quads","Quaggamosselen","Querulanten","Quiëtisten","Quizzen","Radio's","Ramen","Regiseuren","Rekenmachines","Relschoppers","Schepen","Slakken","Slangen","Stegosaurussen","Stoelen","T-rexen","Tafels","Theekopjes","Tijgers","Tovenaars","Uien","Uilen","Universa","Universiteiten","USB-sticks","Vliegtuigen","Vrachtwagens","Vrienden","Vrouwen","Vulkanen","Walvissen","Wespen","Wormen","Worstelaars","Wortels","X-assen","X-chromosomen","Xenonlampen","Xylofonen","Xylofonisten","Y-assen","Y-chromosomen","Yoghurtdranken","Yogaleraren","Yogaleraressen","Zeeën","Zeehonden","Zeepbellen","Zwanen","ZZP'ers"];
const VERBS = ["Accepteren","Activeren","Amputeren","Amuseren","Assisteren","Bakken","Bedreigen","Bellen","Bevruchten","Bijten","Castreren","Categoriseren","Centrifugeren","Claimen","Coachen","Dagvaardigen","Daten","Degraderen","Dienen","Dwarsbomen","Electroniseren","Eren","Erven","Eten","Exploderen","Factureren","Fokken","Föhnen","Fotographeren","Frituren","Gooien","Graderen","Grijpen","Groeperen","Groeten","Hacken","Hallucineren","Haten","Helpen","Huren","Importeren","Inspireren","Intelligente","Irriteren","Isoleren","Jagen op","Jatten","Jennen","Jongleren met","Justeren","Klonen","Koken","Kopen","Kraken","Kussen","Labelen","Leasen","Lonken","Loven","Lusten","Maken","Martelen","Merken","Meten","Mollen","Negeren","Neuken","Neutraliseren","Normaliseren","Notificeren","Observeren","Oliën","Ontbloten","Ontsmetten","Ordenen","Penetreren","Pesten","Plagen","Porren","Produceren","Quadrilleren met","Quadrupleren","Queruleren over","Quoteren","Quotiseren","Raadplegen","Redden","Reinigen","Ruilen","Roken","Schieten","Schoppen","Schudden","Slaan","Stoppen","Tackelen","Telen","Tellen","Temperen","Torpederen","Unificeren","Unlocken","Upgraden","Urineren","Utiliseren","Verbinden","Verjagen","Verkopen","Vermoorden","Verwijderen","Wassen","Wekken","Wijzigen","Wreken","Wurgen","Xeroxen","Xoipen","Xeroxen","Xoipen","X-en","Yammeren","Yellen","Yielding","YouTube-streamen","Youtuben","Zegenen","Zieken","Zien","Zoeken","Zoenen"];
const ADJECTIVES = ["Abstracte","Achterlijke","Afrikaanse","Amerikaanse","Angstaanjagende","Baby","Blauwe","Blote","Boze","Broze","Charmante","Chinese","Chocolade","Coole","Corrupte","Dagdromende","Dansende","Dikke","Dode","Dunne","Echte","Effectieve","Elektrische","Enorme","Europese","Felle","Fictieve","Fietsende","Fluisterende","Fluitende","Gele","Glow-in-the-dark","Grijze","Groene","Grote","Harige","Harde","Homosexuele","Horde","Hyperactieve","Idiote","IJzere","IJzige","Instelbare","Ivoren","Jaloerse","Jammerende","Japanse","Jokkende","Jonge","Kale","Kapotte","Kleine","Knappe","Koude","Lelijke","Lege","Levende","Lopende","Luie","Maffe","Massieve","Middeleeuwse","Milde","Mythische","Naakte","Nachtelijke","Nare","Nucleaire","Normale","Ongelovige","Oranje","Oude","Overheerdende","Oxiderende","Paarse","Platte","Pratende","Piraten","Puzzelende","Quiteense","Quad-rijdende","Quasi","Queue-stotende","Quiche-etende","Rennende","Rode","Romantische","Ronde","Roze","Saaie","Schattige","Scherpe","Springende","Stoffige","Tongzoenende","Transformerende","Transparente","Treiterende","Triomferende","Ultieme","Unieke","Uniseks","Uiteenlopende","Uitmuntende","Vage","Verdrietige","Vierkante","Vliegende","Vrolijke","Warme","Waterige","Wijze","Witte","Wraakzuchtige","Xenofobische","Xhosa-sprekende","XTC-verslaafde","XXX","Xylofoonspelende","Yahoo-zoekende","Yammerende","Yellende","YouTube-streamende","Youtubende","Zachte","Zingende","Zwarte","Zwemmende","Zwevende"];

console.log(f("71NNBT")([NOUNS, VERBS, ADJECTIVES]))
console.log(f("80XWIK")([NOUNS, VERBS, ADJECTIVES]))
console.log(f("13UUEF")([NOUNS, VERBS, ADJECTIVES]))
console.log(f("12AAAA")([NOUNS, VERBS, ADJECTIVES]))
console.log(f("99ZXYW")([NOUNS, VERBS, ADJECTIVES]))
console.log(f("73THQQ")([NOUNS, VERBS, ADJECTIVES]))
console.log(f("04DJIO")([NOUNS, VERBS, ADJECTIVES]))
```

### How?

The sequences of lists to pick the words from are stored as bitmasks, in reverse order:

```
Noun, Verb, Adjective, Noun --> 0, 1, 2, 0 --> 00 01 10 00 --[reverse]--> 00100100 --> 36
Adjective, Noun, Verb, Noun --> 2, 0, 1, 0 --> 10 00 01 00 --[reverse]--> 00010010 --> 18

```

That's why ***i*** is randomly initialized to either ***18*** or ***36***.

```
s => a =>                           // given 's' and 'a'
  s.replace(                        // replace in 's'
    /\D/g, c =>                     // each non-digit character 'c' with:
    ' ' + (                         // a space followed by
      g = a =>                      // a word picked from the list 'a'
        a.sort(R)                   //   shuffle the list
        [0][0] == c ?               //   if the 1st char. of the 1st word is matching 'c':
          a.shift(i /= 4)           //     return this word (removing it from the list)
                                    //     and discard the 2 least significant bits of 'i'
        :                           //   else:
          g(a)                      //     try again with a recursive call
    )(a[i & 3]),                    // initial call to g() with the next list
    i = (                           // initialize 'i', using:
      R = _ => Math.random() - 0.5  //   R(): returns a random float in [-0,5, 0.5)
    )() < 0 ? 18 : 36               // to either 18 or 36 (see above)
  )                                 // end of replace()

```
> 3 votes

# Answer
# Excel, ~~382~~ 353 bytes

```
=D1&E1&" "&IF(RAND()>0.5,INDIRECT("C"&INT((CODE(F1)-64.8+RAND())*5))&" "&INDIRECT("A"&INT((CODE(G1)-64.8+RAND())*5))&" "&INDIRECT("B"&INT((CODE(H1)-64.8+RAND())*5)),INDIRECT("A"&INT((CODE(F1)-64.8+RAND())*5))&" "&INDIRECT("B"&INT((CODE(G1)-64.8+RAND())*5))&" "&INDIRECT("C"&INT((CODE(H1)-64.8+RAND())*5)))&" "&INDIRECT("A"&INT((CODE(I1)-64.8+RAND())*5))

```

Three lists in `A`, `B` and `C` respectively. Numberplate characters in `D1` -to- `I1`. Formula in any other cell.

Golfing:

* Last word will always be `NOUN`,
* -14 bytes replacing `ADDRESS` with `"A"&INT()`
* -14 bytes arithmetic`(CODE(F1)-65)*5+RAND()*5+1` with `(CODE(F1)-64.8+RAND())*5`
> 3 votes

# Answer
# Java (OpenJDK 8), ~~535~~ ~~314~~ ~~304~~ ~~297~~ 382 bytes

```
import java.util.*;
L->N->V->A->{int c=((int)(Math.random()*8))%2,i=0,f;String[]a=new String[4],b[]={A,N,V,N,N,V,A,N};for(;i<4;i++){List<String>p=new ArrayList();for(f=0;f<b[i+c*4].length;f++)if(b[i+c*4][f].charAt(0)==L.charAt(i+2)&&(i<3|!b[i+c*4][f].equals(a[1-c])))p.add(b[i+c*4][f]);a[i]=p.get((int)(Math.random()*p.size()));}System.out.print(L.substring(0,2)+" "+L.join(" ",a));}

```

Try it online!
> 2 votes

# Answer
# Python 3, 82 bytes

```
def f(l,d):print(l[:2],*map(lambda i,j:d[i][j].pop(),{'anvn','nvan'}.pop(),l[2:]))

```

Try it online!

Function taking a string `l` for the license plate and a dictionary `d` containing dictionaries with nouns, verbs and adjectives. These must be labeled `'n'`, `'v'` and `'a'`, respectively.

In each of these dictionaries, the words are grouped and labeled by their first letter. Each key then contains a `set` of words. By using the `set.pop()` method to generate output, the chosen words are both random and non-duplicate.
> 1 votes

# Answer
# C#, 245 bytes

```
Random r=new Random();var a1=a[r.Next(0,a.Length)];var n1=n[r.Next(0,n.Length)];var n2=n[r.Next(0,n.Length)];var v1=v[r.Next(0,v.Length)];var m=r.Next(0,2)==0;Console.WriteLine($"{r.Next(0,10)}{r.Next(0,10)} {m?a1:n1} {m?n1:v1} {m?v1:a1} {n2}");

```

Surely not the shortest but it was fun to do so idc xD
Same code uncompacted (272 bytes):

```
Random r=new Random();
var a1 = a[r.Next(0, a.Length)];
var n1 = n[r.Next(0, n.Length)];
var n2 = n[r.Next(0, n.Length)];
var v1 = v[r.Next(0, v.Length)];
var m = r.Next(0, 2)==0;
Console.WriteLine($"{r.Next(0,10)}{r.Next(0,10)} {m?a1:n1} {m?n1:v1} {m?v1:a1} {n2}");

```
> 0 votes

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


title: Levenshtein Neighbours

text:
# Question
Title: Levenshtein Neighbours
Most square numbers have at least 1 different square number with which their Levenshtein distance is exactly 1. For a given square \\$x\\$, each square that meets this condition is called a *Levenshtein neighbour* of \\$x\\$. For example, \\$36\\$ is a Levenshtein neighbour of \\$16\\$, as only 1 edit (\\$1 \to 3\\$) is required. However, \\$64\\$ is not a Levenshtein neighbour of \\$16\\$, as it requires a minimum of 2 edits. Numbers that have leading 0s (\\$2025 \to 025\\$) are *not* Levenshtein neighbours.

Your task is to take a square number as input and to output, in any reasonable format, the complete list of it's Levenshtein neighbours. You may include repeat neighbours in the list, if you wish, but you may not include the original input, as it isn't a Levenshtein neighbour of itself.

Any reasonable format should include some sort of separator between the outputs, such as `,` or a newline, and can output characters with the corresponding Unicode value (i.e. brainfuck) rather than the numbers themselves. The order of the output doesn't matter.

This input will always be a square number, greater than \\$0\\$. Your program should have no *theoretical* limit, but if it fails for large numbers for practical reasons (e.g. beyond 32-bit numbers), that's completely fine.

If the input does not have any Levenshtein neighbours, the output must clearly reflect this, such as outputting nothing, an empty array/string, a negative integer, \\$0\\$, etc.

This is , so the shortest code in bytes wins.

## Test cases

These are the results for the squares of \\$1\\$ through to \\$20\\$:

```
  1: 4, 9, 16, 81
  4: 1, 9, 49, 64
  9: 1, 4, 49
 16: 1, 36, 169, 196
 25: 225, 256, 625
 36: 16, 361
 49: 4, 9
 64: 4
 81: 1, 841
100: 400, 900, 1600, 8100
121: 1521
144: 1444
169: 16, 1369
196: 16, 1296, 1936
225: 25, 625, 1225, 2025, 4225, 7225
256: 25
289: 2809
324: 3249
361: 36, 961
400: 100, 900, 4900, 6400

```

In addition, `1024` does not have any neighbours, so is a good test case.

# Answer
> 7 votes
# 05AB1E,  ~~11 10~~  6 bytes

-4 thanks to Grimy !! (square first rather than looking for squares saves 3; use 10^n saves 1)

```
°Lnʒ.L

```

Takes an integer, outputs a, possibly empty, list

**Try it online!** \- This is crazy-slow due to the `°`, so no point trying it even for `9`.
Or **Try a slightly faster version** \- This one adds eight instead with `8+` then uses the same approach.

### How?

```
°Lnʒ.L - f(integer)    stack = n
°      - push 10^n             10^n
 L     - range                 [1,2,3,...,10^n]
  n    - square                [1,4,9,...,10^2n]
   ʒ   - filter keep if == 1:
    .L -   Levenshtein distance

```

# Answer
> 5 votes
# Retina 0.8.2, ~~142~~ 138 bytes

```
.?
$'¶$`#$&$'¶$`#$'¶$`$&
#
0$%'¶$%`1$%'¶$%`2$%'¶$%`3$%'¶$%`4$%'¶$%`5$%'¶$%`6$%'¶$%`7$%'¶$%`8$%'¶$%`9
A`^0
Dr`
\d+
$*
-2G`(\b1|11\1)+\b
%`1

```

Try it online! Explanation:

```
.?
$'¶$`#$&$'¶$`#$'¶$`$&

```

For each digit, try a) removing it b) preceding it with a different digit c) changing it to a different digit. For now, the different digit is marked with a `#`.

```
#
0$%'¶$%`1$%'¶$%`2$%'¶$%`3$%'¶$%`4$%'¶$%`5$%'¶$%`6$%'¶$%`7$%'¶$%`8$%'¶$%`9

```

For each potential different digit, substitute each possible digit.

```
A`^0

```

Remove numbers that now begin with zero.

```
Dr`

```

Remove all duplicated numbers. (This just leaves the lines blank.)

```
\d+
$*

```

Convert to unary.

```
-2G`(\b1|11\1)+\b

```

Keep all square numbers except the last (which is always the input number).

```
%`1

```

Convert the remaining numbers back to decimal.

# Answer
> 5 votes
# , ~~42~~ 41 bytes

-1 byte with the bound \\$(9n)^2\\$.

```
function(n,y=(1:(9*n))^2)y[adist(n,y)==1]

```

Try it online!

All Levenshtein neighbours of \\$n\\$ are smaller than \\$91n\\$ (That bound is attained, for example, by \\$1\to 91\\$ or \\$100\to9100\\$). Here, I am using instead the bound \\$(9n)^2=81n^2\\$. For \\$n\>1\\$, \\$81n^2\>91n\\$ so we are fine. For \\$n=1\\$, this bound misses one Levenshtein neighbour: \\$1\to91\\$; since \\$91\\$ is not a square, we are fine.

Lists all square numbers between \\$1\\$ and \\$(9n)^2\\$, and keeps those with Levenshtein distance equal to 1.

# Answer
> 4 votes
# Python 2, ~~173~~ ~~167~~ ~~149~~ ~~148~~ ~~147~~ ~~144~~ ~~139~~ 138 bytes

```
lambda n,I=int:{(I(I(v)**.5)**2==I(v))*I(v)for v in[`n`[:i]+`j-1`[:j]+`n`[i+k:]or 0for j in range(11)for i in range(n)for k in 0,1]}-{0,n}

```

Try it online!

19+3+5+1=28! bytes thx to Jonathan Allan.

# Answer
> 3 votes
# Oracle SQL, 93 bytes

```
select level*level from t where utl_match.edit_distance(x,level*level)=1connect by level<10*x

```

Test in SQL\*PLus.

```
SQL> set heading off
SQL> with t(x) as (select 225 from dual)
  2  select level*level from t where utl_match.edit_distance(x,level*level)=1connect by level<10*x
  3  /

         25
        625
       1225
       2025
       4225
       7225

6 rows selected.

```

# Answer
> 2 votes
# Jelly, ~~53~~ 38 bytes

```
D;Ɱ⁵ṭJœP,œṖjþ⁵Ẏṭ@ḢF${ʋʋ€$ƲẎ%⁵1ị$ƇḌÆ²Ƈḟ

```

Try it online!

There’s no built-in for Levenshtein distance so generates all possible 1-distance edits and then excludes those with leading zero and keeps only perfect squares. Doesn’t filter duplicates (as permitted).

# Answer
> 2 votes
# JavaScript (V8),  ~~129 125~~  123 bytes

Takes input as a string. Prints the Levenshtein neighbours to STDOUT.

```
s=>{for(t=9+s;t;t--)(t+='')**.5%1||(g=m=>m*n?1+g(m,--n)*(g(--m)-(s[m]==t[n++]))*g(m):m+n)(s.length,n=t.length)-1||print(t)}

```

Try it online!

### Commented

```
s => {                        // s = input
  for(                        // loop:
    t = 9 + s;                //   start with t = '9' + s
    t;                        //   repeat while t > 0
    t--                       //   decrement t after each iteration
  )                           //
    (t += '')                 //   coerce t to a string
    ** .5 % 1 ||              //   abort if t is not a square
    ( g =                     //   g is a recursive function to test whether the
                              //   Levenshtein distance between s and t is exactly 1
      m =>                    //   m = pointer into s (explicit parameter)
                              //   n = pointer into t (defined in the global scope)
        m * n ?               //     if both m and n are greater than 0:
          1 +                 //       add 1 to the final result and add the product of:
          g(m, --n) * (       //         - a recursive call with m and n - 1
            g(--m) -          //         - a recursive call with m - 1 and n - 1
            (s[m] == t[n++])  //           minus 1 if s[m - 1] = t[n - 1]
          ) *                 //
          g(m)                //         - a recursive call with m - 1 and n
        :                     //       else:
          m + n               //         stop recursion and return m + n
    )(s.length, n = t.length) //   initial call to g with m = s.length, n = t.length
    - 1 ||                    //   abort if the final result is not 1
    print(t)                  //   otherwise, print t
}                             //

```

# Answer
> 2 votes
# PHP, 62 bytes

```
for(;$argn*92>$n=++$i**2;levenshtein($argn,$n)==1&&print$n._);

```

Try it online!

This script prints Levenshtein neighbors of input separated by `_` with a trailing separator, and if no neighbors are found, prints nothing.

Happily PHP has a built-in for Levenshtein distance! This script loops over all square numbers from 1 to `input * 91`, since all valid Levenshtein neighbors (distance of 1) are in that range. Then prints every number in that range which has a Levenshtein distance of 1 with the input.

# Answer
> 1 votes
# Wolfram Language (Mathematica), ~~62~~ 59 bytes

```
f@n_:=Select[Range[9n]^2,EditDistance@@ToString/@{n,#}==1&]

```

Try it online!

Using the bound from the R answer.

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