title: Embiggen your input

text:
# Question
Title: Embiggen your input
This is a bit similar to this dust covered entry but I'm hoping my spin on it makes it unique enough. Not been able to find anything dissuading me from posting this but there is quite the sea out there.

Anyway! The challenge:

Your code receives a string of characters; It converts this into an ASCII-art style version of the same string, but with a catch.

# Input transformation

* The only characters to be supported are A-Z and 0-9
* Lower case letters are transformed into uppercase
* Anything else is silently removed

# Character drawing

* Each "pixel" of the enlarged font is drawn from the input string
* The n'th pixel is equal to the n'th character in the input string. If n is greater than the length of the input string, wrap around back to the beginning
* Individual letters are drawn left-to-right, top-to-bottom
* Subsequent letters pick up their "pixel character" index from where the last letter left off (e.g. with an input length of 10, if the first letter had 9 pixels, the second letter's first pixel will be drawn with the 10th input character, the second pixel will be drawn with the 1st input character)
* Each letter is drawn in a 5x5 grid, fully padded with spaces. You can find the font you are to use pre-rendered for you in this pastebin or a bit further down in this post
* Every letter is drawn on the same line, so the total number of line breaks in your output will be 4
* Every letter is seperated by 2 columns of spaces

# The font

```
 000
0  00
0 0 0
00  0
 000

111
  1
  1
  1
11111

2222
    2
 222
2
22222

3333
    3
  333
    3
3333

  44
 4 4
44444
   4
   4

55555
5
5555
    5
5555

 6666
6
6666
6   6
 666

77777
    7
   7
  7
 7

 888
8   8
 888
8   8
 888

 999
9   9
 9999
    9
9999

 AAA
A   A
AAAAA
A   A
A   A

BBBB
B   B
BBBB
B   B
BBBB

 CCCC
C
C
C
 CCCC

DDDD
D   D
D   D
D   D
DDDD

EEEEE
E
EEE
E
EEEEE

FFFFF
F
FFF
F
F

 GGGG
G
G  GG
G   G
 GGGG

H   H
H   H
HHHHH
H   H
H   H

IIIII
  I
  I
  I
IIIII

JJJJJ
  J
  J
  J
JJ

K   K
K  K
KKK
K  K
K   K

L
L
L
L
LLLLL

M   M
MM MM
M M M
M   M
M   M

N   N
NN  N
N N N
N  NN
N   N

 OOO
O   O
O   O
O   O
 OOO

PPPP
P   P
PPPP
P
P

 QQ
Q  Q
Q QQ
Q  Q
 QQ Q

RRRR
R   R
RRRR
R  R
R   R

 SSSS
S
 SSS
    S
SSSS

TTTTT
  T
  T
  T
  T

U   U
U   U
U   U
U   U
 UUU

V   V
V   V
 V V
 V V
  V

W   W
W   W
W W W
WW WW
W   W

X   X
 X X
  X
 X X
X   X

Y   Y
 Y Y
  Y
  Y
  Y

ZZZZZ
   Z
  Z
 Z
ZZZZZ

```

Yes I know the 4 and Q are ugly

# An example

Input

```
0123456789

```

Output

```
 012   567    6789   0123     34   45678   9012  34567   234    567
3  45    8        0      4   5 6   9      3          8  5   6  8   9
6 7 8    9     123     567  78901  0123   4567      9    789    0123
90  1    0    4          8     2       4  8   9    0    0   1      4
 234   12345  56789  9012      3   5678    012    1      234   5678

```

# Another example

Input

```
a3 B'2

```

Output

```
 A3B   B2A3   2A3B   2A3B
2   A      B  2   A      2
3B2A3    2A3  3B2A    A3B
B   2      B  3   B  2
A   3  2A3B   2A3B   A3B2A

```

Standard loopholes are forbidden. Code golf so no green tick will be given.

# Answer
> 16 votes
# Python 2, ~~413~~ ~~411~~ ~~373~~ ~~364~~ ~~352~~ 345 bytes

-1 byte thanks to Kevin Cruijssen.
-9 bytes thanks to Jo King.
-1 byte thanks to Lynn.

Data string contains unprintables, escaped version below.

```
k=list(filter(str.isalnum,input()))
q=range(5);o=['']*5;r=k*25;d=0
for c in'uM<LxSe#ye>El4NpD@$	gh>I,m]aB>e,]?kFLyglxV!%w832wGj%uT{Hr*K,*[P\n6.&ED#T}^DLI&p7f\d`*lG!FacG\rz?!A':d*=126;d+=ord(c)-1
for c in k:
 for i in q:
	for y in q+[999]*2:o[i]+=d>>int(c,36)*25+i*5+y&1and r.pop(0)or' '
print'\n'.join(o).upper()

```

Try it online!

As each character has 25 pixels it can be easily encoded in 25 bits. The base 126 number `'uM\x04<L\x10x\x14Se#ye\x0f>El4NpD@$\tgh>\x1d\x10\x15I,\x0em]a\x0e\x03B>e\x15,\x0c]\x03?kFL\x01\x0byglxV!\x18\x16\x0c\x0b\x10\x0b%w832wGj%uT{Hr*K,*[P\n6.&ED#T\x0c}^\x1c\x0fD\x17LI&p7\x17f\\d`*\x01l\x1bG\x12!Fac\x05\x08\x0eG\rz?!\x1aA'` encodes all chars, the `0` is encoded by the least significant 25 bits, the `1` by the next 25 bits and the `Z` is encoded by the 25 most significant bits. A single character is encoded in the following order:

```
00 01 02 03 04
05 06 07 08 09
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

```

(`00` is the least significant bit, `25` the most significant one)

Spaces are encoded by a zero, non-spaces by a one. *Example*:

```
77777      11111
    7      00001
   7   =>  00010  => (0001000100010001000011111)
  7        00100
 7         01000

```

---

## Ungolfed

```
k = list(filter(str.isalnum,input()))  # keep only alphanumeric characters of the input
o = ['']*5   # this list contains the output, initially 5 empty lines
r = k * 25   # make a copy of the input 25-times the length, these chars will be used for the pixels
data = 0
#  data encoded in base 126
b92d = 'uM<LxSe#ye>El4NpD@$	gh>I,m]aB>e,]?kFLyglxV!%w832wGj%uT{Hr*K,*[P\n6.&ED#T}^DLI&p7f\d`*lG!FacG\rz?!A'
for c in b92d:          # convert base 92 to base 10
  d*=126;d+=ord(c)-1

for c in k:             # iterate over the filtered input
  a_index = int(c, 36)  # the index of the current char in '0..9A..Z' / '0..9a..z'
  for i in range(5):    # for each row of the output
    for y in range(5)+[999]*2:  # for each pixel in the row, th two 999's are used for spaces
      is_set = data >> (a_index*25 + i*5 + y) & 1  # We shift the to the right to have ...
                                                   # the current pixels value at the LSB:
                                                   # 25 bits for each char that came before
                                                   # 5 bits for each previous row and 1 bit
                                                   # for every pixel in the same row
      o[i] += is_set and r.pop(0) or ' '           # If the current pixel is set, append ...
                                                   # ... a character from the input to the current row
print '\n'.join(o).upper()  # print the output

```

Try it online!

# Answer
> 10 votes
# APL (Dyalog Unicode), ~~228~~ ~~225~~ ~~224~~ 214 bytes

Full program. Prompts stdin for string. Prints to stdout. About half of the code is just decoding the encoded alphabet.

```
⍉↓(⍴t)⍴r\i⍴⍨+/r←,t←(⊂a⍳i←(1(819⌶)⍞)∩a←⎕D,⎕A)⌷0(220⌶)¯1(219⌶)¯125+⎕AV⍳_________________________________________________________________________________________________________________________________________________

```

`_``_` represents the following 143-byte LZ4-encoded string in quotes: `"⊥\u0004pæ€}€\\⊃⌿Æ€â<Å€∧€ÀÆ€Ð┬:Ëcü\u0000≥ðè⊤õ⍨¢∧·èý\u0005þÐÕ\u001EÐ :\u001Eè⌊×ßi[B⊂ɫoÃ£à oéìÐ⍙⊃Ý∣à)≥èB⊃\u001B\u001F⊥ä{⌿⍨ G⍺\u001B⌿Æ\u001F∇x└îR`:└è→⊂\u0000ê∧⍒\u0003ɫqè$$ÛD⊥â∊\u001B\u001Eéu|\u001B@4A|⍪┌nàkááÐ€€€€€€€"`

Try it online!

`_``_` 143-byte LZ4-encoded string in quotes

`⎕AV⍳`**ɩ**ndices of that in the **A**tomic **V**ector (the character set)

`¯125+` add -125 to that (to get signed 8-bit integers)

`¯1(219⌶)` LZ4 decompress

`0(220⌶)` deserialise to a 36 layer, 5 row, 5 column Boolean array

`(``)⌷` index into that using the following indices:

`⎕A` uppercase **A**lphabet

`⎕D,` prepend the **D**igits

`a←` store in `a` (for **a**lphabet)

`(``)∩` intersection of the following and that (removes invalid input):

prompt for text input from stdin (console)

`1(819⌶)` fold to uppercase (`819` looks like `Big`, 1 is for yes big as opposed to small)

`i←` store in `i` (for **i**nput)

`a⍳`**ɩ**ndices of that in `a`

enclose (to index with each one representing the leading coordinate)

`t←` store in `t` (for **t**ext)

`,` ravel (flatten)

`r←` store in `r` (for **r**avelled)

`+/` sum that (i.e. number of characters needed to paint the artwork)

`i⍴⍨` cyclically **r**eshape the input to that length

`r\` expand that; insert a spaces at 0s, consume letters at 1s

`(`…)⍴\` reshape to the following shape:

`⍴t` the shape of the text

split the N-by-5-by5 array into an N-by-5 matrix of art lines

transpose into a 5-by-N matrix of art lines (this aligns corresponding lines of the characters)

By default, APL separates simple elements of a nested array with 2 spaces.

# Answer
> 9 votes
# Python 2, 428 bytes

```
s=filter(str.isalnum,input().upper());x=s
R=['']*5
for c in s:
 i=0;exec"n=int('RAAAOQQ2RBAQBQRRBDRRDCDDAQ8QBRDDDDDRXDDF0XX6CCDDCDCCCD00ECNLDDEDC0DDD66YYABH0A3RQQRQCDOOFR00OCHHDQIQA0D6H0000DXL0CXYXDDDCDCCDD00ECDFDCEEX0D6N6044AQARRQYQADQBQRCBDRKDRDDAC9DQ0A0DD0R'[i*36+ord(c)%55%45],36);R[i]+=bin(n+36*(n<30)<<2)[3:].replace(*'0 ').replace(*'1.');i+=1;"*5
 while'.'in`R`:R=eval(`R`.replace('.',x[0],1));x=x[1:]+s
print'\n'.join(R)

```

Try it online!

---

The letters are encoded as follows:

Each unique part (there are 23) is converted to binary, and a 1 is added in front. Then it is converted to base 36.

```
  part      bin      1+bin     int     base36
'  ...' -> 00111 -> 100111 ->   39  ->   13

```

The resulting base-36 numbers are:

```
[10,12,13,14,16,18,19,1A,1B,1C,1D,1E,1F,1H,1I,1K,1L,1N,1O,1Q,1R,X,Y]

```

The initial `1` is removed, so we have a single character:

```
[0,2,3,4,6,8,9,A,B,C,D,E,F,H,I,K,L,N,O,Q,R,X,Y]

```

Each letter (`A-Z0-9`) is then encoded to five of these new chars.

```
0 = ' ... ','.  ..','. . .','..  .',' ... ' -> A,F,H,L,A
1 = '...  ','  .  ','  .  ','  .  ','.....' -> O,0,0,0,R
etc.

```

Into five lists:

```
'AOQQ2RBRAAAQBQRRBDRRDCDDAQ8QBRDDDDDR'
'F0XX6CCXDDDDCDCCCD00ECNLDDEDC0DDD66Y'
'H0A3RQQYABRQCDOOFR00OCHHDQIQA0D6H000'
'L0CXYXD0DXDDCDCCDD00ECDFDCEEX0D6N604'
'ARRQYQA4AQDQBQRCBDRKDRDDAC9DQ0A0DD0R'

```

To map the input to an index in these lists, the ordinal is modded:

```
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ord(c) = [48-57, 65-90]
ord(c)%55%45 = [3-9, 0-2, 10-35]

```

Because the ordinals are not 0-35, but slightly mixed, the 5 lists are rearranged, and concatenated:

```
'RAAAOQQ2RBAQBQRRBDRRDCDDAQ8QBRDDDDDR'
'XDDF0XX6CCDDCDCCCD00ECNLDDEDC0DDD66Y'
'YABH0A3RQQRQCDOOFR00OCHHDQIQA0D6H000'
'0DXL0CXYXDDDCDCCDD00ECDFDCEEX0D6N604'
'4AQARRQYQADQBQRCBDRKDRDDAC9DQ0A0DD0R'
->
'RAAAOQQ2RBAQBQRRBDRRDCDDAQ8QBRDDDDDRXDDF0XX6CCDDCDCCCD00ECNLDDEDC0DDD66YYABH0A3RQQRQCDOOFR00OCHHDQIQA0D6H0000DXL0CXYXDDDCDCCDD00ECDFDCEEX0D6N6044AQARRQYQADQBQRCBDRKDRDDAC9DQ0A0DD0R'

```

---

For each char in the input, it's 5 letters are found, and converted to a ints(base36):

```
n=int('RAAA...D0R'[i*36+ord(c)%55%45],36)
                   i*36                    #get row i
                        ord(c)%55%45       #n -> 0..35
  int(                               ,36)  #convert to int

```

If the number is below `30`, `36`is added (the missing `1`we removed earlier)

```
n+36*(n<30)

```

Then the number is converted back to binary, and `0`s and `1`s are converted to and `.`. Two spaces are added at the end during the conversion.

```
bin(n+36*(n<30)<<2)[3:].replace(*'0 ').replace(*'1.')

    n+36*(n<30)                                       #add leading base36 '1'
               <<2                                    #add 2 0's to end
bin(              )                                   #convert to binary string
                   [3:]                               #remove '0b1' from front
                       .replace(*'0 ').replace(*'1.') #replace 0 and 1

```

Eg.

```
C    base36    int     <<2       bin-str        str
3 ->   13   ->  39  ->  156 -> 0b10011100 -> '  ...  '

```

For each `.` in the result, it is replaced by the next character from the input (iterated by `x`)

```
while'.'in`R`:R=eval(`R`.replace('.',x[0],1));x=x[1:]+s

```

# Answer
> 6 votes
# Java 8, ~~917~~ 907 bytes

```
int i,l;String[]S;s->{String q=" ",t="",r[]={t,t,t,t,t};S=s.toUpperCase().replaceAll("[^A-Z0-9]",t).split(t);i=-1;l=S.length;for(String c:S){r[0]+=s("12357BDEFHIJKLMNPRTUVWXYZ",c)+s("012356789ABCDEFGIJOPQRSTZ",c)+s("0123456789ABCDEFGIJOPQRSTZ",c)+s("023456789ABCDEFGIJOPRSTZ",c)+s("567CEFGHIJKMNSTUVWXYZ",c)+q;r[1]+=s("05689ABCDEFGHKLMNOPQRSUVW",c)+s("4MNXY",c)+s("1IJT",c)+s("04KMQXYZ",c)+s("023789ABDHMNOPRUVW",c)+q;r[2]+=s("0456ABCDEFGHKLMNOPQRUW",c)+s("245689ABEFHKPRSV",c)+s("012345689ABEFHIJKMNPQRSTWXYZ",c)+s("23456789ABGHPQRSV",c)+s("0349ADGHMNOUW",c)+q;r[3]+=s("0268ABCDEFGHKLMNOPQRUW",c)+s("0VWXZ",c)+s("17IJTY",c)+s("4KNQRVWX",c)+s("035689ABDGHMNOSUW",c)+q;r[4]+=s("12359ABDEFHIJKLMNPRSWXZ",c)+s("012356789BCDEGIJLOQSUZ",c)+s("01235689BCDEGILOQSTUVYZ",c)+s("012345689BCDEGILOSUZ",c)+s("12ACEGHIKLMNQRWXZ",c)+q;}return"".join("\n",r);}String s(String...s){return s[0].contains(s[1])?S[++i%l]:" ";}

```

Will golf it down from here to at least halve the current byte-count hopefully..

Try it online.

**Explanation:**

```
int i,                         // Index-integer on class-level
    l;                         // Length-integer on class-level
String[]S;                     // String-array of characters on class-level

s->{                           // Method with String as both parameter and return-type
  String q="  ",               //  Temp String containing two spaces to reduce bytes
         t="",                 //  Temp Empty String to reduce bytes
         r[]={t,t,t,t,t};      //  Start with five empty rows
  S=s.toUpperCase()            //  Transform the input-String to uppercase
     .replaceAll("[^A-Z0-9]",t)//  Remove all non alphanumeric characters
     .split(t);                //  And transform it into a String-array of characters
  i=-1;                        //  Set the index-integer on -1 to start with
  l=S.length;                  //  Set the length of the modified input
  for(String c:S){             //  Loop over the characters of the modified input:
    r[0]+=                     //   Append to the first row:
          s("12357BDEFHIJKLMNPRTUVWXYZ",c)      // The first pixel
          +s("012356789ABCDEFGIJOPQRSTZ",c)     // The second pixel
          +s("0123456789ABCDEFGIJOPQRSTZ",c)    // The third pixel
          +s("023456789ABCDEFGIJOPRSTZ",c)      // The fourth pixel
          +s("567CEFGHIJKMNSTUVWXYZ",c)         // The fifth pixel
          +q;                                   // Two trailing spaces
    r[1]+=                     //   Append to the second row:
          s("05689ABCDEFGHKLMNOPQRSUVW",c)      // The first pixel
          +s("4MNXY",c)                         // The second pixel
          +s("1IJT",c)                          // The third pixel
          +s("04KMQXYZ",c)                      // The fourth pixel
          +s("023789ABDHMNOPRUVW",c)            // The fifth pixel
          +q;                                   // Two trailing spaces
    r[2]+=                     //   Append to the third row:
          s("0456ABCDEFGHKLMNOPQRUW",c)         // The first pixel
          +s("245689ABEFHKPRSV",c)              // The second pixel
          +s("012345689ABEFHIJKMNPQRSTWXYZ",c)  // The third pixel
          +s("23456789ABGHPQRSV",c)             // The fourth pixel
          +s("0349ADGHMNOUW",c)                 // The fifth pixel
          +q;                                   // Two trailing spaces
    r[3]+=                     //   Append to the fourth row:
          s("0268ABCDEFGHKLMNOPQRUW",c)         // The first pixel
          +s("0VWXZ",c)                         // The second pixel
          +s("17IJTY",c)                        // The third pixel
          +s("4KNQRVWX",c)                      // The fourth pixel
          +s("035689ABDGHMNOSUW",c)             // The fifth pixel
          +q;                                   // Two trailing spaces
    r[4]+=                     //   Append to the fifth row:
          s("12359ABDEFHIJKLMNPRSWXZ",c)        // The first pixel
          +s("012356789BCDEGIJLOQSUZ",c)        // The second pixel
          +s("01235689BCDEGILOQSTUVYZ",c)       // The third pixel
          +s("012345689BCDEGILOSUZ",c)          // The fourth pixel
          +s("12ACEGHIKLMNQRWXZ",c)             // The fifth pixel
          +q;}                                  // Two trailing spaces
  return"".join("\n",r);}      //  Return the rows joined with new-lines

//  Separated method with String-varargs parameter and String return-type
String s(String...s){
  return s[0].contains(s[1])?  //  If the String contains the character-String:
                               //   Increase `i` by 1 first with `++i`
    S[++i%l]                   //   Then return the i'th character of the modified input
                               //   with wraparound by using modulo-`l`
   :                           //  Else:
    " ";}                      //   Return a space

```

# Answer
> 6 votes
# Japt v2.0a0 `-R`, ~~213~~ ~~211~~ ~~210~~ ~~209~~ ~~206~~ ~~193~~ ~~191~~ ~~190~~ ~~188~~ 187 bytes

```
u f\w Ën36 g`...`ò4)nLõd)¤®Í?FgT°:SÃò5n)ù6ÃÕm¸

```

Try it or test all characters (the extra bytes are due to TIO not supporting Japt v2)

---

## Explanation

### Lookup Table

Every group of 4 characters in the backtick enclosed string (represented by `...` above to save space and because it contains a bunch of unprintables) is the binary representation of each character (`0` for spaces, `1` for characters) with the newlines removed and converted to base-100.

**Example**

```
ZZZZZ -> 11111
   Z  -> 00010
  Z   -> 00100 -> 1111100010001000100011111 -> 32575775 -> !::L
 Z    -> 01000
ZZZZZ -> 11111
```

### The Code

```
u f\w Ën36 g`...`ò4)nLõd)¤®Í?FgT°:SÃò5n)ù6ÃÕm¸     :Implicit input of string U
u                                                  :Uppercase
  f                                                :Match
   \w                                              :  RegEx /[a-z0-9]/gi
      Ë                                            :Map each D in array F
       n36                                         :  Convert D from base-36 to decimal
           g                                       :  Index into
            `...`                                  :    The string described above
                 ò4                                :    Partitions of length 4
                   )                               :  End Indexing
                    n                              :  Convert from base
                     Lõ                            :    Range [1,100]
                       d                           :    Get characters at those codepoints
                        )                          :  End base conversion
                         ¤                         :  Convert to binary
                          ®                        :  Map
                           Í                       :    Convert from binary to decimal
                            ?                      :    If truthy (i.e, 1)
                             Fg                    :      Get the element in F at index
                               T°                  :        T (initially 0) postfix incremented
                                 :                 :    Else
                                  S                :      Space
                                   Ã               :  End map
                                    ò              :  Partitions of length
                                     5n            :    -5 (i.e., weighted towards the end)
                                       )           :  End partition
                                        ù6         :  Left pad each with spaces to length 6
                                          Ã        :End map
                                           Õ       :Transpose
                                            m      :Map
                                             ¸     :  Join with spaces
                                                   :Implicit output joined with newlines

```

# Answer
> 4 votes
# Ruby, 366 bytes

```
->s{s.tr!('^0-9A-Za-z','');b=([s]*s.size).map(&:chars);%w(esuu6vfveeeufuvvfhvvhghheucufvhhhhhv j411agg1hhhhghgggh44igrphhihg4hhhaa2 l4e7vuu2efvughssjv44sgllhumue4hal444 p4g121h4h1hhghgghh44ighjhgii14hara48 evvu2ue8euhufuvgfhvohvhhegdhu4e4hh4v).map{|x|w=t='';s.chars{|c|c=~/\w/&&w+="%5b  "%x[c.to_i 36].to_i(36)};w.size.times{|i|t+=w[i]>?0?b[i/7].rotate![-1]:' '};t}}

```

Try it online!

This can be golfed a lot, but now I've run out of time and ideas. It was harder than I first thought just to get it working.

### How it works:

It's not so hard to understand, I'll just explain how the alphabet is coded with an example. Every line of every character is converted to binary and then to base-36.

```
 AAA   -> 01110 -> E
A   A  -> 10001 -> H
AAAAA  -> 11111 -> V
A   A  -> 10001 -> H
A   A  -> 10001 -> H

```

The first step is stripping all non-alphanumeric characters from the input string.

Then I generate a lookup table for the final rendering, because I want to print line for line.

After that, iterating on the alphabet line, I create the binary pattern of the letters.

Finally I replace 0 with spaces and 1 with characters from the lookup table.

Feel free to golf further, I know this could be 20-30 bytes shorter (using gsub instead of tr, and so on), but I'm not interested now, unless I can make the alphabet table drastically smaller.

# Answer
> 4 votes
# Charcoal, ~~172~~ 164 bytes

```
≔⁺⭆χιαα≔Φ↥Ｓ№αιθＦθ«Ｅ⁵⭆§⪪”)∧%"<⁰ＥＴV´el⟧2[◧À&η²p.±‹§Ｋ×GＲ←∨�X¶⌈hＦ)ξυ9ＤUuqε↘Ｚ)s⎚H⊙←<¿.＆]～b≧✂⪪XïＪ61%ZWm/ειK⮌λ﹪▷(σΠＮc←º✳Ｆb⌕⊘¹ÞＥpＭ＆➙δl◨α↑j≕ςL¡ρG⁰/y”⁵⁺κ×⁵⌕αι⎇Ｉμ§θ⊖Ｌ⊞Ｏυω Ｍ⁷±⁵

```

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

```
≔⁺⭆χιαα

```

Prefix the digits to the predefined uppercase alphabet.

```
≔Φ↥Ｓ№αιθ

```

Uppercase the input and filter out all the unsupported characters.

```
Ｆθ«

```

Loop over the remaining characters.

```
Ｅ⁵

```

Loop over each row, implicitly printing each result on its own line.

```
⭆§⪪”...”⁵⁺κ×⁵⌕αι

```

The compressed string is @ovs's large integer constant, converted to binary and reversed. It is then sliced into 180 substrings of 5 characters, and the relevant substring for the current character and row is then looped over.

```
⎇Ｉμ§θ⊖Ｌ⊞Ｏυω

```

If the bit was set then cyclically print the next character of the filtered input otherwise print a space.

```
Ｍ⁷±⁵

```

Position the cursor ready to print the next character.

# Answer
> 3 votes
## Perl 5 with `-nlaF/[^A-Za-z0-9]+|/`, 247 bytes

```
@l{0..9,A..Z}=unpack("b*",q&....!.?.......G...../.......\....c|...C......'..N.>..c.1~B......I1..~.5.8k....^|!...}.......BH.1..."1..."*FE.....&)=~/.{25}/g;eval'$;[$j%5].=($l{+uc}=~/.{5}/g)[$j++%5]=~s/./$&?uc$F[$i++%@F]:$"/ger.$"x2;'x5for@F;say for@

```

Try it online!

---

## Explanation

First a lookup table is created in `%l` using the `pack`ed data. This data is a 900-bit binary string of each char packed as a 25-bit binary string (stored as 113 bytes - only 1 more byte than charcoal!), similar to some other answers, so `A` is:

```
 AAA
A   A
AAAAA
A   A
A   A

```

which, using `0` for space and `1` for `A` is:

```
01110
10001
11111
10001
10001

```

and without the line breaks is:

```
0111010001111111000110001

```

Once the lookup is initialised, we iterate over each valid char in `@F` (which is populated using Perl's `-a`utosplit option) appending to each of the 5 elements of the list `@;` for each row in the array from the lookup, replacing all `1`s with `uc$F[$i++%@F]` which is the `$i`th character (modulo `@F` which is the length of `@F`) converted to `u`pper`c`ase, and all `0`s with `$"` which defaults to space. Once each index in `@;` is populated for each character in `@F`, `say` prints each line with a trailing newline.

**Note**: the string after `unpack` contains unprintables which are escaped using `\xXX` notation. Verification for score of 247.

# Answer
> 3 votes
# SOGL V0.12, ~~165~~ ~~164~~ 163 bytes

```
⁰CīøDs8↓3‛⁸⁷ω8<t↑\≈⅓dPb¦l═│Æ¹č<⁷i3ζ°@Ο≠ΖηKπ⁴Φd←⅔Ωī$∞ΧΗf▼xƧqWƨ∑ģpc!ƨ@┐Γ<§5ΛMn«Ιq;⁾№╔1xdψBN≤⁴ζ8□\b╗³╤>↔²Μ±}H}≤╬bφIæ7“2─{rƧ- W}⁰∑M¼nEU{SUZ+;W:?ew;cF+C}X}⁰┌cŗā;{√┼@L*┼

```

Try it Here!

Explanation:

```
...“                 big long number of the character data
    2─               convert to a base 2 string
      {r    }        for each number in it
        Ƨ- W           get it's index in "- ": space for 0, dash for 1
             ⁰∑      join up the results
               M¼n   split into groups of 25 - the letters
                  E  save that in variable E

U{                 }⁰ map over the input uppercased
  SUZ+                  push 1234567890 + the alphabet
      ;W                get the current characters index in that string
        :?       }      duplicate, if not 0 (aka if found)
          e               push the variable E
           w              get in it the duplicated number'th item
                            this leavesleaving the array below the item
            ;             get the array ontop
             cF+C         append the character to the array C
                  X     and remove the top item - either the duplicate or the array

┌             push "-"
 c            load the variable C
  ŗ           cycically replace "-" in maps result with the characters of C
   ā          push an empty array - the output
    ;{        for each item in the result of the replacement
      √         squareify it
       ┼        and append that to the output array
        @L*┼    top-to-bottom, left-to-right add 10 spaces to the array

```

# Answer
> 2 votes
# JavaScript (Node.js), ~~365~~ 347 bytes

*Saved 1 byte thanks to @Scoots*

Returns an array of 5 strings. Includes a leading space on each row.

~~37~~ 36 bytes are lost in converting everything to uppercase and matching `[A-Z0-9]` :-/

```
a=>(a=a.toUpperCase(s=[...'     ']).match(/[A-Z\d]/g)).map(x=c=>(g=n=>n<35&&g(n+1,s[n<25?n/5|0:n%5]+=Buffer("mJ*Z?<^#?.&+o@V+`L7ho=Jkm?`:Tm)Km?ZZo@p*#MmjoCZ[=('ZoC#;?-g[RZW[>.cJ#Mmm?<^;Vp5[#p*]?,iM#KAm$$:Mm?0*R[#;-46B#qC;o==*X$(km?0-XDc=$.Mm#%]=X$*-?1M[".slice(parseInt(c,36)*(i=v=4))).map(c=>v+=c%80*80**--i)|v>>n&n<25?a[++x]||a[x=0]:' '))(0))&&s

```

Try it online!

### Character encoding

Characters are encoded upside-down and converted to a custom base-80 with an offset of **4**, using the ASCII range **\[35..114\]**.

Values **35** to **79** are directly mapped to the corresponding ASCII character, while values **0** to **34** are mapped to characters **80** to **114**. This allows to decode by just taking the ASCII code **modulo 80**.

For instance, **'F'** is encoded as `"RZW["`:

```
....#     00001
....#     00001
..### --> 00111 --> 0000100001001110000111111 --[decimal]--> 1088575 --[-4]--> 1088571
....#     00001
#####     11111

floor(1088571 / 80**3)        = 2    --> (( 2 + 45) mod 80) + 35 = 82  --> 'R'
floor(1088571 / 80**2) mod 80 = 10   --> ((10 + 45) mod 80) + 35 = 90  --> 'Z'
floor(1088571 / 80)    mod 80 = 7    --> (( 7 + 45) mod 80) + 35 = 87  --> 'W'
1088571                mod 80 = 11   --> ((11 + 45) mod 80) + 35 = 91  --> '['

```

Starting with **i = v = 4**, it is decoded back to a 25-bit integer by doing:

```
Buffer("RZW[").map(c => v += c % 80 * 80 ** --i)

```

In the full code, we actually process an unbounded **slice()** of the encoded stream, which means that we are likely to iterate significantly more than **4** times. This is not a problem because all iterations with **i \< 0** will only affect the decimal part of the result, which is ignored anyway by the bitwise operations that immediately follow.

Try it online!

# Answer
> 1 votes
# Excel VBA, 816 bytes

An anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the console.

As far as I am aware, this is the first VBA answer to use `base64` compression.

```
For i=1To[Len(A1)]:c=Mid(UCase([A1]),i,1):y=y &IIf(c Like"[0-9A-Z]",c,""):Next:l=Len(y):Set d=New MSXML2.DOMDocument:Set d=d.createElement("b64"):d.DataType="bin.base64":d.Text="HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnzTHGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc=":b=d.nodeTypedValue:For i=0To 112:k=Right("00000" &Evaluate("=Dec2Bin("&b(i)&")"),8)&k:Next:For i=1To 5:For j=1To l:c=UCase(Mid(y,j,1)):Z=c Like"[0-9]":s=s &IIf(c Like"[A-Z]",Mid(k,IIf(Z,1,25*(Asc(c)-55)+5*i),5)&" ",IIf(Z,Mid(k,25*(Asc(c)-48)+5*i,5)&" ","")):Next:s=Replace(Replace(s,0," "),1,"#") &vbLf:Next:Do:i=InStr(1+(g*l+h)*6+g,s,"#"):p=(p-e)Mod l:e=i<(g*l+h+1)*6+g:s=IIf(e,Left(s,i-1)&Replace(s,"#",Mid(y,p+1,1),i,1),s):g=g-(0=e):h=h-(g>4):g=g Mod 5:Loop While InStr(1,s,"#"):?s

```

*Note: This answer depends on the `Microsoft XML, v3.0` VBA reference*

### Example I/O

```
[A1]="'0123456789"
For i=1To[Len(A1)]:c=Mid(UCase([A1]),i,1):y=y &IIf(c Like"[0-9A-Z]",c,""):Next:l=Len(y):Set d=New MSXML2.DOMDocument:Set d=d.createElement("b64"):d.DataType="bin.base64":d.Text="HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnzTHGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc=":b=d.nodeTypedValue:For i=0To 112:k=Right("00000" &Evaluate("=Dec2Bin("&b(i)&")"),8)&k:Next:For i=1To 5:For j=1To l:c=UCase(Mid(y,j,1)):Z=c Like"[0-9]":s=s &IIf(c Like"[A-Z]",Mid(k,IIf(Z,1,25*(Asc(c)-55)+5*i),5)&" ",IIf(Z,Mid(k,25*(Asc(c)-48)+5*i,5)&" ","")):Next:s=Replace(Replace(s,0," "),1,"#") &vbLf:Next:Do:i=InStr(1+(g*l+h)*6+g,s,"#"):p=(p-e)Mod l:e=i<(g*l+h+1)*6+g:s=IIf(e,Left(s,i-1)&Replace(s,"#",Mid(y,p+1,1),i,1),s):g=g-(0=e):h=h-(g>4):g=g Mod 5:Loop While i<InStrRev(s,"#"):?s
 012  567   6789  0123    34  45678  9012 34567  234   567
3  45   8       0     4  5 6  9     3         8 5   6 8   9
6 7 8   9    123    567 78901 0123  4567     9   789   0123
90  1   0   4         8    2      4 8   9   0   0   1     4
 234  12345 56789 9012     3  5678   012   1     234  5678

```

### Ungolfed and Explained

The major part of this solution storing the large font as a base 64 string. This is done by first converting the font to binary, where `1` represents an on pixel and `0` represents an off pixel. For example, for `0`, this is represented as

```
      ###     01110
     #  ##    10011
0 -> # # # -> 10101 --> 0111010011101011100101110
     ##  #    11001
      ###     01110

```

With this approach, the alphanumerics can then be represented as

```
0: 0111010011101011100101110    1: 1110000100001000010011111
2: 1111000001011101000011111    3: 1111000001001110000111110
4: 0011001010111110001000010    5: 1111110000111100000111110
6: 0111110000111101000101110    7: 1111100001000100010001000
8: 0111010001011101000101110    9: 0111010001011110000111110
A: 0111010001111111000110001    B: 1111010001111101000111110
C: 0111110000100001000001111    D: 1111010001100011000111110
E: 1111110000111001000011111    F: 1111110000111001000010000
G: 0111110000100111000101111    H: 1000110001111111000110001
I: 1111100100001000010011111    J: 1111100100001000010011000
K: 1000110010111001001010001    L: 1000010000100001000011111
M: 1000111011101011000110001    N: 1000111001101011001110001
O: 0111010001100011000101110    P: 1111010001111101000010000
Q: 0110010010101101001001101    R: 1111010001111101001010001
S: 0111110000011100000111110    T: 1111100100001000010000100
U: 1000110001100011000101110    V: 1000110001010100101000100
W: 1000110001101011101110001    X: 1000101010001000101010001
Y: 1000101010001000010000100    Z: 1111100010001000100011111

```

These segments were concatenated and converted to MSXML base 64, rendering

```
HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnzTHGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc=

```

The subroutine below takes this, back converts to binary, and uses this a reference from which to build an output string, line by line, grabbing first the top 5 pixels of each character, then the second row and so on until the string is constructed.

The subroutine then iterates over the output string and replaces the 'on' pixels with characters from the input string.

```
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
''  Embiggen Function
''
''  @Title  :   Embiggen
''  @Author :   Taylor Scott
''  @Date   :   15 June 2018
''  @Desc   :   Function that takes input, value, and outputs a string in which
''              value has been filtered to alphnumerics only, each char is then
''              scaled up to a 5x5 ASCII art, and each 'pixel' is replaced with
''              a char from value. Replacement occurs letter by letter, line by
''              line
''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function EMBIGGEN(ByVal value As String) As String

    Dim DOM         As New MSXML2.DOMDocument, _
        bytes()     As Byte

    Dim isNum       As Boolean, _
        found       As Boolean, _
        index       As Integer, _
        length      As Integer, _
        line        As Integer, _
        letter      As Integer, _
        pos         As Integer, _
        alphanum    As String, _
        char        As String, _
        filValue    As String, _
        outValue    As String

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Filter input
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    For letter = 1 To Len(value) Step 1             ''  Iterate Accross `Value`
        Let char = Mid$(UCase(value), letter, 1)    ''  Take the nth char
        ''  If the char is alphnumeric, append it to a filtered input string
        Let filValue = filValue & IIf(char Like "[0-9A-Z]", char, "")
    Next letter
    Let length = Len(filValue)                      ''  store length of filValue

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Convert Constant from Base 64 to Byte Array
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    With DOM.createElement("b64")           ''  Construct b64 DOM object
        Let .DataType = "bin.base64"        ''  define type of object`
        ''  Input constructed constant string shown above
        Let .Text = "HxHxCSEqRkVUjLvGSJSK0cUYIyGEfB8cfFH66Ju0kkHoo3cxRhdnz" & _
                     "THGuuOHEMIouYyYEPI/IeTH+GN8ccIHIYf/Qw6/jzH6ByF8PvroY/" & _
                     "zR+fCic9FFh4gI30UPnw8efiG+Mj6c4D90wX9CCHe5Tgc="
        Let bytes = .nodeTypedValue         ''  Pass resulting bytes to array
    End With

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Convert Byte Array to Byte String
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    For index = 0 To 112 Step 1
        '' convert each byte to binary, fill left with `0`s and prepend
        Let alphanum = _
            Right("00000" & Evaluate("=Dec2Bin(" & bytes(index) & ")"), 8) & _
            alphanum
    Next index

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Construct Embiggened Binary String of Input Value
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    For line = 1 To 5 Step 1                ''  iterate across lines
        For letter = 1 To length Step 1     ''  iterate across letters
            ''  take the corresponding letter from
            Let char = UCase(Mid(filValue, letter, 1))
            If char Like "[0-9]" Then       '' if it is a number,
                ''  Add the 5 bit corresponding to number at line
                Let outValue = outValue & _
                    Mid$(alphanum, 25 * Val(char) + 5 * line, 5) & " "
            ElseIf char Like "[A-Z]" Then   '' if it is a letter,
                ''  Add the 5 bits corresponding to letter at line
                Let outValue = outValue & _
                    Mid$(alphanum, 25 * (Asc(char) - 55) + 5 * line, 5) & " "
            End If
            Next letter
        Let outValue = outValue & IIf(line < 5, vbLf, "")
    Next line
    Let outValue = Replace(Replace(outValue, 0, " "), 1, "#")

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Replace #s with Input Value
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Let pos = 0                             ''  Reset position in filValue
    Let line = 0                            ''  Reset line index
    Let letter = 0                          ''  Reset letter index
    Do
        ''  Find the index of the first `#` starting at line and letter
        Let index = _
            InStr(1 + (line * length + letter) * 6 + line, outValue, "#")
        ''  Iterate position in filValue if a `#` is found in that letter & line
        Let pos = (pos - found) Mod length
        ''  check to see if found index is in the correct letter
        Let found = index < (line * length + letter + 1) * 6 + line
        ''  iff so, replace that # with letter in filValue corresponding to pos
        Let outValue = IIf(found, _
            Left(outValue, index - 1) & _
                Replace(outValue, "#", Mid(filValue, pos + 1, 1), index, 1), _
            outValue)
        ''  if not found, them iterate line
        Let line = line - (found = False)
        ''  iterate letter every five iterations of line
        Let letter = letter - (line > 4)
        ''  Ensure that line between 0 and 4 (inc)
        Let line = line Mod 5
    ''  Loop while there are '#'s in outValue
    Loop While InStr(1, outValue, "#")

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Output
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Let EMBIGGEN = outValue

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ''
    ''  Clean Up
    ''
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Set DOM = Nothoing
End Function

```

# Answer
> 1 votes
# C (gcc), 792 690 bytes

```
#define S strlen
#define V v[1][i]
#define A putchar(32);
#define F(x)(((G(x,0)*92+G(x,1))*92+G(x,2))*92+G(x,3))*92+G(x,4))
#define G(x,y)(f[(x-(x<58?48:55))*5+y]-35)
i,j,l;main(c,v)char**v;{l=S(v[c=1]);char*x[l],t[l+1],*p=t,*f="$dKqK&>%Q3&R`ms&RYXg#gAB/&b_R/$n>Pw&]?vO$cbu+$ccG#$csC+&X7sS$n0w[&X+={&b^%s&b^$W$n3qS%(4\\_&^Bjg&^Bj/%(Pec$xx%S%+L`/%*jjw$cel7&X7oS$NWLO&X7u3$n.U+&^BhG%(')k%'|*/%(+:'%%UO;%%U=K&]`{+";*x=t;for(;i<l;i++){V>96?V-=32:V;(V>47)&(V<58)|(V>64)&(V<91)?*(p++)=V:V;}*p=0;for(;c<S(t);)x[c++]=((__builtin_popcount(F(t[c-1])+x[c-1]-t)%S(t))+t;for(c=6;--c;){for(i=0;i<S(t);i++){for(j=5,l=1<<c*5+3;j--;)if((l>>=1)&F(t[i]){putchar(*x[i]++);!*x[i]?x[i]=t:x;}else A A A}puts(p);}}

```

Try it online!

Managed to squeeze this under 800 with some variable reuse. Opted to store the font as an array of `int`s, as although storing it as one long string looked like an attractive idea so many of the 8-bit chunks of the font weren't a nice convenient ASCII character that the escape codes were taking up more characters than the `int` array did.

Edit: Got under 700 by switching to a string encoding after all - somewhat inspired by many of the other responses here I cobbled together a base-92 representation using (most of) the printable ASCII characters. The representation does include backslashes which need an extra to be escaped but that only happens once in the font.

Other than that there isn't much that's too flashy going on - the input (consisting of the first command-line argument) is copied into a stack array, minus any characters that aren't in the font and with lowercase letters replaced with their uppercase versions, what "pixel" character each full letter starts on is computed (using `__builtin_popcount` has a painfully long name but was still better than any method of counting on bits I could think of), and then the printing goes through line by line. The compiler of course outputs several times the program length in warnings.

Somewhat degolfed below for your viewing pleasure:

```
//The defines are listed here for reference. Some are replaced in the below code but I still use F() because it's long.
#define S strlen
#define V v[1][i]
#define A putchar(32);
#define F(x)(((G(x,0)*92+G(x,1))*92+G(x,2))*92+G(x,3))*92+G(x,4))  //How to lookup a font character given an input char x
#define G(x,y)(f[(x-(x<58?48:55))*5+y]-35)                         //Used for looking up the individual parts of a character font
i, j, l;                                           // Declaring some int variables for later use.
main(c,v) char**v; {                               // Declaring afterwards lets us have the int arg default without declaring it
  l = strlen(v[c=1]);                              // Using l as a local variable to shorten S(v[1]) and also giving c an initial value here where there was a spare 1, saving a character over writing the full c=1 init in a later for loop.
  char t[l+1], *p=t, *x[l];                        // Declaring char arrays and char*s and char* arrays. t is oversized if there are any invalid characters in the input, but that's not important for golfing.
  char *f="$dKqK&>%Q3&R`ms&RYXg#gAB/&b_R/$n>Pw&]?vO$cbu+$ccG#$csC+&X7sS$n0w[&X+={&b^%s&b^$W$n3qS%(4\\_&^Bjg&^Bj/%(Pec$xx%S%+L`/%*jjw$cel7&X7oS$NWLO&X7u3$n.U+&^BhG%(')k%'|*/%(+:'%%UO;%%U=K&]`{+";      // The font, encoded base-92 with 5 characters to a letter in the order 0123456789ABCDEF... etc.
  *x=t;                                            // The first character's "pixels" will start at the beginning of the valid input.
  for(; i<strlen(l); i++){                         // Speaking of which, now validate the input.
    v[1][i] > 96 ? v[1][i] -= 32 : v[1][i];        // Change lowercase characters to uppercase. If they aren't actually lowercase characters but have ascii value >96, they won't end up valid after this either and will be edited out on the next line. The false case does nothing, but since with the macro it is one character using the ternary operator saves a character over an if statement even though that case ends up redundant.
    (v[1][i]>47)&(v[1][i]<58)|(v[1][i]>64)&(v[1][i]<91)?*(p++)=v[1][i]:v[1][i];        // If the character is now either a numeral or an uppercase letter, set the next spot in the t array by way of the pointer p and then increment said pointer.
  }
  *p=0;                                            // Add the null terminator to the t array, our validated input string.
  for(;c<strlen(t);) {                             // Now find out at what index each letter should start getting "pixels" from.
    x[c++] = ((__builtin_popcount(F(t[c-1])+x[c-1]-t)%strlen(t))+t;          // Use the builtin to get the number of on bits/pixels in the previous letter, then add that to the previous letter's starting pixel and take the modulus strlen() of the valid string.
  }
  for(c=6; --c;){                                  // Now start the actual printing. For each line...
    for(i=0; i<strlen(t); i++){                    // For each letter...
      for(j=5, l=1<<c*5+3; j--;) {                 // For each pixel of the 5 on this line...
        if((l>>=1) & F(t[i]) {                     // If it is on...
          putchar(*x[i]++);                        // Print it and increment the pixel-fetching pointer for this letter.
          !*x[i]?x[i]=t:x;                         // If said pointer hit the end of the valid input go back to the beginning.
        } else {
          putchar(32);                             // If it is an off pixel, print a space.
        }
      }
      putchar(32);                                 // After a letter, print two spaces.
      putchar(32);
    }
    puts(p);                                       // This is the cheapest way in character count I could come up with to output a newline. p currently points to the end of t, so it is an empty string and puts just adds a newline.
  }
}

```

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


title: Fun with strings and numbers

text:
# Question
Title: Fun with strings and numbers
Here's a programming puzzle for you:

Given a list of pairs of strings and corresponding numbers, for example, `[[A,37],[B,27],[C,21],[D,11],[E,10],[F,9],[G,3],[H,2]]`, output another list which will have just the strings in the following manner:

1. The total count of any string should be exactly equal to its corresponding number in the input data.
2. No string should be repeated adjacently in the sequence, and every string should appear in the output list.
3. The selection of the next string should be done randomly as long as they don't break above two rules. Each solution should have a non-zero probability of being chosen.
4. If no combination is possible, the output should be just `0`.

The input list may be given in any order (sorted or unsorted), and the strings in the list may be of any length.

---

Sample output for the above sample input 1

`[A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,C,A,C,A,C,A,C,A,C,A,C,A,C,A,C,A,C,A,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,E,F,E,F,E,F,E,F,E,F,E,F,E,F,E,F,E,F,E,G,H,G,H,G]`

---

Input sample 2:

`[[A,6],[B,1],[C,1]]`

Output for second input:

`0`

since no list possible based on rules.

---

Sample input 3:

`[[AC,3],[BD,2]]`

valid output: `[AC,BD,AC,BD,AC]`

invalid output: `[AC,BD,AC,AC,BD]`

---

If further clarification is needed, please, do not hesitate to tell me in the comments and I will promptly act accordingly.

This is , so shortest code in bytes for each language wins!

# Answer
# Jelly, 11 bytes

```
Œṙ'Œ!⁻ƝẠ$ƇX

```

Try it online!

```
Œṙ'Œ!⁻ƝẠ$ƇX Arguments: z
  '         Flat: Apply link directly to x, ignoring its left and right depth properties
Œṙ            Run-length decode
   Œ!       Permutations of x
         Ƈ  Filter; keep elements of x for which the link returns a truthy result
        $     ≥2-link monadic chain
      Ɲ         Apply link on overlapping pairs (non-wrapping)
     ⁻            x != y
       Ạ        Check if all elements of x have a truthy value (+vacuous truth)
          X Pick a random element of x; return 0 if the list is empty.

```
> 6 votes

# Answer
# Jelly, 17 bytes

```
Wẋ¥Ɲ€ẎẎŒ!Œɠ’SƊÐḟX

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~114~~ ~~189~~ ~~185~~ 174 bytes

```
from random import*
a=input()
s=u=[]
while a:x,y=a.pop(a.index(next((w for w in a if w[1]>sum(v[1]for v in a+u)/2),choice(a))));s=s+[x];a+=u;u=[[x,y-1]]*(y>1)
print[s,0][y>1]

```

Try it online!

Ouch! Much harder with rule 3... :). Still trying to avoid the `O(n!)` approach, so it can handle all the test cases sometime before the heat death of the universe...

Algorithm: suppose the total sum of the string counts is `t`. If any string has a count `n` with `2*n>t+1`, then it is not possible to satisfy the constraints. Therefore, if any string (excluding the previously chosen one) has count `n` with `2*n=t+1`, then we must choose that string next. Otherwise, we can choose at random any string which is not the previously chosen string.
> 5 votes

# Answer
# , ~~148~~ 141 bytes

```
function(x,y,p=combinatXXpermn(rep(seq(y),y)),q=which(sapply(lapply(p,diff),all)))"if"(n<-sum(q|1),"if"(n-1,x[p[[sample(q,1)]]],x[p[[q]]]),0)

```

Try it online! (I've copied `combinat::permn` and called it `combinatXXpermn` there.)

Brute force O(n!) solution.

Uses `permn` from the `combinat` package to generate all possible orderings. Then checks to see if any follow the rules, and picks one of those at random.
> 4 votes

# Answer
# J, 60 53 bytes

*-7 thanks to FrownyFrog*

```
(?@#{])@(#~*/@(2~:/\])"1)@(]i.@!@#@;A.;) ::0(#~>)/&.>

```

## original

```
(?@#{])@(#~2&([:*/~:/\)"1)@(A.~i.@!@#)@;@:(([#~>@])/&.>) ::0

```

## ungolfed

```
(?@# { ])@(#~ 2&([: */ ~:/\)"1)@(A.~ i.@!@#)@;@:(([ #~ >@])/&.>) ::0

```

Suggestions for improvement welcome.

Try it online!
> 3 votes

# Answer
# JavaScript, 112 bytes

First pass at this, more golfing to (hopefully) follow.

```
f=([i,...a],o=[])=>a.sort((x,y)=>(y[1]-x[1])*Math.random()-n*.5,n=--i[1],o.push(i[0]))+a?f(n?[...a,i]:a,o):n?0:o

```

Try it online
> 3 votes

# Answer
# JavaScript (ES6), 160 bytes

```
a=>(g=(a,m=[])=>a.map((v,n)=>v==m[0]||g(a.filter(_=>n--),[v,...m]))>[]?0:r=m)(a.reduce((p,[v,n])=>[...p,...Array(n).fill(v)],r=[]).sort(_=>Math.random()-.5))||r

```

Try it online!
> 2 votes

# Answer
# Charcoal, 38 bytes

```
ＷΦθ§κ¹«≔‽Φ∨Φι›⊗§κ¹ΣＥι§μ¹ι¬⁼κυυ§υ⁰⊞υ⊖⊟υ

```

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

```
ＷΦθ§κ¹«

```

Repeat while there is at least one non-zero count.

```
Φι›⊗§κ¹ΣＥι§μ¹

```

Find any count that makes up more than half the remainder.

```
∨...ι

```

If there wasn't one, then just take the non-zero counts filtered earlier.

```
Φ...¬⁼κυ

```

Filter out the string that was output last time.

```
≔‽∨...υ

```

Assign a random element from the first non-empty of the above two lists to the last output string. Note that if an impossible combination is entered, the program will crash at this point.

```
§υ⁰

```

Print the string.

```
⊞υ⊖⊟υ

```

Decrement its count.
> 2 votes

# Answer
# Ruby, 85 bytes

The brute force approach (thanks Jonah for the idea).

```
->l{l.flat_map{|a,b|[a]*b}.permutation.select{|p|r=0;p.all?{|a|a!=r&&r=a}}.sample||0}

```

Try it online!

# Ruby, ~~108 100~~ 96 bytes

Previously, the Bogosort approach

```
->l{w=[];l.map{|a,b|w+=[a]*b;b}.max*2>w.size+1?0:(w.shuffle!until(r='';w.all?{|a|a!=r&&r=a});w)}

```

Try it online!
> 2 votes

# Answer
# Rust 633 bytes

What makes this a little different than the others is that it started with the idea to rearrange the strings by simulating a physical system. Each string is first duplicated the appropriate number of times. Then each individual string is treated as a Particle in a space. Two particles with the same string value "repel" each other, while two particles with different values attract each other. For example if we begin with AAAAAAABBBBCC, the As will repeal each other, moving away from each other, allowing the Bs to move inbetween them. Over time this reaches a nice mixture of particles. After each iteration of 'particle movement', the program checks that no same-particles are adjacent, then stops and prints the state of the system, which is simply the list of strings in order, as they appear in the 1 dimensional space.

Now, when it comes to actually implementing that physical system, it started out as using the old fashiond PC demo/game technique, to store each particles position and velocity as numbers, then go through iterations to update position and velocity. At each iteration, we are adding velocity to position (movement), and adding acceleration to velocity (change in rate of movement), and calculating acceleration (finding the force on the particle). To simplify, the system doesn't calculate force on each particle based on all other particles - it only checks the particles immediately adjacent. There was also a 'damping' effect so that particles wouldn't accelerate too much and fly off to infinity (velocity is reduced by x percentage each step, for example).

Through the process of golfing, however, this whole thing was cut down and simplified drastically. Now, instead of two alike particles repelling each other, they simply 'teleport'. Different particles simply 'scoot' a wee bit to prevent stagnation in the system. For example if A is next to A it will teleport. If A is next to B it will only slightly shift. Then it checks if the conditions are met (no like particles adjacent) and prints the strings in order, based on their position in 1-d space. It is almost more like a sorting algorithm than a simulation - then again, one could see sorting algorithms as a form of simulated 'drifting' based on 'mass'. I digress.

Anyways, this is one of my first Rust programs so I gave up after several hours of golfing, although there might be opportunities there still. The parsing bit is difficult for me. It reads the input string from standard input. If desired, that could be replaced with "let mut s = "\[\[A,3\],\[B,2\]\]". But right now I do 'echo \[\[A,3\],\[B,2\]\] | cargo run' on the command line.

The calculation of stopping is a bit of a problem. How to detect if a valid state of the system will never be reached? The first plan was to detect if the 'current' state ever repeated an old state, for example if ACCC changes to CACC but then back to ACCC we know the program will never terminate, since it's only pseudo-random. It should then give up and print 0 if that happened. However this seemed like a huge amount of Rust code, so instead I just decided that if it goes through a high number of iterations, its probably stuck and will never reach a steady state, so it prints 0 and stops. How many? The number of particles squared.

Code:

```
extern crate regex;
struct P {s:String,x:i32,v:i32}
fn main() {
    let (mut i,mut j,mut p,mut s)=(0,0,Vec::new(),String::new());
    std::io::stdin().read_line(&mut s);
    for c in regex::Regex::new(r"([A-Z]+),(\d+)").unwrap().captures_iter(&s) {
        for _j in 0..c[2].parse().unwrap() {p.push(P{s:c[1].to_string(),x:i,v:0});i+=1;}
    }
    let l=p.len(); while i>1 {
        j+=1;i=1;p.sort_by_key(|k| k.x);
        for m in 0..l {
            let n=(m+1)%l;
            if p[m].s==p[n].s {p[m].v=p[m].x;if n!=0 {i=2}} else {p[m].v=1}
            p[m].x=(p[m].x+p[m].v)%l as i32;
        }
        if j>l*l{p.truncate(1);p[0].s="0".to_string();i=1}
    }
    for k in &p{print!("{}",k.s)};println!();
}

```
> 2 votes

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

```
l=>(a=[],g=(r,s)=>s.length?s.forEach((x,i)=>g([...r,x],s.filter((y,j)=>j-i))):a.push(r),g([],l.reduce(((a,x)=>[...a, ...(x[0]+' ').repeat(x[1]).split(' ')]),[]).filter(x=>x)),p=a.filter(a=>a.every((x,i)=>x!=a[i+1])),p[~~(Math.random()*p.length)]||0)

```

Try it online!
> 1 votes

# Answer
# Java (JDK 10), 191 bytes

```
S->N->{var l=new java.util.Stack();int i=0,j;for(var s:S)for(j=N[i++];j-->0;)l.add(s);for(;i>0;){i=0;java.util.Collections.shuffle(l);for(var s:S)if(s.join("",l).contains(s+s))i++;}return l;}

```

Try it online!

This never returns if there are no solutions.
> 1 votes

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


title: The Unique Padlock PIN List!

text:
# Question
Title: The Unique Padlock PIN List!
## Introduction

In a private chat, a friend of mine apparently recently stumbled across a security system which has the following two restrictions on its valid pins:

* Each digit must be unique (that is "1" may only appear once)
* The order of the digits doesn't matter ("1234"="4321")

So to illustrate how bad this padlock system is, let's actually enumerate all valid PINs!

## Input

Your input will consist of a single, positive integer, which denotes the length of the PIN.

## Output

Your output consists of a list of non-negative integers or strings\*, which enumerate all valid PINs of the given length.

\*More precisely something that a human can use to try all combinations if you would print it for them. This means set of sets of digits and arrays of arrays of digits are fine.

## Who wins?

This is so the shortest answer in bytes wins! Standard rules and loopholes apply.

## Corner Cases

* The output behaviour is undefined if an integer greater than 10 is input.
* The ordering of the digits within each output entry is undefined, as entries with a zero actually contain said zero, that is you may not strip "0123" to "123" but "1230", "1203" and "1023" are all valid as is "0123".

## Test Cases

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

2
[10,20,30,40,50,60,70,80,90,21,31,41,51,61,71,81,91,32,42,52,62,72,82,92,43,53,63,73,83,93,54,64,74,84,94,65,75,85,95,76,86,96,87,97,98]

3
[210,310,410,510,610,710,810,910,320,420,520,620,720,820,920,430,530,630,730,830,930,540,640,740,840,940,650,750,850,950,760,860,960,870,970,980,321,421,521,621,721,821,921,431,531,631,731,831,931,541,641,741,841,941,651,751,851,951,761,861,961,871,971,981,432,532,632,732,832,932,542,642,742,842,942,652,752,852,952,762,862,962,872,972,982,543,643,743,843,943,653,753,853,953,763,863,963,873,973,983,654,754,854,954,764,864,964,874,974,984,765,865,965,875,975,985,876,976,986,987]

4
[3210,4210,5210,6210,7210,8210,9210,4310,5310,6310,7310,8310,9310,5410,6410,7410,8410,9410,6510,7510,8510,9510,7610,8610,9610,8710,9710,9810,4320,5320,6320,7320,8320,9320,5420,6420,7420,8420,9420,6520,7520,8520,9520,7620,8620,9620,8720,9720,9820,5430,6430,7430,8430,9430,6530,7530,8530,9530,7630,8630,9630,8730,9730,9830,6540,7540,8540,9540,7640,8640,9640,8740,9740,9840,7650,8650,9650,8750,9750,9850,8760,9760,9860,9870,4321,5321,6321,7321,8321,9321,5421,6421,7421,8421,9421,6521,7521,8521,9521,7621,8621,9621,8721,9721,9821,5431,6431,7431,8431,9431,6531,7531,8531,9531,7631,8631,9631,8731,9731,9831,6541,7541,8541,9541,7641,8641,9641,8741,9741,9841,7651,8651,9651,8751,9751,9851,8761,9761,9861,9871,5432,6432,7432,8432,9432,6532,7532,8532,9532,7632,8632,9632,8732,9732,9832,6542,7542,8542,9542,7642,8642,9642,8742,9742,9842,7652,8652,9652,8752,9752,9852,8762,9762,9862,9872,6543,7543,8543,9543,7643,8643,9643,8743,9743,9843,7653,8653,9653,8753,9753,9853,8763,9763,9863,9873,7654,8654,9654,8754,9754,9854,8764,9764,9864,9874,8765,9765,9865,9875,9876]

```

# Answer
# Jelly, 4 bytes

```
ØDœc

```

Try it online!

# Explanation

```
ØDœc  Double-builtin; main link
  œc  Number of combinations of          of length
ØD                              [digits]
                                                   <right argument>

```

Behavior for `n > 10` is empty list.
> 7 votes

# Answer
# JavaScript (ES7), 89 bytes

Returns a list of lists of digits (as characters), or an empty list if **n \> 10**.

```
n=>[...2**29+'4'].reduce((a,x)=>[...a,...a.map(y=>[x,...y])],[[]]).filter(a=>a.length==n)

```

Try it online!

### How?

We first generate a list of all decimal digits as characters by computing **229 = 536870912**, adding the missing **'4'** and splitting:

```
[...2**29+'4'] → [ '5', '3', '6', '8', '7', '0', '9', '1', '2', '4' ]

```

We then compute the powerset:

```
.reduce(                                   ,[[]]) // starting with a[] holding an empty list
        (a,x)=>[                          ]       // for each decimal digit x:
                ...a,                             //   copy all previous entries in a[]
                     ...a.map(y=>        )        //   and duplicate each previous entry y
                                 [x,...y]         //   with x prepended at the beginning

```

Finally, we filter the results on their length:

```
.filter(a=>a.length==n)

```
> 6 votes

# Answer
# 05AB1E, 5 bytes

```
žhæsù

```

Try it online!

**Explanation**

```
   sù  # keep elements the length of the input
  æ    # from the powerset
žh     # of 0123456789

```
> 6 votes

# Answer
# Python 3, 57 bytes

```
lambda l:combinations(range(10),l)
from itertools import*

```

Try it online!

Finds all combinations of `0 .. 9` of length `l`.

Behavior for `n > 10` is empty list.
> 4 votes

# Answer
# Wolfram Language (Mathematica), 22 bytes

```
0~Range~9~Subsets~{#}&

```

Try it online!
> 4 votes

# Answer
# Python 2, 62 bytes

```
f=lambda n:{d+s for d in`5**19`*n for s in f(n-1)if d>s}or{''}

```

Returns a set of strings.

Try it online!
> 4 votes

# Answer
# , 17 bytes

```
combn(0:9,scan())

```

Try it online!

Errors for input greater than `10`.

Returns a `matrix` where each column is a PIN.
> 3 votes

# Answer
# Pyth, 4 bytes

```
.cUT

```

Try it here

### Explanation

```
.cUT
  UT     [0, 1, ..., 9].
.c  Q    All (implicit input)-element subsets.

```
> 3 votes

# Answer
# Ruby, 30 bytes

```
->n{[*[*0..9].combination(n)]}

```

Try it online!
> 2 votes

# Answer
# MATL, 6 bytes

```
4Y2wXN

```

Try it online!

Returns nothing (empty array) for `k>10`.

```
          % implicit input k
4Y2       % push '0':'9'
   w      % swap top two elements of stack
    XN    % nchoosek, select all k-combinations of '0':'9' as a char array
          % implicit output

```
> 2 votes

# Answer
# Haskell, ~~56~~ 50 bytes

-6 bytes thanks to Hat Wizard.

```
(10!)
_!0=[[]]
w!n=[0..w-1]>>=(map.(:)<*>(!(n-1)))

```

Try it online!
> 2 votes

# Answer
# Java (JDK 10), 105 bytes

```
n->{var s="";for(int i=1024,j;i-->0;s+=" ")for(j=10;n.bitCount(i)==n&j-->0;)s+=(1<<j&i)>0?j:"";return s;}

```

Try it online!
> 2 votes

# Answer
# Haskell, 47 bytes

```
f 0=[[]]
f n=[a:x|x<-f$n-1,a<-[0..9],all(/=a)x]

```

Try it online!

## Explanation

When the number of digits is zero there is only one combination, that is the empty one:

```
f 0=[[]]

```

When the number of digits is `n` and `n/=0` the combinations are all the ways to add digits to combinations from `f$n-1` such that no digit is addded to a combination that already contains it.

```
f n=[a:x|x<-f$n-1,a<-[0..9],all(/=a)x]

```
> 2 votes

# Answer
# Gaia,  ~~4~~  3 bytes

```
₸…K

```

Try it online!

It's been a while since I posted an answer in Gaia! *Thanks to Mr. Xcoder for saving a byte!*

```
      % implicit input n
₸     % push 10
 …    % pop 10, push 0..9
  K   % all subsets of size n
      % print top of stack implicitly

```
> 2 votes

# Answer
# Retina, ~~51~~ 36 bytes

```
.+
10*
"$+"{%`^.
*_$&
L$v`_+
$.%`$%'

```

Try it online! Outputs nothing for `n>10`. Explanation:

```
.+
10*

```

Replace the input with 10 `_`s.

```
"$+"{

```

Repeat the rest of the program `n` times.

```
%`^.
*_$&

```

Prefix each number with `_` repeated according to its first digit.

```
L$v`_+

```

Match all `_`s, but include all of the following `_`s in the match too, for which we need to enable overlapping matches.

```
$.%`$%'

```

For each `_` found, prefix the number of `_`s to its left to the number.

This is a bit tricky so perhaps an actual case would be better. Let's suppose that we've already run the loop twice, so that all 2-digit PINs have been generated, and we're currently working through them to create 3-digit PINs. We'll look at what happens to `36`: The first digit is `3`, so three `_`s are prefixed, to make `___36`. This then creates the following matches, marked here with ``'`s:

```
Match   $%` $.%`
`___'36     0
_`__'36 _   1
__`_'36 __  2

```

`$%'` evalutes to `36` in all three cases, resulting in the 3-digit PINs `036`, `136` and `236`.

If we were then to go on to create 4-digit PINs, then `036` would not have any `_`s prefixed, and therefore would result in no matches at all in the final output.
> 2 votes

# Answer
# Proton, 43 bytes

```
(0..9)&__import__("itertools").combinations

```

Try it online!

Proton finally outgolfs Python :D I thought `(import itertools)` would return the value but apparently I failed at that. Also importing `*` afterwards doesn't work because it's not in a lambda, it's a top-level expression.
> 1 votes

# Answer
# Japt, 5 bytes

Outputs an array of digit arrays. Outputs *all* combinations if input is `0` or an empty array if input is `<0` or `>10`.

```
Ao àU

```

Try it

---

## Explanation

```
          :Implicit input of integer U
A         :10
 o        :Range [0,10)
   àU     :Combinations of length U

```
> 1 votes

# Answer
# Stax, 4 bytes

```
Vd,S

```

Try it online!

`Vd` is `"0123456789"`. `,` pushes the input to the main stack. `S` gets combinations of the specified size.

In the tio link, `m` is used in the footer to print each output.
> 1 votes

# Answer
# Standard ML, ~~124~~ ~~122~~ 121 bytes

```
open List;fun f(s:: &)m=(if exists(fn x=>x=m)s then[]else[m::s])@f&m|f&m= &
fun!0=[[]]| !n=concat(tabulate(10,f(!(n-1))))

```

Try it online! Example usage: `!2` yields `[[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],[0,7],[0,8],[0,9],[1,0],[1,2],[1,3], ...]`.

**Ungolfed:**

```
open List;

(* int list list -> int -> int list list *)
fun f (s::r) m =
    if exists (fn x => x=m) s
    then f r m
    else (m::s) :: f r m
  | f [] m = []

(* int -> int list list *)
fun g 0 = [[]]
  | g n = concat(tabulate(10, f(g(n-1))))

```

---

**Some alternatives:**

### ~~125~~ 123 bytes

```
fun f(s:: &)m=(if List.exists(fn x=>x=m)s then[]else[m::s])@f&m|f&m= &
fun!m 0=[[]]| !10n=[]| !m n=f(!0(n-1))m@ !(m+1)n;!0;

```

Try it online! Defines an anonymous function which is bound to `it`.

### ~~127~~ 124 bytes

```
fun!0=[[]]| !n=let fun f(s:: &)m=(if List.exists(fn x=>x=m)s then[]else[m::s])@f&m|f&9=[]|f&m=f(!(n-1))(m+1)in f(!(n-1))0end

```

Try it online!
> 1 votes

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

```
f=(i,b='',k=10)=>k--?f(i-1,k+b,k)+f(i,b,k):i?'':b+`,`

```

Try it online!
> 1 votes

# Answer
# Oracle 18 SQL, 169 bytes

Not a golfing language but:

```
WITH t(v)AS(SELECT*FROM SYS.ODCINUMBERLIST(0,1,2,3,4,5,6,7,8,9)),n(a,b,c)AS(SELECT a,-1,''FROM i UNION ALL SELECT a-1,v,v||c FROM n,t WHERE v>b)SELECT c FROM n WHERE a=0

```

Expected the input to be in a table `i` with column `a`:

```
CREATE TABLE i (a INT);
INSERT INTO i VALUES ( 3 );

```

Try it online at Oracle Live SQL (a free login is required then copy-paste the solution into a worksheet) or SQLFiddle (no login but requires +7 bytes to work on the lower Oracle version).
> 1 votes

# Answer
# CJam, ~~13~~ 11 bytes

```
{Ae!f<:$_|}

```

Try it online!

Technically doesn't run on tio.run, since heap space runs out. However, it works properly for up to 9 digit keypads, and should run just fine with more RAM.

Saved 2 bytes thanks to Dennis
> 1 votes

# Answer
# Bash, ~~113~~ 99 bytes

```
p()(r $1 0 $[10-$1])
r()for i in `seq $2 $3`;{ (($1>1))&&r $[$1-1] $[i+1] $[$3+1] $4$i||echo $4$i;}

```

Try it online!
> 0 votes

# Answer
## JavaScript (Firefox 30-57), 67 bytes

```
n=>n?[for(x of f(n-1))for(y of Array(x?+x[0]:10).keys())y+x]:['']

```

Port of my Retina answer, but works for `n=0` too (returning a list of an empty string, as distinct from an empty list for `n>10`).
> 0 votes

# Answer
# Charcoal, 21 bytes

```
⊞υωＦχ≔⁺υＥυ⁺κＩιυΦυ⁼θＬι

```

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

```
⊞υω

```

Push the empty string to the predefined list.

```
Ｆχ

```

Loop over each digit.

```
Ｅυ⁺κＩι

```

Append the digit to every string in the list.

```
≔⁺υ...υ

```

Append the result to the original list.

```
Φυ⁼θＬι

```

Print all strings with the correct number of digits.
> 0 votes

# Answer
# Perl 6, 20 bytes

```
{combinations 10,$_}

```

Try it online!

This is exactly what `combinations` (as a subroutine, or `.combinations` on a list) is for.

https://docs.perl6.org/routine/combinations
> 0 votes

# Answer
# , 32 bytes

.. frustratingly longer than Mathematica and  `f=:{[:(#@>"0]/.])[:<@I.@#:@i.2^]` TIO
> 0 votes

---
Tags: code-golf, combinatorics
---


title: Golfing Chain (Cops' Thread)

text:
# Question
Title: Golfing Chain (Cops' Thread)
This is a Cops and Robbers challenge. For the Robbers' thread, go here.

The Cops have three tasks.
1) Pick a sequence from the OEIS.

2) Pick a language (this is suggested to be a golflang, but doesn't have to be) that, when given input `n`, outputs `A(n)` (where `A(n)` is the sequence chosen) using all usual rules.
Call this language **LA** and code **CA**.
For example, *Jelly* and *Jelly\_code*.

3) Then, pick a different language (this is suggested to be a non-golflang, but doesn't have to be) and write code that takes no input and outputs code **CA**, again following all usual rules. (Note: this can be obfuscated code and doesn't necessarily need to be golfed, but the longer this code is the easier it will be for the robbers to crack your submission.)
Call this language **LB** and code **CB**.
For example, *Python* and *Python\_code*.

**The Cop's submission to this challenge** is the sequence (specified whether 0- or 1-indexed), the name of the two languages **LA** and **LB** (and which one solves which part), and the byte-count of **CB** only. Keep the actual code of both parts, and the length of **CA**, secret.

For the Cop, links to documentation for **LA** and **LB**, or an interpreter (or a TIO link, since that includes both), are appreciated but not required.

The Robber's challenge is to select a Cops' entry and write code **CC** in the same **LB** language that outputs *some* code in the same **LA** language that solves the original OEIS task. The length of **CC** can be no longer than the length of **CB** as revealed by the cop (though may be shorter). Note: The code produced by **CC** does *not* have to match **CA**.

For our example, this means that the Robber has to write *Python* code that outputs *Jelly* code that solves the original OEIS sequence, and that *Python* code has to be no longer than the length revealed by the Cop.

### Winning conditions

Answers that have not been cracked in a week can have their solutions revealed, at which point they are considered *Safe*. Note that if you don't reveal your solution after a week, it can still be cracked. The Cop with the shortest *Safe* answer wins.

# Answer
> 3 votes
# OEIS A000041, cracked by ETHproductions

Let's try it the other way around: golflang generates non-golflang.

> ***a(n)** = number of partitions of **n** (the partition numbers).*

* **a(n)** (0-indexed) is returned by a **JavaScript** function (ES6)
* The program that outputs the JS function is written in **Jelly**
* The length of the Jelly program is **35 bytes**

## Intended solution

> Jelly: `“¦ṚoIwƭ- ḊFæSḂ¥¶Ẉ|ḊJƓƝʋnrB⁾’b28+40Ọ`
> which outputs
> JS: `C=(A,B=A)=>A<0?0:A?B?C(A,B-1)+C(A-B,B):0:1`

# Answer
> 2 votes
# OEIS 000035, cracked by betseg

The problem is solved in **Proton**.
The Proton code is output by **Python**.
The length of the Python program is **13 bytes**.

Really easy one for starters (if you know Proton :D). Zero-indexed.

# Intended Solution

> Python: `print("(2%)")`
> Proton: `(2%)`
> Though I decided to let `n=>n%2` be short enough because dyadic/monadic function shortcuts are not documented.

# Answer
> 2 votes
# OEIS A048272, cracked by DJMcMayhem

> Number of odd divisors of **n** minus number of even divisors of **n** (1-indexed).

* The program that outputs **a(n)** is written in **05AB1E**.
* The program that outputs the 05AB1E program is written in **Brain-Flak** \+ the `-A` flag.
* The length of the Brain-Flak program is **198 bytes** (the byte count does *not* include the flag).

Note that I could probably easily golf the Brain-Flak program by using stack-manipluation tricks and other kolmogorov-complexity tricks I am aware of, but I wanted to keep this simple as my first submission. ~~Good luck, robbers!~~

### What I had in mind

> 05AB1E: `ÑÈD<)O(O`
> Brain-Flak: `(((((((((((()()()){}){}){({}[()])}{}())[((((()()()){}){}())){}{}])((((()()()){}){}())){}{})[((((()()()){}){})()){}{}])(((()()()){})){}{}())(()()()()){})(((((()()()()){}){}){}()){}){})((()()())){}{})`

# Answer
> 2 votes
# OEIS A000034 (cracked by H.PWiz)

> **1, 2, 1, 2, 1, 2, 1, 2, …**
>
> *Period 2: repeat \[1, 2\]; a(n) = 1 + (n mod 2).*

**a(n)** is the output of a **Haskell** answer, which is the output of a 32-byte **Malbolge** answer.

# Answer
> 1 votes
# OEIS A000668, cracked by Lynn

> Mersenne primes (of form **2p-1** where **p** is a prime)

* **a(n)** is outputted by a **Jelly** full program.
* **n** is 1-indexed.
* The Jelly program is printed by a **Triangularity** program, whose length is **38 bytes**.

Different strategy: solve the sequence in a golflang and output the program in an esolang.

### Intended solution

>

# Answer
> 1 votes
# OEIS A055642, cracked by Lynn

> Number of digits in decimal expansion of n

This is probably too easy, but it took me a while so I hope someone out there will be just as disappointed as I was when I finally figured it out :D

* The program that writes out **a(n)** is written in **05AB1E**
* The program that prints the 05AB1E program is written in **TeX**
* The TeX program is **6 bytes** long

What I had in mind:

> `Sg` as 05AB1E code
> `Sg\bye` as TeX code

---
Tags: code-golf, sequence, cops-and-robbers
---


title: Golfing Chain (Robbers' Thread)

text:
# Question
Title: Golfing Chain (Robbers' Thread)
This is a Cops and Robbers challenge. For the Cops' thread, go here.

The Cops have three tasks.
1) Pick a sequence from the OEIS.

2) Pick a language (this is suggested to be a golflang, but doesn't have to be) that, when given input `n`, outputs `A(n)` (where `A(n)` is the sequence chosen) using all usual rules.
Call this language **LA** and code **CA**.
For example, *Jelly* and *Jelly\_code*.

3) Then, pick a different language (this is suggested to be a non-golflang, but doesn't have to be) and write code that takes no input and outputs code **CA**, again following all usual rules. (Note: this can be obfuscated code and doesn't necessarily need to be golfed, but the longer this code is the easier it will be for the robbers to crack your submission.)
Call this language **LB** and code **CB**.
For example, *Python* and *Python\_code*.

The Cop's submission to this challenge is the sequence (specified whether 0- or 1-indexed), the name of the two languages **LA** and **LB** (and which one solves which part), and the byte-count of **CB** only. Keep the actual code of both parts, and the length of **CA**, secret.

**The Robber's challenge** is to select a Cops' entry and write code **CC** in the same **LB** language that outputs *some* code in the same **LA** language that solves the original OEIS task. The length of **CC** can be no longer than the length of **CB** as revealed by the cop (though may be shorter). Note: The code produced by **CC** does *not* have to match **CA**.

For our example, this means that the Robber has to write *Python* code that outputs *Jelly* code that solves the original OEIS sequence, and that *Python* code has to be no longer than the length revealed by the Cop.

### Winning conditions

The Robber with the most cracked solutions wins.

# Answer
> 6 votes
# Brain-Flak, 90 bytes by Mr. Xcoder

```
((((((((((()()()){}){}){({}[()])}{}())[(((()()()){})){}{}()]))){}{}()()())([][][]){})[][])

```

Try it online!

This outputs:

```
ÑÉ·<O

```

First 05AB1E answer!

## How does it work?

Let's say we have 24 as input.

```
Ñ       # Divisors.
        # Stack: [1, 2, 3, 4, 6, 8, 12, 24]
 É      # Odd?
        # Stack: [1, 0, 1, 0, 0, 0, 0, 0]
  ·     # Double
        # Stack: [2, 0, 2, 0, 0, 0, 0, 0]
   <    # Decrement
        # Stack: [1, -1, 1, -1, -1, -1, -1, -1]
    O   # Sum
        # Stack: -4

```

The brain-flak code mostly just uses tricks to push large numbers in few bytes. It was very convenient (and unintentional) that the ASCII values are mostly increasing:

```
209
201
183
60
79

```

It's also nice that `60 * 3 ~=~ 183` so tripling it and adding a few can save a ton of bytes.

```
((((((

    # Push 79
    ((((()()()){}){}){({}[()])}{}())
    # Minus 19 (60)

    [(((()()()){})){}{}()])
    # Push that two extra times
    ))

    # Push that ^ (60) Plus the two extras popped (60 + 120 == 180)...
    {}{}
    # + 3 (183)
    ()()())

    # Plus stack-height * 3 * 2 == 3 * 3 * 2 == 18 (201)
    ([][][]){})

    # Plus stack-height * 2 == 4 * 2 == 8 (209)
    [][])

```

# Answer
> 2 votes
## Jelly, 34 bytes by Arnauld

Managed a byte shorter than his solution!

```
“`Ḃ|⁴ʂⱮdÐỌK_ƬƬfıæh’ṃ“fnk1()+-,=>?:

```

Try it online!

This outputs the JS function

```
f=(n,k=1)=>n>=k?f(n-k,k)+f(n,k+1):1>n

```

which computes A000041 (0-indexed; `nn(0)` returns `true` in place of `1`).

# Answer
> 2 votes
# TeX by Simon Klaver

```
g\bye

```

prints `g`, which computes the length of the input in 05AB1E.

# Answer
> 2 votes
# Malbolge, 32 bytes by Lynn

```
('%$:?>7[5|981Uv.uQrq)Mnmm$Hj4ED

```

Try it online!

That prints the following haskell function:

```
gcd 2

```

Try it online!

I used this online tool to generate the Malbolge

# Answer
> 1 votes
## Python, 13 bytes by HyperNeutrino

```
print"n=>n%2"

```

Try it online!

# Answer
> 1 votes
# Triangularity by Mr. Xcoder, 36 bytes

```
... ...
..  "..
.aẒ;Ba.
1ÇP$#Ṁ"

```

Try it online!

Prints Jelly code:

```
..
.aẒ;Ba.
1ÇP$#Ṁ

```

Try the Jelly code online! It's quite slow.

---
Tags: code-golf, sequence, cops-and-robbers
---


title: Rational Counting Function

text:
# Question
Title: Rational Counting Function
Create a function that takes a natural number (starting from 0 inclusive), and returns a pair of positive integers, which are the numerator and denominator respectively. Use the diagonal traversal. Previous-counted numbers must be skipped. (you can memorize the set of skipped values)

Diagram:

Red are skipped values

Values:

* f(0) = 1, 1
* f(1) = 2, 1
* f(2) = 1, 2
* f(3) = 1, 3
* f(4) = 3, 1 (notice the skip)
* f(5) = 4, 1
* f(6) = 3, 2
* f(7) = 2, 3
* f(8) = 1, 4
* f(9) = 1, 5
* f(10) = 5, 1 (notice the skip)

You may use the Rational data structure and their operations if they exist. Shortest code wins.

# Answer
## J, ~~41~~ 36 characters

Takes an integers and returns a vector comprising two integers. My first solution that is neither entirely tacit nor entirely explicit.

```
{3 :'~.;<`(<@|.)/.(,%+.)"0/~1+i.1+y'

```

Here is the solution with spaces inserted where appropriate:

```
{ 3 : '~. ; <`(<@|.)/. (, % +.)"0/~ 1 + i. 1 + y'

```

An explanation:

1. `x (, % +.) y`–a vector of length 2 representing the fraction with numerator `x` and denominator `y` reduced to the smallest denominator
2. `1 + i. 1 + y`–a vector of integers from `1` to `y + 1`
3. `(, % +.)"0/~ 1 + i. 1 + y`–a matrix of all reduced fractions with unreduced denominator and numerator in the range from `1` to `y + 1`.
4. `<`(<@|.)/. y`–an array of the oblique diagonals of matrix `y`, each other diagonal flipped
5. `~. ; y`–an array of diagonals collapsed into a vector of elements with duplicates removed
6. `x { y`–the item at position `x` in `y`
7. `(u v) y`–the same as `y u v y`. In this particular use case, `u` is `{` and `v` is `3 : '~. ; <`(<@|.)/. (, % +.)"0/~ 1 + i. 1 + y'`
> 4 votes

# Answer
## Haskell, 78 characters

```
q(r,f)=[(r-b,b)|b<-f[1..r-1],r`gcd`b==1]
d=reverse:id:d
f=((zip[2..]d>>=q)!!)

```

Sample run:

```
> map f [0..10]
[(1,1),(2,1),(1,2),(1,3),(3,1),(4,1),(3,2),(2,3),(1,4),(1,5),(5,1)]
> f 100
(17,1)
> f 1000
(3,55)

```

---

* Edit: (100 → 87) silly me, just testing the gcd is enough!
* Edit: (87 → 85) clever trick with `cycle` and functions to alternate row order
* Edit: (85 → 82) replace `cycle` with the hand-built infinite list `d`
* Edit: (82 → 78) applied `gcd` identity as suggested by Matías
> 8 votes

# Answer
## Python, 144 chars

```
def F(i):
 r,d,z=[1],1,[]
 while z[:i]==z:z+=[(x,y)for x,y in zip(r[::d],r[::-d])if all(x%j+y%j for j in r[1:])];d=-d;r+=[r[-1]+1]
 return z[i]

```
> 3 votes

# Answer
## Ruby 1.9, 109 106

```
F=->n{x=y=d=1
e=0
n.times{(x+=d).gcd(y+=e)>1&&redo
x<2?d<0?d=0:(d,e=1,-1):y<2?e<0?e=0:(d,e=-1,1):0}
[x,y]}

```
> 2 votes

# Answer
# OCaml + Batteries, 182 168 characters

This is what would be natural in Haskell but is only barely possible in OCaml:

```
open LazyList
let rec r(i,j)=lazy(let a,b=if(i+j)mod 2=0then i,j else j,i in
Cons((a,b),filter(fun(c,d)->a*d<>c*b)(r(if j=1 then 1,i+1else i+1,j-1))))
let f=nth(r(1,1))

```

*Edit:* The diagonal is unnecessary
> 2 votes

# Answer
# Perl 6, 75 bytes

```
{(({|(1…($+=2)…1)}…*)Z/(1,{|(1…(($||=1)+=2)…1)}…*)).unique[$_]}

```

Test it

This basically generates the entire sequence of rational values, only stopping once the indexed value is generated.

(Based on my golf to another challenge.)

## Expanded:

```
{  # bare block lambda with implicit parameter $_

  (
      ( # sequence of numerators

        {
          |( # slip into outer sequence (flatten)

            1      # start at one
            …
            (
              $    # state variable
              += 2 # increment it by two each time this block is called
            )
            …
            1      # finish at one
          )

        }
        … * # never stop generating values
      )

    Z/   # zip using &infix:« /  » (generates Rats)

      ( # sequence of denominators

        1,  # start with an extra one

        {
          |( # slip into outer sequence (flatten)

            1
            …
            (
              ( $ ||= 1 ) # state variable that starts with 1 (rather than 0)
              += 2        # increment it by two each time this is called
            )
            …
            1
          )
        }
        … * # never stop generating values
      )

  ).unique                # get only the unique values
  .[ $_ ]                 # index into the sequence
}

```

---

`({1…($+=2)…1}…*)` generates the infinite sequence of numerators (`|(…)` is used above to flatten)

```
(1 2 1)
(1 2 3 4 3 2 1)
(1 2 3 4 5 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1)
…

```

`(1,{1…(($||=1)+=2)…1}…*)` generates the infinite sequence of denominators

```
1
(1 2 3 2 1)
(1 2 3 4 5 4 3 2 1)
(1 2 3 4 5 6 7 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1)
(1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1)
…

```
> 0 votes

---
Tags: code-golf, rational-numbers
---


title: Block partition a string

text:
# Question
Title: Block partition a string
Inspiration.

Consider a list `l`, consisting of numbers. Define a block operation at index `i` on the list `l` to be the act of moving 3 consecutive elements starting from `i` in `l` to the end.

Example:

```
l, i (1-indexing) -> l (after applying block operation at index i)
[1,2,3,4,5], 1 -> [4,5,1,2,3]
[1,2,3,4,5,6,7], 3 -> [1,2,6,7,3,4,5]

```

Given a list consisting of only 0 and 1, your challenge is to partition it so that zeros are at the front, and ones are at the back, using only block operations. Output should be the indices in the order they are applied on the list.

Because this is impossible for the list `[1,0,1,0]`, the list length is guaranteed to be at least 5.

# Test cases (1-indexing)

(there are other valid outputs)

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

```

Use this script to generate more test cases. (only input. The `rplc ' ';','` part is used to **r**e**pl**a**c**e spaces with commas in the output)

# Winning criteria

is the main winning criteria, and is the tie-breaker. In particular:

* The solution with the shortest output length (least number of block operations) with the test case (`n_elem` = 500, `random_seed` = {secret value}) wins. You should be able to run your solution to completion with the test case (`n_elem` = 500, `random_seed` = 123456).
* In case of ties, the solution that can handles the largest power-of-2 value of `n_elem` with `random_seed` = {secret value} within 10 seconds (for me) wins.
* In case of ties, the solution that takes less time on that test case wins.

# Answer
> 7 votes
# Python 3, (0.397 n + 3.58) steps

1000-point polynomial regression by `numpy.polyfit`.

---

* Number of steps for version 1: 0.0546 n² + 2.80 n - 221
* Number of steps for version 2: 0.0235 n² + 0.965 n - 74
* Number of steps for version 3: 0.00965 n² + 2.35 n - 111
* Number of steps for version 4: 1.08 n - 36.3
* Number of steps for version 5: 0.397 n + 3.58

---

* Secret test case score for version 1: 14468
* Secret test case score for version 2: 5349
* Secret test case score for version 3: 4143
* Secret test case score for version 4: 450
* Secret test case score for version 5: 205

---

```
def partite(L):
	endgame5 = [9,9,1,9,0,0,1,9,
		0,1,0,1,0,1,1,9,
		0,0,1,0,0,0,1,0,
		0,0,0,1,0,0,0,9]
	endgame6 = [9,9,2,9,1,1,2,9,0,2,0,0,1,2,2,9,
		0,1,2,1,0,1,2,1,0,1,0,2,1,1,0,9,
		0,0,1,0,1,0,1,1,0,0,0,0,1,1,1,1,
		0,0,2,2,0,0,2,2,0,0,0,0,0,0,0,9]
	endgame = [9,9,3,9,2,2,3,9,1,0,3,0,2,0,3,9,0,1,3,3,2,2,3,0,1,0,1,0,2,1,0,9,
		0,0,2,1,0,0,2,2,1,0,1,2,0,0,0,2,0,1,3,3,3,3,3,0,1,1,1,1,1,3,0,9,
		0,0,0,0,1,0,1,1,1,0,3,0,1,0,1,0,0,1,0,0,1,1,0,0,1,0,0,0,2,0,1,0,
		0,0,2,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,3,0,3,0,3,0,3,0,2,3,3,0,0,9]
	offset = 1
	steps = []
	def update(L,steps,ind):
		steps.append(offset + ind)
		if 0 <= ind and ind+3 < len(L):
			return (steps,L[:ind]+L[ind+3:]+L[ind:ind+3])
		else:
			print(offset,ind,L)
			raise
	if len(L) == 5:
		while endgame5[L[0]*16+L[1]*8+L[2]*4+L[3]*2+L[4]] != 9:
			steps, L = update(L,steps,endgame5[L[0]*16+L[1]*8+L[2]*4+L[3]*2+L[4]])
		return steps
	if len(L) == 6:
		while endgame6[L[0]*32+L[1]*16+L[2]*8+L[3]*4+L[4]*2+L[5]] != 9:
			steps, L = update(L,steps,endgame6[L[0]*32+L[1]*16+L[2]*8+L[3]*4+L[4]*2+L[5]])
		return steps
	if 1 not in L:
		return []
	while len(L) > 7 and 0 in L:
		wf_check = len(L)
		while L[0] != 0:
			pos = [-1]
			wf_check2 = -1
			while True:
				i = pos[-1]+1
				while i < len(L):
					if L[i] == 0:
						pos.append(i)
						i += 1
					else:
						i += 3
				assert len(pos) > wf_check2
				wf_check2 = len(pos)
				space = (pos[-1]-len(L)+1)%3
				ind = -1
				tail = pos.pop()
				i = len(L)-1
				while i >= 0:
					if tail == i:
						while tail == i:
							i -= 1
							tail = pos.pop() if pos else -1
						i -= 2
					elif i < len(L)-3 and L[i+space] == 0:
						ind = i
						break
					else:
						i -= 1
				if ind == -1:
					break
				steps, L = update(L, steps, ind)
				pos = pos or [-1]
			if L[0] == 0:
				break
			pos = [-1]
			while L[0] != 0:
				pos = [-1]
				found = False
				for i in range(1,len(L)):
					if L[i] == 0:
						if i%3 == (pos[-1]+1)%3:
							pos.append(i)
						else:
							found = found or i
				if found > len(L)-4:
					found = False
				if not found:
					break
				triple = []
				for i in range(1,len(L)-1):
					if L[i-1] == 1 and L[i] == 1 and L[i+1] == 1:
						triple.append(i)
					if len(triple) > 3:
						break
				space = (pos[-1]-len(L)+1)%3
				if space == 0:
					if found >= 2 and found-2 not in pos and found-1 not in pos:
						# ... _ 1 _ [0] 0 ...
						if found-2 in triple:
							triple.remove(found-2)
						if found-3 in triple:
							triple.remove(found-3)
						if L[-1] == 1:
							steps, L = update(L, steps, found-2)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
						elif triple:
							steps, L = update(L, steps, found-2)
							if found < triple[0]:
								triple[0] -= 3
							steps, L = update(L, steps, triple[0]-1)
							steps, L = update(L, steps, len(L)-4)
						else:
							break
						assert L[-3] == 0
					elif found >= 1 and found-1 not in pos and found+1 not in pos:
						# ... _ 1 [0] _ 0 ...
						if found-2 in triple:
							triple.remove(found-2)
						if L[-2] == 1 and L[-1] == 1:
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-5)
							steps, L = update(L, steps, len(L)-5)
						elif triple:
							steps, L = update(L, steps, found-1)
							if found < triple[0]:
								triple[0] -= 3
							steps, L = update(L, steps, triple[0]-1)
							steps, L = update(L, steps, len(L)-5)
						elif L[-1] == 1:
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
						else:
							break
						assert L[-3] == 0
					else:
						break
				elif space == 1:
					# ... 1 1 [0] 0 ...
					if found >= 2 and found-2 not in pos and found-1 not in pos:
						if found-2 in triple:
							triple.remove(found-2)
						if found-3 in triple:
							triple.remove(found-3)
						if triple:
							steps, L = update(L, steps, found-2)
							if found < triple[0]:
								triple[0] -= 3
							steps, L = update(L, steps, triple[0]-1)
							steps, L = update(L, steps, len(L)-5)
						elif L[-2] == 1 and L[-1] == 1:
							steps, L = update(L, steps, found-2)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-5)
						else:
							break
						assert L[-2] == 0
					else:
						break
				else:
					if found+1 not in pos and found+2 not in pos:
						# ... 0 [0] _ 1 _ ...
						if found+2 in triple:
							triple.remove(found+2)
						if found+3 in triple:
							triple.remove(found+3)
						if L[-2] == 1 and L[-1] == 1:
							steps, L = update(L, steps, found)
							steps, L = update(L, steps, len(L)-5)
						elif L[-1] == 1:
							steps, L = update(L, steps, found)
							steps, L = update(L, steps, len(L)-4)
							steps, L = update(L, steps, len(L)-4)
						elif triple:
							steps, L = update(L, steps, triple[0]-1)
							if triple[0] < found:
								found -= 3
							steps, L = update(L, steps, found)
							steps, L = update(L, steps, len(L)-5)
						else:
							break
						assert L[-1] == 0
					elif found >= 1 and found-1 not in pos and found+1 not in pos:
						# ... 0 _ [0] 1 _ ...
						if found+2 in triple:
							triple.remove(found+2)
						if L[-1] == 1:
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-4)
						elif triple:
							steps, L = update(L, steps, triple[0]-1)
							if triple[0] < found:
								found -= 3
							steps, L = update(L, steps, found-1)
							steps, L = update(L, steps, len(L)-4)
						else:
							break
						assert L[-1] == 0
					else:
						break
			if L[0] == 0:
				break
			if 0 in L[::3]:
				assert L[::3].index(0) < wf_check
				wf_check = L[::3].index(0)
			steps, L = update(L, steps, 0)
		assert L[0] == 0
		offset += L.index(1)
		del L[:L.index(1)]
		continue
	if 0 in L:
		offset -= 7-len(L)
		L = [0]*(7-len(L))+L
		assert(len(L) == 7)
		while endgame[L[0]*64+L[1]*32+L[2]*16+L[3]*8+L[4]*4+L[5]*2+L[6]] != 9:
			steps, L = update(L,steps,endgame[L[0]*64+L[1]*32+L[2]*16+L[3]*8+L[4]*4+L[5]*2+L[6]])
	return steps

```

Try it online!

# Answer
> 4 votes
# Python 3, ~179 steps for n=500 (on average)

A heuristic greedy approach. Kinda slow but still works. Uses an optimal solver for small sizes.

```
def incomplete_groups(l):
    r = 0
    ones = 0
    for x in l:
        if x == "1":
            ones += 1
        else:
            if ones % 3:
                r += 1
            ones = 0
    # Ones at the end don't count as an incomplete group.

    return r

def move(l, i):
    return l[:i] + l[i+3:] + l[i:i+3]

def best_pos(l, hist):
    r = []
    cleanup = incomplete_groups(l) == 0

    candidates = []
    for i in range(len(l) - 3):
        block = l[i:i+3]
        if block == "111" and cleanup:
            return i
        elif block == "111":
            continue

        new = move(l, i)
        bad_start = i < 3 and "10" in l[:3]
        candidates.append((new not in hist, -incomplete_groups(new), bad_start, block != "000", i))

    candidates.sort(reverse=True)
    return candidates[0][-1]

def done(l):
    return list(l) == sorted(l)

class IDAStar:
    def __init__(self, h, neighbours):
        """ Iterative-deepening A* search.

        h(n) is the heuristic that gives the cost between node n and the goal node. It must be admissable, meaning that h(n) MUST NEVER OVERSTIMATE the true cost. Underestimating is fine.

        neighbours(n) is an iterable giving a pair (cost, node, descr) for each node neighbouring n
        IN ASCENDING ORDER OF COST. descr is not used in the computation but can be used to
        efficiently store information about the path edges (e.g. up/left/right/down for grids).
        """

        self.h = h
        self.neighbours = neighbours
        self.FOUND = object()

    def solve(self, root, is_goal, max_cost=None):
        """ Returns the shortest path between the root and a given goal, as well as the total cost.
        If the cost exceeds a given max_cost, the function returns None. If you do not give a
        maximum cost the solver will never return for unsolvable instances."""

        self.is_goal = is_goal
        self.path = [root]
        self.is_in_path = {root}
        self.path_descrs = []
        self.nodes_evaluated = 0

        bound = self.h(root)

        while True:
            t = self._search(0, bound)
            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated
            if t is None: return None
            bound = t

    def _search(self, g, bound):
        self.nodes_evaluated += 1

        node = self.path[-1]
        f = g + self.h(node)
        if f > bound: return f
        if self.is_goal(node): return self.FOUND

        m = None # Lower bound on cost.
        for cost, n, descr in self.neighbours(node):
            if n in self.is_in_path: continue

            self.path.append(n)
            self.is_in_path.add(n)
            self.path_descrs.append(descr)
            t = self._search(g + cost, bound)

            if t == self.FOUND: return self.FOUND
            if m is None or (t is not None and t < m): m = t

            self.path.pop()
            self.path_descrs.pop()
            self.is_in_path.remove(n)

        return m

def h(l):
    """Number of groups of 1 with length <= 3 that come before a zero."""
    h = 0
    num_ones = 0
    complete_groups = 0
    incomplete_groups = 0
    for x in l:
        if x == "1":
            num_ones += 1
        else:
            while num_ones > 3:
                num_ones -= 3
                h += 1
                complete_groups += 1
            if num_ones > 0:
                h += 1
                incomplete_groups += 1
            num_ones = 0

    return complete_groups + incomplete_groups

def neighbours(l):
    inc_groups = incomplete_groups(l)
    final = inc_groups == 0

    candidates = []
    for i in range(len(l) - 3):
        left = l[:i]
        block = l[i:i+3]
        right = l[i+3:]
        cand = (1, left + right + block, i)

        # Optimal choice.
        if final and (block != "111" or i >= len(l.rstrip("1"))):
            continue

        candidates.append(cand)

    candidates.sort(key=lambda c: c[2], reverse=True)

    return candidates

def is_goal(l):
    return all(l[i] <= l[i+1] for i in range(len(l)-1))

opt_solver = IDAStar(h, neighbours)

def partite(l):
    if isinstance(l, list):
        l = "".join(map(str, l))
    if len(l) < 10:
        return [i + 1 for i in opt_solver.solve(l, is_goal)[1]]
    moves = []
    hist = [l]
    while not done(l):
        i = best_pos(l, hist)
        l = move(l, i)
        moves.append(i+1)
        hist.append(l)
    return moves

```

---
Tags: code-challenge, fastest-code
---