title: Print a list of iPhones

text:
# Question
Title: Print a list of iPhones
Write the shortest program that prints, in order, a complete list of iPhone iterations, according to this site:

```
iPhone
iPhone 3G
iPhone 3GS
iPhone 4
iPhone 4S
iPhone 5
iPhone 5c
iPhone 5s
iPhone 6
iPhone 6 Plus
iPhone 6s
iPhone 6s Plus
iPhone SE
iPhone 7
iPhone 7 Plus
iPhone 8
iPhone 8 Plus
iPhone X
iPhone XR
iPhone XS
iPhone XS Max
iPhone 11
iPhone 11 Pro
iPhone 11 Pro Max

```

Output should be printed exactly as specified, though trailing newlines are allowed (as well as additional whitespace at the end of each line).

This is code golf, so the shortest answer in bytes, per language, wins.

# Answer
> 13 votes
# Canvas, ~~77~~ ~~76~~ 73 bytes

```
¶＋∔ｉＦ╴qV1┼#│»ｌN↶:╋KＡRV／＋├6<∔ZK＠≠≡Ｚｅ３ｈ}s×⁴＊⁵GZX─?ep┼Q‟-ｓ｛iPhone ×|∙ Plus╋］

```

Try it here!

`-3G-3GS-4-4S-5-5c-5s-6-6|-6s-6s|-SE-7-7|-8-8|-X-XR-XS-XS Max-11-11 Pro-11 Pro Max` compressed, split on `-`, `|` replaced with `' Plus'`, and `'iPhone '` prepended.

# Answer
> 9 votes
# Zsh, ~~107~~ 105 bytes

*-2 bytes due to leniency on trailing spaces*

```
print -l iPhone\ {,{3G,4}{,S},5{,c,s},6{,s}{,\ Plus},SE,{7,8}{,\ Plus},X{,R,S,S\ Max},11{,\ Pro{,\ Max}}}

```

~~Try it online!~~ Try it online!

A long brace expansion. Bash/sh need `printf %s\\n` instead for 4 extra bytes.

# Answer
> 9 votes
# JavaScript (ES6),  ~~137 136~~  135 bytes

```
_=>"iPhone3G9GS39S33c9s3303s9s01SE3903301X1XR1XS1XS Max22 Pro2 Pro Max".replace(/\d/g,n=>[" Plus",k=`
iPhone `,k+11,k+i][n]||k+i++,i=3)

```

Try it online!

### How?

The numeric version is stored in a counter \\$i\\$ initialized to \\$3\\$.

Below are the digits used for the compression:

* \\$0\\$: `" Plus"`
* \\$1\\$: `"\n"` \+ `"iPhone "`
* \\$2\\$: `"\n"` \+ `"iPhone 11"`
* \\$3\\$: `"\n"` \+ `"iPhone "` \+ \\$i\\$
* \\$9\\$: same as \\$3\\$, but \\$i\\$ is incremented afterwards

Resulting in:

```
"iPhone"    --> "iPhone"
"3G"        --> "iPhone 3G"
"9GS"       --> "iPhone 3GS" (i++)
"3"         --> "iPhone 4"
"9S"        --> "iPhone 4S" (i++)
"3"         --> "iPhone 5"
"3c"        --> "iPhone 5c"
"9s"        --> "iPhone 5s" (i++)
"3"         --> "iPhone 6"
"30"        --> "iPhone 6 Plus"
"3s"        --> "iPhone 6s"
"9s0"       --> "iPhone 6s Plus" (i++)
"1SE"       --> "iPhone SE"
"3"         --> "iPhone 7"
"90"        --> "iPhone 7 Plus" (i++)
"3"         --> "iPhone 8"
"30"        --> "iPhone 8 Plus"
"1X"        --> "iPhone X"
"1XR"       --> "iPhone XR"
"1XS"       --> "iPhone XS"
"1XS Max"   --> "iPhone XS Max"
"2"         --> "iPhone 11"
"2 Pro"     --> "iPhone 11 Pro"
"2 Pro Max" --> "iPhone 11 Pro Max"

```

# Answer
> 4 votes
# ///, 108 bytes

Naive compression, simply replacing `#` with `\niPhone`. (Further compression does not work by the way.)

```
/#/
iPhone //@/ Plus/iPhone#3G#3GS#4#4S#5#5c#5s#6#6@#6s#6s@#SE#7#7@#8#8@#X#XR#XS#XS Max#11#11 Pro#11 Pro Max

```

Try it online!

# ///, 103 bytes

This works only if preceding newlines are allowed.

```
/#/
iPhone //@/ Plus/##3G#3GS#4#4S#5#5c#5s#6#6@#6s#6s@#SE#7#7@#8#8@#X#XR#XS#XS Max#11#11 Pro#11 Pro Max

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 81 bytes

```
11”3G3GS44S55c5s66‰´6s6s‰´SE77‰´88‰´XXRXSXSî£ÿÿˆ×ÿˆ×î£”•ΛΩ&°ŽäÞнã•0šTª£'i”ƒ¿ ”«ì»

```

Try it online!

I dom't have time to re-analyze.

# Original Solution, 178 bytes

```
'i”ƒ¿”«D… 3G«D'S«.ÀD.Á„ 4«D'S«.ÀD.Á„ 5«Ð'c«s's«.ÀD.Á„ 6«D" Plus"D.Á«sDŠ's«D.À«.ÀD.Á… SE«.ÀD.Á„ 7«D" Plus"D.Á«.À.ÀD.Á„ 8«DŠs«.ÀD.Á„ X«Ð'R«s'S«D" Max"D.Á«.À.ÀD.Á… 11«DŠ" Pro"«DŠs«»

```

Try it online!

## Explanation

First, I push the string "iPhone" by using `'i”ƒ¿”«`.

I duplicate that, and push " 3G", and concatenate them to get "iPhone 3G".

After that, I use `.ÀD.Á` to get "iPhone" at the top of the stack, etc.

When I get to iPhone 6, I put " Plus" at the bottom of the stack and save it for iPhone 6S Plus.

I don't save it for iPhone 7 and 8 Plus, because I'm not sure if it will golf off some bytes, and I'd already spent enough time figuring it out.

I **did** save " Max" though, and I'm pretty sure now that saving " Plus" would've shaved off more bytes. However, now that the program is already completed, it's unclear how I do that.

At the end, I concatenate the whole stack together with newline delimiters, and implicit output happens.

# Answer
> 4 votes
# Jelly, 83 bytes

```
“Ø^ÞṠṠẠ'Ḣß¥»=⁶œṗ;11;“RcGEs436X578 ”µ“ƈ`¿øÐ⁽ḞÆCḊḋɲÑF×GÇz ⁸¦MƊ‘×“£¿Þç‘¦5ŻṃµṚ“®Ɲ,»,K)Y

```

**Try it online!**

### How?

Uses eighteen non-"iPhone " parts and constructs each line from a big-endian number in base eighteen, then prefixes each with "iPhone " and joins with newline characters.

The parts used are (comma separated):
`Max, Plus, Pro, ,S,R,c,G,E,X,s,3,4,5,6,7,8,11`

The mapping to the eighteen digits was chosen so that:

1. the space character is a zero - allowing a single byte prepend-zero to make the first line
2. no two digit "numbers" are greater than 255 - allowing encoding with code-page indices
3. the three digit "numbers" (`S,G,3`;  `Plus,s,6`;  `Max,S,X`; and  `Max, Pro,11`) are all exact multiples of five (and less than 1275) - allowing encoding with code-page indices, with post multiplication to acquire their full value
4. the three words are adjacent and do not occupy digit one - allowing compression with a split-before spaces application

One such (1-indexed) ordering is:
`S, Max, Plus, Pro,11,R,c,G,E,s,4,3,6,X,5,7,8,`

As such the code works like so:

```
“...»=⁶œṗ;11;“...”µ“...‘×“£¿Þç‘¦5ŻṃµṚ“®Ɲ,»,K)Y - Main Link: no arguments
“...»                                          - string = "S"+" Max"+" Plus"+" Pro"
      ⁶                                        - space character
     =                                         - equals? (vectorises)
       œṗ                                      - partition before truthy indices
         ;11                                   - concatenate 11
             “...”                             - list of characters "RcGEs436X578 "
            ;                                  - concatenate
                                               - giving our "digits" [1,2,...,17,0]
                  µ                            - start a new monadic chain
                   “...‘                       - list of code-page indices = [156, 96, 11, 29, 15, 141, 195, 13, 67, 193, 233, 163, 16, 70, 17, 71, 14, 122, 32, 136, 5, 77, 145]
                               ¦               - sparse application...
                                               - ...to indices:
                         “£¿Þç‘                -   code-page indices = [2, 11, 20, 23]
                        ×       5              - ...do: multiply by five -> [156, 480, 11, 29, 15, 141, 195, 13, 67, 193, 1165, 163, 16, 70, 17, 71, 14, 122, 32, 680, 5, 77, 725]
                                 Ż             - prepend a zero
                                  ṃ            - base-decompress (convert to base-18 using the "digits")
                                               -   e.g. 680 -> [2, 1, 14] -> [" Max",'S','X']
                                   µ        )  - for each:
                                    Ṛ          -   reverse it (e.g. [" Max",'S','X'] -> ['X','S'," Max"])
                                     “®Ɲ,»     -   string = "iPhone"
                                          ,    -   pair
                                           K   -   join with a space character
                                             Y - join with newline characters
                                               - implicit, smashing print

```

# Answer
> 3 votes
# Bubblegum, 82 bytes

```
00000000: cb0c c8c8 cf4b e582 500a c6ee 0856 308c  .....K..P....V0.
00000010: 6902 67c0 854c e18c 6438 ab18 c632 8333  i.g..L..d8...2.3
00000020: 1402 724a 11c2 482c 1489 6057 18cb 1cce  ..rJ..H,..`W....
00000030: 4051 6001 67a0 0847 c019 4170 5630 82a5  @Q`.g..G..ApV0..
00000040: e09b 5801 e319 1a22 580a 0145 f9a8 3c90  ..X...."X..E..<.
00000050: 4a00                                     J.

```

Try it online!

# Bubblegum, 87 bytes

Written by @FryAmTheEggman, so I don't take credit for this.

```
00000000: e001 0700 4f5d 0034 9409 072b 9ed9 334a  ....O].4...+..3J
00000010: 2d4f 957c 30d4 5ae8 8bc7 1c12 f267 7c2c  -O.|0.Z......g|,
00000020: 47df 6d0b 6d45 b174 dcab 2da7 e97a ed9f  G.m.mE.t..-..z..
00000030: e772 808d f6c6 d93e c423 2b3c 378e 0a13  .r.....>.#+<7...
00000040: c57b 7a72 436d a362 6818 88d0 a495 4466  .{zrCm.bh.....Df
00000050: e336 dcfb ac00 00                        .6.....

```

Try it online!

# Answer
> 3 votes
# Perl 5, ~~118~~ 114 bytes

```
$_="3G3GS44S55c5s66-6s6s-SE77-88-XXRXSXS Max99Pro9Pro Max";s/-/ Plus/g;s/^|(\d|X|SE)/\niPhone $1/g;s/9/11 /g;print

```

Try it online!

This code is rather simple: in the string `$_`, it replaces "-" with " Plus". Then it cuts the string at every digit, "X" or "SE" and prefixes the matching part with a line break and "iPhone ". Finally, it replaces "9" by "11 ".

Attempting to replace " Max" or " Pro" with shorter symbols would not bring any benefits because the substitution would cost more characters.

Thanks to Weizel who allowed me to save 4 bytes by replacing the first "iPhone" in the string.

I assumed that the final newline was not necessary.

# Answer
> 2 votes
# Keg, ~~129~~ 127 bytes

```
‘1⊙‘®p`iPhone `:&
⑻3G
⑻3GS
⑻4
⑻4S
⑻5
⑻5c
⑻5s
⑻6
⑻6 ©p
⑻6s
⑻6s ©p
⑻SE
⑻7
⑻7 ©p
⑻8
⑻8 ©p
⑻X
⑻XR
⑻XS
⑻XS Max
⑻11
⑻11 Pro
⑻11 “∂⬭q≥

```

Try it online!

How's that for a submission! Simply using the register and a little bit of string compression + variables gives a kind of competitive answer.

# Answer
> 2 votes
# Retina 0.8.2, 91 bytes

```

¶3G¶3GS¶4¶4S¶5¶5c¶5s¶6=¶6s=¶SE¶7=¶8=¶X¶XR¶XS!¶11¶11 Pro!
%(`^
iPhone
!
¶$` Max
=
¶$` Plus

```

Try it online! Includes additional whitespace on the first line Explanation:

```

¶3G¶3GS¶4¶4S¶5¶5c¶5s¶6=¶6s=¶SE¶7=¶8=¶X¶XR¶XS!¶11¶11 Pro!

```

Insert the names of the models, but without `iPhone`, `Max` or `Plus`, which get added later.

```
%(`

```

Operate on each line individually.

```
^
iPhone

```

Prefix `iPhone` to the line.

```
!
¶$` Max

```

If the line has a `!`, then duplicate it and append `Max` to the duplicate.

```
=
¶$` Plus

```

If the line has a `=`, then duplicate it and append `Plus` to the duplicate.

# Answer
> 2 votes
# Bash, 109 bytes

```
printf %s\\n iPhone\ {,{3G,4}{,S},5{,c,s},6{,s}{,\ Plus},SE,{7,8}{,\ Plus},X{,R,S,S\ Max},11{,\ Pro{,\ Max}}}

```

Similar to the Zsh solution but some slight changes and some output leniency.

Try it online!

# Answer
> 2 votes
# Swift, 152 bytes

```
",3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max".split(separator: ",").forEach{print("iPhone \($0)")}

```

Being related to iPhones, this needs an answer in Swift. Unfortunately Swift is woooordy. The most boring route is the shortest :/

Try it online

# Answer
> 2 votes
# Brain-Flak, 5007 bytes

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

```

Try it online!

Created using this program

# Answer
> 2 votes
# Deadfish, 2374 bytes

```
{{i}}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}i}dc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dc{i}{i}c{{d}iiii}dc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dc{i}{i}c{i}iic{{d}iii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}c{{d}iiiiii}ddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}c{i}{i}{i}ic{{d}iii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}ic{{d}iiiiii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}ic{{i}dddddd}iiiiiic{{d}i}ic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}ic{{i}dddd}iic{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{{d}iiiiii}ddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{d}{d}ddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{{i}dddd}ic{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iic{{i}dddd}ic{{d}ii}dddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}ic{d}ddddc{{d}iiii}ic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiic{{d}iiiiii}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiic{d}{d}dddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiiic{{d}iiiiii}ddddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}iiiic{d}{d}ddddc{{i}ddddd}ddc{i}{i}{i}ddc{i}dcddc{{d}}dddddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiic{{d}ii}iic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiicddddddc{{d}iii}ddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiicdddddc{{d}iii}dddc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{{i}ddddd}iiiiiicdddddc{{d}iiiii}dc{{i}dddddd}iiiiic{i}{i}c{i}{i}iiic{{d}}{d}c{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dddcc{{d}iiiiii}ic{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dddcc{d}{d}iiic{{i}ddddd}ddc{i}{i}{i}iiiicdddc{{d}}dc{{i}d}iiiiic{d}{d}dddddc{i}{i}iiiic{i}dddcdc{d}ic{{d}iii}ic{i}{i}dddcc{d}{d}iiic{{i}ddddd}ddc{i}{i}{i}iiiicdddc{{d}ii}ic{{i}dddddd}iiiiic{i}{i}c{i}{i}iiic

```

Umm...

# Answer
> 2 votes
# Vyxal `jr`, ~~96~~ 93 bytes

```
` «₍
`\Y`
3G
3GS
4
4S
5
5c
5s
6
6Y6s
6sYSE
7
7Y8
8YX
XR
XS
XS ½…
11
11 ×Ǐ
11 ×Ǐ ½…`V↵ƛ`i¬Ẋ `+

```

Try it Online!

Compressed  `Plus` with a newline a bit.

# Answer
> 2 votes
# Python 3, 136 bytes

```
for i in",3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max".split(","):print("iPhone",i)

```

Try it online!

# Answer
> 2 votes
# APL (dzaima/APL), 139 bytes

```
⎕←↑('iPhone ',)¨" ""3G""3GS""4""4S""5""5c""5s""6""6 Plus""6s""6s Plus""SE""7""7 Plus""8""8 Plus""X""XR""XS""XS Max""11""11 Pro""11 Pro Max"

```

I do not think there is a way to "bond" similar to J's `n&u`. That would be an obvious way to save some bytes.

This is my first APL answer. I probably should've gone with something a little less trivial.

Attempt This Online!

# Answer
> 2 votes
# Vyxal `jr`, 88 bytes

```
`3G3GS44S55c5s66 «₍6s6s «₍SE77 «₍88 «₍XXRXSXS ½…1111 ×Ǐ11 ×Ǐ ½…`»∵Te§ḋƒꜝL⁼»f₀pẇ¤J`i¬Ẋ `+

```

Try it Online!

# Answer
> 1 votes
# Stax, 100 bytes

Yay, I (finally) beat Zsh!

```
┌W○εRKW>◙≡D↨u^╬=Θs╜i^░δ#(\D╘i╗◄⌠╜`┌!║Æ♂∞╦J╘^╙üÜ°¢╠╣⌂ƒ♣↨←Bµ☻òK$▲,0fε▄PÉ↔ΓÅ▲s2îùvπ↑╛!╢╠♣=·F┴²C6µób└╢íf

```

Run and debug it

## Explanation

1. Repace all `A`'s in the compressed string with `""`.
2. Surround it with `"`.
3. Evaluate the string.
4. Wrap the output in a list.
5. Map every item with a preceding `iPhone`. Print with a newline.

# Answer
> 1 votes
# , ~~175~~ 178 bytes

```
cat(paste('iPhone',c('','3G','3GS','4','4S','5','5c','5s','6','6 Plus','6s','6s Plus','SE','7','7 Plus','8','8 Plus','X','XR','XS','XS Max','11','11 Pro','11 Pro Max')),sep='\n')

```

Try it online!

Manual is shorter than this programmatic take:

# , 231 bytes

```
r=rep;b='';m='Plus';cat(paste("iPhone",paste0(r(c(b,3:6,'SE',7:8,'X',11),c(1,2,2,3,3,1,2,2,4,3)),c(b,'G','GS',b,'S',b,'c','s',b,'s','s',r(b,6),'R','S','S',r(b,3))),c(r(b,9),m,b,m,b,b,m,b,m,r(b,3),'Max',b,'Pro','Pro Max')),sep='\n')

```

Try it online!

# Answer
> 1 votes
# Batch, 156 Bytes

```
@ECHO(iPhone&For %%A In (3G 3GS 4 4S 5 5c 5s 6 6s "6 Plus" "6s Plus" SE 7 "7 Plus" 8 "8 Plus" X XR XS "XS Max" 11 "11 Pro" "11 Pro Max")do @Echo(iPhone %%~A

```

# Answer
> 1 votes
# T-SQL, 145 bytes:

```
SELECT'iPhone '+value
FROM string_split(' -3G-3GS-4-4S-5-5c-5s-6-6 Plus-6s-6s Plus-SE-7-7 Plus-8-8 Plus-X-XR-XS-XS Max-11-11 Pro-11 Pro Max','-')

```

I did find a shorter version using a simple string replacement (**128 bytes**), but it's not quite as interesting, and it's not clear whether the preceding line break is allowed:

```
PRINT REPLACE('223G23GS2424S2525c25s2626 Plus26s26s Plus2SE2727 Plus2828 Plus2X2XR2XS2XS Max211211 Pro211 Pro Max',2,'
iPhone ')

```

I used the numeral (`2`) as the replacement character so I don't have to include another set of quotes.

# Answer
> 1 votes
# Ruby, 129 bytes

```
$><<"iPhone:3G:3GS:4:4S:5:5c:5s:6:6 Plus:6s:6s Plus:SE:7:7 Plus:8:8 Plus:X:XR:XS:XS Max:11:11 Pro:11 Pro Max".gsub(?:,"
iPhone ")

```

Try it online!

Uses the fact that strings can have newlines in (one byte), rather than `\n` (two bytes). Otherwise this is a simple replacement of a single-character string into `iPhone`

# Answer
> 1 votes
# PowerShell, 108 bytes

```
'3G,3GS,4,4S,5,5c,6,6 Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max'-split','|%{"iPhone $_"}

```

Try it online!

-30 bytes for mazzy

# Answer
> 1 votes
# Stax, 92 bytes

```
Ωî♂∞¥■J⌡┤≥♦C♀ç¿kë▀/∞♥╧0î·Φ│∟/╢ì☼αuèôΩY?╘÷▄òà╣○╢{⌂P○å§o\τ+ mδ↓ê☻.═+Ä{╜A2jJü7πP|è╡╖Rä►┴Luƒ☺/¬&

```

Run and debug it

simplifying the existing answer was enough for 92. there's probably a way to compress the intial over-big string.

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

```
_=>'iPhone,3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max'.split`,`.join`
iPhone `

```

Try it online!

-5 bytes thanks to @cairdcoinheringaahing and @RedwolfPrograms

# Answer
> 1 votes
# Sequences, \\$118 \log\_{256}(96) \approx 97.1\\$ bytes

```
",3G,3GS,4,4S,5,5c,5s,6,6 Plus,6s,6s Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max"","p{H"iPhone "fhF}

```

### Explanation

```
"..."","p{H"iPhone "fhF}
"..."                    // Push a string of suffixes of the models of iPhones
     ","p                // Split by commas
         {             } // For each model:
          H"iPhone "f    //   Print "iPhone " with no trailing newline
                     hF  //   And print the suffix with a trailing newline

```

### Screenshot

# Answer
> 0 votes
# C (gcc), 162 bytes

```
f(i,n){n="3G3GS44S55c5s66 Plus6s6s PlusSE77 Plus88 plusXXRXSXS Max1111 Pro11 Pro Max";for(i=24;i--;)printf("iPhone %s\n",n+=strlen(n++));}

```

*-1 byte thanks to Neil!*
*-45 bytes thanks to dzaima!*

Try it online!

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 123 bytes

```
Write("iPhone,3G,3GS,4,4S,5,5c,6,6 Plus,SE,7,7 Plus,8,8 Plus,X,XR,XS,XS Max,11,11 Pro,11 Pro Max".Replace(",","\niPhone "))

```

Try it online!

# C# (Visual C# Interactive Compiler), 131 chars, 154 bytes

```
foreach(var x in"ȔДȥ͖˶ଇ˷೷աଈ	ଉ\0΀Ƞਠࡼၼ")WriteLine($"iPhone {x%16-1:0;X;.}"+" GS Max Pro Maxs PluscSER".Substring(x/16%32,x>>9));

```

Though it isn't the shortest, I invested quite a lot of effort and it would be a shame to just toss it all away.

Note: There is a null byte in the string, but I can't copy-paste it so it's represented by `\0` in the code.

Try it online!

# Answer
> 0 votes
# Pyth, 103 bytes

```
j"
iPhone "[kk"3G""3GS"4"4S"5"5s""5c"6+6J" Plus"="6s"+GJ"SE"7+7J8+8~J" Max"\X"XR"K"XS"+KJ11="11 Pro"+bJ

```

Today I learned about the `~`.

Try it online!

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


# Question
Title: The jumping digits to letters transformation
Imagine you have an infinite sequence of the alphabet repeated infinitely many times:

```
abcdefghijklmnopqrstuvwxyzabcd...

```

You start at index `0`, which corresponds to the letter `a`, and the `should_write` boolean flag is `False`.

The input is a list or string of single-digit numbers. For each number `n` in the input, you should:

* Print (or add to the return value) the `n-th` item of the list if the `should_write` flag is set to `True`
* If `n` is `0`, swap the `should_write` flag.
* Otherwise move (jump) the index `n` places forward.

At the end of the input, stop (and return the result if using a function).

**Input**

A sequence of digits (list or string).

**Output**

The text that comes out after applying the above procedure.

**Examples**

```
>>> g('99010')
st
>>> g('100')
b
>>> g('2300312')
f
>>> g('390921041912042041010')
mvxyptvab
>>> g('1')
>>> g('1045')
bf
>>> g('33005780')
g
>>> g('100100102')
bcd
>>> g('012')
ab

```

# Answer
> 4 votes
## Python 3, 60

```
i=b=0
for c in input():b and print(chr(97+i%26));b^=c<1;i+=c

```

Takes a list of numbers and prints the chars on separate lines.

Basically just follows the instructions. The index is `i` and the `should_write` flag is `b`. The expression `b and` short-circuits to print only when `b` is true.

# Answer
> 3 votes
# Pip, 20 bytes

Takes a string of digits as command-line argument.

```
Fda{IyOz@id?i+:dY!y}

```

This code uses a number of Pip's preinitialized variables. `i` is initially `0`, `y` is initially `""` (falsy) and `z` contains the lowercase alphabet. `a` gets the first command-line arg.

```
Fda{               }  For each digit d in a:
    IyOz@i              If y (the flag) is truthy, output letter of z at index i
                        Pip's cyclic indexing takes care of the infinite effect
          d?            If d is truthy (digit is nonzero),
            i+:d          then increment i by d;
                Y!y       otherwise, yank !y into y (thus swapping the flag)

```

An alternate way of swapping the flag would be `!:y`, with `!:` being a compute-and-assign operator just like `+:`.

```
C:\Users\dlosc> pip.py -e Fda{IyOz@id?i+:dY!y} 390921041912042041010
mvxyptvab

```

# Answer
> 2 votes
# CJam, 28 bytes

```
0q{~U{1$'a+o}&_!U^:U;+26%}/;

```

Test it here.

Nothing really special here. Like xnor, I don't have a string of letters but simply a running total (mod 26) which I add to `a` when I need to print it. The `should_write` flag is kept track of in `U`.

# Answer
> 2 votes
# R, 73 bytes

Once I got it sorted in my head:)

```
(letters[cumsum(a<-head(scan()),-1)%%26+1])[which(cumprod(-(a<1)*2+1)<0)]

```

This takes a vector of integers from STDIN and returns a vector of letters.

Ungolfed and explanation

```
a <- head(scan()),-1)    # get integers from stdin and drop last one
a <- cumsum(a) %% 26 + 1 # do the cumulative sum of the vector to use as a vector of letter indexes
l <- letters[a]          # vector of potential letters
p <- -(a<1)*2+1          # turns 0's into -1 and everything else into 1
p <- cumprod(p)          # the cumlative prod then creates a vector of on and off values
f <- which(p<0)          # index values of the returned characters
l[f]                     # return vector of characters

```

Tests

```
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 9 9 0 1 0
6:
Read 5 items
[1] "s" "t"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 1 0 0
4:
Read 3 items
[1] "b"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 2 3 0 0 3 1 2
8:
Read 7 items
[1] "f"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 1
2:
Read 1 item
character(0)
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 1 0 4 5
5:
Read 4 items
[1] "b" "f"
> (letters[cumsum(a<-head(scan(),-1))%%26+1])[which(cumprod(-(a<1)*2+1)<0)]
1: 0 1 2
4:
Read 3 items
[1] "a" "b"
>

```

# Answer
> 1 votes
# JavaScript (ES6) 76

(note: the fromCharCode function is so lengthy that for lowercase letters it's better a conversion to base 36)

Test running the snippet below in any EcmaScript 6 compliant browser

```
g=l=>l.replace(/./g,n=>[f?(p%26+10).toString(36):'',-n?p-=-n:f=!f][0],p=f=0)

console.log=x=>O.innerHTML+=x+'\n'

;['99010','100','2300312','390921041912042041010','1','1045','33005780','100100102','012']
.forEach(t=>console.log(t+' ['+g(t)+']'))
```

```
<pre id=O></pre>
```

# Answer
> 0 votes
# Ruby, 59 bytes

Port of xnor's Python answer.

```
->a{i=0
b=p
a.map{b&&$><<(97+i%26).chr
b=!b if _1<1
i+=_1}}

```

Attempt This Online!

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


title: On the Subject of Keypads

text:
# Question
Title: On the Subject of Keypads
Keep Talking and Nobody Explodes is a local multiplayer game where one player has control over a virtual "bomb", and has to be guided by another player, the "expert", who has access to a bomb defusal manual. One of the modules to be disarmed in the game is the keypad module, which is what we'll be dealing with in this challenge.

## The task

Input will start with a single line of printable ASCII characters except space (0x21 to 0x7E). These represent the keypad buttons visible to you.

The next few lines will represent "keys" – only one line will contain all of the characters of the first line, not necessarily in order. Your task is to output the keypad characters, in the order of the matching key line.

For example, if the input was

```
5~Fy
HrD7K!#}
Ui%^fHnF
)Tf;y~I5
~Fi(&5gy
,'Xd#5fZ

```

then the keypad buttons are `5`, `~`, `F` and `y`. Only the 4th key line `~Fi(&5gy` contains all of these characters, so we output the keypad characters in the order in which they appear, i.e. `~F5y`.

## Rules and clarifications

* Input must be a single multiline string, with the keypad buttons and key lines on separate lines.
* There will be exactly one key line which contains all of the keypad characters.
* Every line, i.e. the initial keypad line and following key lines, will have no duplicate characters.
* Unlike the game, you may not assume anything about the number of keypad characters, the length of each key line or the number of key lines. However, all key lines are guaranteed to be the same length.
* The output may contain a single optional trailing newline. Similarly you may assume either way about an optional trailing newline in the input, but please specify in your answer if you need the assumption.
* Although this already seems to be common practice, I'll state explicitly: terminating with an error is okay for this challenge, as long as STDOUT output is correct (if this is your chosen form of output). Hopefully this will make handling input easier.

## Test cases

```
7
4?j01C3"ch
KP.OG>QB)[
z#)Kn"I2&.
]#,D|sBFy5
Qzj*+~7DLP

```

**Output:** `7`. Only the last line contains a `7`.

```
0b~
Ob+hy{M|?;>=dtszPAR5
*8rCfsw|3O9.7Yv^x>Hq
$ip.V@n}|La:TbIt^AOF
jZ[Ec4s0|%b*$id',~J6
z*#b}-x$Ua&!O2;['T+?
NVj_X8rlhxfnS\.z}];c
bykscf.w^dnWj+}-*2g_
VP`AJH|&j5Yqmw/"9IMc

```

**Output**: `0b~`. The 4th key line already contains the characters in the right order.

```
MTuz
bIAr>1ZUK`s9c[tyO]~W
oMGIi/H&V"BeNLua%El=
j*uYbplT:~);BM|_mPZt
Q}z5TC@=6pgr<[&uJnM%
YOA(F~_nH6T{%B7[\u#5
y&t"8zQn{wo5[Idu4g:?
[0tZG"-fm!]/|nqk,_2h
dA&C.+(byo6{7,?I}D@w

```

**Output**: `zTuM`. The key line is the 4th one, although the 3rd key line is a close miss.

```
o@nj<G1
f]?-<I6h2vS*%l=:}c8>LK5rMdyeon,;sE[@m(73
ibhp+2Hq6yKzIf_Zo}EO3-[*0/e&Fvd]wQU=|%`C
;}>d'cg~CPtQG&%L\)MUl419bkTZ7@]:[*H"RyYj
L^<:zXJ#kj$EFlwN%B`Dd,Cs?]xRZ*K9-uQ.@&f+
i1v'7:90R-l}FMxj`,DTWK+(n32Z4Vs[p@%*eS!d
B|^Ti/ZG$}ufL9*wE[AVt]P7CrX-)2JpD<sYxd6O
ex.$4#KarS^j+'_!B"]H[\83:(DCXUgI*Lct?qAR
^GXQoy*KW&v}n']Em~\N9)fxP(qC=7#4sRdcD6%5
;inr[&$1j_!F~@pzo#blv]}<'|fRds6OW%tEg"G2
e;0T#gfo^+!:xHDN&4V=In?AwhEv$2Fd~ZLz_\81

```

**Output**: `n1j@o<G`. The key line is the second last line.

## Scoring

This is , so the code in the fewest bytes wins.

# Answer
## CJam, ~~13~~ 12 bytes

```
qN/(f&{,}$W=

```

Test it here.

### Explanation

```
q     e# Read all input.
N/    e# Split into lines.
(     e# Pull off the keypad buttons.
f&    e# Take the set intersection of each key line with the keypad, preserving the order
      e# order in the key line.
{,}$  e# Sort the results by length.
W=    e# Pick the last (longest) one.

```
> 10 votes

# Answer
# Pyth, 10

```
@zhf!-zT.z

```

Try it online

### Explanation

```
@zhf!-zT.z         ##  z = first line of input, .z = list of rest of lines
   f    .z         ##  Filter .z as T based on
    !-zT           ##  Whether removing all the letters from z that appear in T leaves an
                   ##  Empty string or not (keep the ones that give empty strings)
  h                ##  Take the first such line (necessary indexing, shouldn't ever matter)
@z                 ##  @ is setwise intersection. Pyth implements this by iterating over
                   ##  each element of the second argument and keeping values that appear
                   ##  in the first argument, which gives the intended result

```
> 8 votes

# Answer
# Pyth, 9 bytes

```
eolN@Lz.z

```

Demonstration

`@Lz.z`: Filter all lines for the intersection with the first line.

`olN`: Order by length

`e`: Take the longest.
> 7 votes

# Answer
## Haskell, 49 bytes

```
g(!)(a:b)=[c|d<-b,all(!d)a,c<-d,c!a]
g elem.lines

```

The first line defines a helper function `g`, the unnamed function on the second line is my answer.

## Explanation

The algorithm is the obvious one: split input into lines, find the line that contains all characters of the first line, and filter out all the other characters on that line.

```
g(!)(a:b)=                            -- g gets a binary function ! and list of strings a:b
          [c|                         -- and returns the string of characters c where
             d<-b,all(!d)a,           -- d is drawn from b and x!d holds for all x in a,
                           c<-d,c!a]  -- and c is drawn from d and c!a holds.
g elem.lines                          -- The input is split into lines and fed to g elem;
                                      -- then x!d means x `elem` d in the above.

```
> 3 votes

# Answer
# Prolog, ~~204~~ 190 bytes

This could have been a nice challenge for Prolog if it hadn't been for the combined requirements of multiline input and unescaped characters ' and " in the input. A big chunk of the code (p and r) exist to read a file as character codes which is what I had to do to take unescaped input on several lines.
If only ' existed as an unescaped character, I could read input as a string.
If only " existed as an unescaped character, I could read input as an atom.
If input wasn't multiline, say separated by space instead, I could read it as one line to codes.

```
r(I,[H|T]):-read_line_to_codes(I,H),H\=end_of_file,r(I,T).
r(_,[]).
q(_,[]).
q(E,[H|T]):-subset(E,H),intersection(H,E,X),writef("%s",[X]);q(E,T).
p:-open("t",read,I),r(I,[H|T]),q(H,T),!.

```

**How it functions**

1. Opens file t (which contains all input) to read
2. Read all lines as character codes and place in a list of lists (1 list per row)
3. Recurses over tail lists and checks if head list exist as a subset of that list
4. Intersects matched list with head to get wanted characters in the correct order
5. Prints solution

**How to run**
Program is run with command:
p.
File namned t containing input has to be in the same directory.

**Edit:** Saved 14 bytes by unifying 2 q-clauses with OR.
> 3 votes

# Answer
## MATLAB, 107 bytes

```
b=char(strsplit(char(inputdlg),' '));[~,x]=ismember(b,b(1,:));[~,f]=min(abs(1./sum(~x')-1));b(f,(~~x(f,:)))

```

This ended up being a very sloppy piece of code...

When being run, an input dialog is opened where a multi-line string can be pasted into (newlines are converted to spaces and the output will be a cell with 1 very long string). I chose to convert the resulting cell to a char which makes it possible to split at the spaces (result is a cell array) and then again convert to char to retrieve the intended shape. MATLAB's built-in **ismember** function does a good job here in comparing our first line to the other lines.

After that it gets nasty... I've tried a lot of ways to exclude the first line from my 'best match' check and ended up with this. We look for the line and then use this information to grab the indices (by converting our **ismember** output to logicals) that we want our output characters from.
> 2 votes

# Answer
# Wolfram Language 106 bytes

```
c=Characters[InputString[]~StringSplit~"\n"];o=c[[1]];t=Select;t[t[Rest@c,#~SubsetQ~o&][[1]],o~MemberQ~#&]

```

Example input:

Output:

Explanation of the code : First with InputString we get the full string of input, then we get the first set of letters by splitting the string by newline, and saving all the characters of the first one in variable o. Next, we select from the rest of the input lines those lines that have the first line's characters (saved as variable o) as a subset. Then with that line selected, we grab the members of that line that are in the original set.

Edit : Thanks to Martin Büttner for the tips on using infix notation and my unnecessary variables
> 2 votes

# Answer
# Japt `-h`, ~~6~~ 8 bytes

~~Takes the keypad as an array of lines. The buttons can be either a string or a character array.~~ +2 bytes to accommodate the cumbersome input format.

```
·ËoFgÃñl

```

Try it

```
·ËoFgÃñl     :Implicit input of multi-line string
·            :Split on newlines
 Ë           :Map each element in array F
  o          :  Remove characters not contained in
   Fg        :  First element of F
     Ã       :End map
      ñ      :Sort by
       l     :  Length
             :Implicit output of last element

```
> 2 votes

# Answer
# Javascript (ES6), 107 104 102 bytes

Snippet demo for supporting browsers.

```
f=x=>([a]=x.split`
`).map(y=>[...y].filter(z=>~a.indexOf(z)-x).join(x='')).find(z=>z.length==a.length)
```

```
<textarea id="i" rows="6" cols="45">o@nj<G1
f]?-<I6h2vS*%l=:}c8>LK5rMdyeon,;sE[@m(73
ibhp+2Hq6yKzIf_Zo}EO3-[*0/e&Fvd]wQU=|%`C
;}>d'cg~CPtQG&%L\)MUl419bkTZ7@]:[*H"RyYj
L^<:zXJ#kj$EFlwN%B`Dd,Cs?]xRZ*K9-uQ.@&f+
i1v'7:90R-l}FMxj`,DTWK+(n32Z4Vs[p@%*eS!d
B|^Ti/ZG$}ufL9*wE[AVt]P7CrX-)2JpD<sYxd6O
ex.$4#KarS^j+'_!B"]H[\83:(DCXUgI*Lct?qAR
^GXQoy*KW&v}n']Em~\N9)fxP(qC=7#4sRdcD6%5
;inr[&$1j_!F~@pzo#blv]}<'|fRds6OW%tEg"G2
e;0T#gfo^+!:xHDN&4V=In?AwhEv$2Fd~ZLz_\81</textarea><br /><input type="button" onclick="o.value=f(i.value)" value="Run"> Output: <input type="text" id="o" readonly />
```

**Commented:**

```
f=x=>
([a]=x.split('\n')) // split input by newlines, assign first value to a
.map(y=> // map function to each line
    [...y].filter(z=> // filter characters
        ~a.indexOf(z)-x // a has character z and not the first item (x is still set)
    ).join(x='') // join characters with empty string, reset x flag
).find(z=>z.length==a.length) // return string with same length as a

```
> 1 votes

# Answer
# Python 2, 112 bytes

```
import sys
i=sys.stdin.readlines()
print[''.join(c for c in l if c in i[0])for l in i[1:]if set(i[0])<set(l)][0]

```

Example run: Ideone
> 1 votes

# Answer
# Ruby, ~~96~~ ~~71~~ 63 bytes

-8 bytes thanks to south

Inspired by Shaggy’s Japt solution. Requires a trailing newline in the input.

```
->s{a,b=s.split$/,2
b.gsub(/./){a[$&]&&$&}.lines.max_by &:size}

```

Attempt This Online!
> 1 votes

# Answer
# Nibbles, ~~8~~ 7 bytes (14 nibbles)

```
/\+=~.;@`&$;$,

```

```
      .         # map over
       ;@       # all lines of input
         `&     # getting list intersection
           $    # of each line
            ;$  # with the first line of input;
    =~          # now group intersections by
              , # length,
   +            # flatten the list-of-groups,
  \             # reverse it
                # (so the 'found' keys are now first,
                # and the input is second),
/               # finally, fold from right
                # returning the (implicit) right argument
                # at each step
                # (so returning the first element)

```
> 0 votes

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


# Question
Title: Iterate through addition of number sequence until a single digit
Challenge: With any given number that has multiple digits, every digit in the number needs to repeatedly be summed together until the sum is a single digit number. To make things interesting, if there's a 0 in the number, then it must equal 26, because zero starts with the letter z, which is the 26th and final letter of the alphabet.

Example:

With an input of \\$120\\$:

* \\$1 + 2 + 26 = 29\\$
* \\$2 + 9 = 11\\$
* \\$1 + 1 = 2\\$

The answer would be 2.

Output:

```
120
29
11
2

```

Scoring:

The code that's written in the fewest bytes wins.

# Answer
> 5 votes
# Jelly, 7 bytes

```
Do26SƲƬ

```

A monadic Link that accepts a non-negative integer and yields a list of non-negative integers.

**Try it online!**

### How?

```
Do26SƲƬ - Link: integer, n
      Ƭ - collect up (starting with X=n) while distinct applying:
     Ʋ  -   last four links as a monad:
D       -     decimal digits (X)
  26    -     26
 o      -     logical OR (vectorises)
    S   -     sum

```

# Answer
> 3 votes
# Go, 97 bytes

```
func f(n int){println(n)
if n<10{return}
k:=0
for;n>0;n/=10{if n%10<1{k+=26}else{k+=n%10}}
f(k)
}

```

Attempt This Online!

# Answer
> 3 votes
# Nibbles, 8.5 bytes (17 nibbles)

```
/`.$+.`@~$?$$26@

```

Returns just the final digit. If we can return the sequence (for instance, 120 29 11 2, as in the example) then we can drop the initial `/` and final `@` for 7.5 bytes (`/`.$+.`@~$?$$26@`)

```
 `.               # iterate while unique:
      `@ $        #  convert to digits in base
        ~         #  10 (default)
     .            #  now map over each digit
          ?$      #   if it's nonzero
            $     #   then that digit
             26   #   otherwise 26
    +             #  now sum the list
/                 # finally, fold from right
               @  #  each time returning right argument
                  #  (so returning the last element)

```

# Answer
> 3 votes
# Japt `-R`, 12 bytes

```
_ì xª26}hN â

```

Try it

```
_ì xª26}hN â     :Implicit input of integer U
_                :Function taking an integer as argument
 ì               :  To digit array
   x             :  Sum of each
    ª26          :    Logical ORed with 26
       }         :End function
         N       :Starting with the array of all inputs (i.e., [U])
        h        :Run the function and push the result to N until length U
           â     :Deduplicate
                 :Implicit output joined with newlines

```

# Answer
> 3 votes
# Retina 0.8.2, 14 bytes

```
{`0
998
.
$*
.

```

Try it online! Only outputs the final digit. Explanation:

```
{`

```

Repeat until the value doesn't change, i.e. it's a single digit `1-9`.

```
0
998

```

Replace `0`s with `998`, which has a digit sum of 26.

```
.
$*
.

```

Calculate the sum of the values of the digits by converting each digit separately to unary and then converting the total back to decimal.

# Answer
> 3 votes
# Excel (ms365), 83 bytes

Formula in `B1` for 117 bytes:

```
=TOCOL(SCAN(A1,ROW(1:9),LAMBDA(a,b,IF(b=1,a,LET(c,--MID(a,SEQUENCE(LEN(a)),1),d,SUM(IF(c,c,26)),IF(a=d,NA(),d))))),3)

```

Formula in `C1` for 83 bytes:

```
=REDUCE(A1,ROW(1:9),LAMBDA(a,b,LET(c,--MID(a,SEQUENCE(LEN(a)),1),SUM(IF(c,c,26)))))

```

---

**Note:** If Excel's 15 digits precision becomes a problem with huge numbers than `A1` should be text input. I have tried but never needed more than 9 iterations to get to a single digit.

# Answer
> 2 votes
# Python, ~~68~~ ~~66~~ 60 bytes

\*-2 bytes thanks to c--

```
f=lambda n:n>9and[n]+f(sum(int(d)or 26for d in str(n)))or[n]

```

Attempt This Online!

# Answer
> 2 votes
# Husk, ~~12~~ ~~9~~ 7 bytes

```
ω(ṁ|26d

```

*Edit: -2 bytes by copying the logical-OR trick from Jonathan Allan's answer*

Try it online!

Returns just the final digit. If we need to return the sequence (for instance, 120 29 11 2, as in the example) then exchange the initial `ω` for  for 8 bytes (`U¡(ṁ|26d`).

```
 ω(             # Find fixed point by iterating:
          d     #  get decimal digits
   ṁ            #  map over each digit
                #  and sum the result:
     |          #   second arg if truthy (1-9)
       26       #    otherwise 26

```

# Answer
> 2 votes
# Python 2, 56 bytes

```
f=lambda n:[n][n-9:]or[n]+f(sum(int(c)or 26for c in`n`))

```

A recursive function that accepts a non-negative integer and returns a list of non-negative integers.

**Try it online!**

---

# Python 3, 60 bytes

```
f=lambda n:[n][n-9:]or[n]+f(sum(int(c)or 26for c in str(n)))

```

A recursive function that accepts a non-negative integer and returns a list of non-negative integers.

**Try it online!**

# Answer
> 2 votes
# Factor \+ `math.unicode`, 53 bytes

```
[ [ >dec "0" "J" replace 48 v-n Σ ] to-fixed-point ]

```

Try it online!

The only mildly clever thing this does is replace `0` with `J` in the string representation of the number so it ends up as 26 after converting to digits.

* `[ ... ] to-fixed-point` Call `[ ... ]` on the input until it stops changing.
* `>dec` Convert a number to a string.
* `"0" "J" replace` Replace the zeros with `J`.
* `48 v-n` Subtract 48 from each code point in the string.
* `Σ` Take the sum.

# Answer
> 1 votes
# Pyth, 15 bytes

```
Wg
QT=Qsm|sd26`

```

Try it online!

### Explanation

```
                  implicit Q = eval(input())
WgQT              while Q >= 10 (print Q when this is checked)
    =Q            assign Q to
      s           the sum of
       m     `    map the digits of Q to
        |sd26     themselves, unless they are 0, then 26

```

# Answer
> 1 votes
# Ruby, 44 bytes

```
F=->n{(p n)>9?F[n.digits.sum{_1<1?26:_1}]:n}

```

Attempt This Online!

# Answer
> 1 votes
# Japt, 17 bytes

```
<A?N:ßNpUì xª26)Ì

```

Try it

Explanation:

```
<A?N:ßNpUì xª26)Ì
                  # At first iteration, U = input, N = [input]
<A                # Check whether U is less than 10
  ?               # If so:
   N              #  Output N
    :             # Otherwise:
        Uì        #  Get the digits of U
           x      #  Sum them with this modification:
            ª     #   Replace 0
             26   #   With 26
      Np       )  #  Append the result to N
     ß            #  Repeat the program with new U:
                Ì #   The last number in N

```

Alternate which avoids the ternary expression, but it's not shorter.

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

Returns a comma-separated string.

```
f=n=>n>9?n+[,f((g=n=>n&&(n%10||26)+g(n/10|0))(n))]:n

```

Try it online!

### Commented

```
f = n =>             // f is a recursive function taking the input n
n > 9 ?              // if n has more than one digit:
  n + [,             //   append n, followed by a comma,
    f(               //   followed by the result of a recursive call:
      ( g = n =>     //     g is a helper recursive function taking n:
        n && (       //       stop if n = 0
          n % 10     //       otherwise, extract the least significant digit
          || 26      //       replace it with 26 if it's 0
        ) +          //
        g(           //       add the result of a recursive call with ...
          n / 10 | 0 //         ... floor(n / 10)
        )            //       end of recursive call to g
      )(n)           //     initial call to g
    )                //   end of recursive call to f
  ]                  //
:                    // else:
  n                  //   append the final n and stop the recursion

```

# Answer
> 1 votes
# Vyxal, ~~8~~ 7 bytes

```
f0₄V∑)↔

```

Try it Online!

Outputs the whole list. I may have forgotten there's a built in for 26 lol.

## Explained

```
f026V∑)↔
      )↔ # Until applying the following doesn't result in a different value, collect intermittent values.
f         #   flatten the function argument
 026V     #   and replace 0s with 26 (the 0 and 26 are pushed separately)
     ∑    #   sum the resulting list

```

# Answer
> 1 votes
# sed `-E`, 79 bytes

```
:a
/^a{10}*(A|$)/s/$/ABBBBB/
s/B/AAAAA/
s/(a+)\1{9}(.*)/\1\U\2/
ta
s/A+/\L&/
ta

```

Attempt This Online!

**Explanation:**

```
:a
# check for divisibility by 10
# if it is divisible, then add 26 to sum
# B = 5A, A = 1, ABBBBB = 26
/^a{10}*(A|$)/s/$/ABBBBB/
s/B/AAAAA/
# divide the number by 10 and add remainder to the sum
s/(a+)\1{9}(.*)/\1\U\2/
ta
# change the sum back to normal number
s/A+/\L&/
# repeat till the number is single digit
# uses the fact that division is performed only on numbers > 9
# and otherwise the sum is zero, thus no conversion back to normal number is performed
ta

```

# Answer
> 1 votes
# Charcoal, 16 bytes

```
Ｗ⊖Ｌθ≔ＩΣＥθ∨Ｉκ²⁶θθ

```

Try it online! Link is to verbose version of code. Only outputs the final digit. Explanation:

```
Ｗ⊖Ｌθ

```

Repeat until the input only has one digit.

```
≔ＩΣＥθ∨Ｉκ²⁶θ

```

Cast each digit to integer, replace zeros with 26, take the sum, then cast back to string again.

```
θ

```

Output the final digit.

# Answer
> 1 votes
# Gaia, 11 bytes

```
⟨$⟨26∨⟩¦Σ⟩ª

```

Try it online!

Outputs the final result because that seems to be allowed. Uses a similar algorithm to the Jelly answer.

## Explained

```
⟨$⟨26∨⟩¦Σ⟩ª
⟨       ⟩ª  # Until the result doesn't change:
 $⟨26∨⟩¦    #   logical or each digit of the argument with 26
       Σ   #   digital sum

```

# Answer
> 1 votes
# C (gcc), 49 bytes

```
k;f(n){for(k=0;n;n/=10)k+=n%10?:26;n=k>9?f(k):k;}

```

The expression `n%10?:26` returns `n % 10` if it's not 0, otherwise 26, where `:?` is the Elvis operator, a GNU extension to the language.

This returns the last number in the sequence. Try it online!

# Answer
> 0 votes
# 05AB1E, 6 bytes

```
ΔS0₂:O

```

Only outputs the final digit.

Try it online.

Outputting each intermediate step including the first would be 1 bytes longer:

```
Δ=S0₂:O

```

Try it online.

**Explanation:**

```
Δ        # Loop until the result no longer changes, using the (implicit) input:
  S      #  Convert it to a list of digits
   0₂:   #  Replace all 0s with 26s
      O  #  Sum the list together
         # (after which the resulting digit is output implicitly)

 =       #  Print the current integer with trailing newline (without popping)

```

# Answer
> 0 votes
# Whitespace, 161 bytes

```
[S S S N
_Push_0][S N
S _Duplicate][T N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][S N
S _Duplicate_input][N
S S N
_Create_Label_OUTER_LOOP][S N
N
_Discard_top][S N
S _Duplicate_top][T N
S T _Print_as_integer][S N
S _Duplicate_top][S S S T   S T S N
_Push_10_(\n)][S N
S _Duplicate_10_(\n)][T N
S S _Print_as_character][T  S S T   _Subtract][N
T   T   S T N
_If_negative_jump_to_Label_EXIT][S S S N
_Push_digitSum=0][S N
T   _Swap_top_two][N
S S S N
_Create_Label_INNER_LOOP][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S T T   _Modulo][S N
S _Duplicate][N
T   S T N
_If_0_jump_to_Label_ZERO][N
S S S S N
_Create_Label_RETURN][S T   S S T   S N
_Copy_0-based_2nd_(digitSum)][T S S S _Add][S N
T   _Swap_top_two][S S S T  S T S N
_Push_10][T S T S _Integer-divide][S N
S _Duplicate][N
T   S N
_If_0_jump_to_Label_OUTER_LOOP][N
S N
S N
_Jump_to_Label_INNER_LOOP][N
S S T   N
_Create_Label_ZERO][S N
N
_Discard_top][S S S T   T   S T S N
_Push_26][N
S N
S S N
_Jump_to_Label_RETURN]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Outputs each intermediate step (since that's shorter than only outputting the final digit anyway).

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer n = STDIN as integer
Start OUTER_LOOP:
  Print n as integer to STDOUT
  Print '\n'
  If n is smaller than 10 (n-10 is negative):
    Stop the program with an error by jumping to nonexistent Label EXIT
  Integer digitSum = 0
  Start INNER_LOOP:
    Integer d = n modulo-10
    If d == 0:
      d = 26
    digitSum = d + digitSum
    n = n integer-divided by 10
    If n == 0:
      n = digitSum
      Go to next iteration of OUTER_LOOP
    Go to next iteration of INNER_LOOP

```

---
Tags: code-golf, number, arithmetic
---


title: Letters, Get Moving! Pt. 2

text:
# Question
Title: Letters, Get Moving! Pt. 2
The first Letters, Get Moving! was very popular, but had limited participation. This one will be easier to solve, but hopefully involve some tricks in golfing.

You are given a string of only lowercase letters. For each letter, with position in the alphabet *m*, move it so it becomes the *m*th letter from the end. If the value of *m* is longer than the length of the string, move it to the very front. Output only the fully transformed string.

**Examples:**

**"giraffe"**

* 'g' is the 7th letter in the alphabet, it is already the 7th letter from the back, so leave it.
* 'i' is the 9th letter, since 9 is bigger than the length of the word, it goes to the front, so the string becomes `igraffe`
* 'r' is the 18th letter, like 'i' it goes to the front: `rigaffe`
* 'a' is the 1st letter, it goes to the very end: `rigffea`
* 'f' is the 6th letter, it becomes the 6th from the back: `rfigfea`
* the next 'f' is also the 6th letter, so it also goes to 6th from the back : `rffigea`
* 'e' is the 5th letters, it goes to 5th from the back: `rfefiga`

**"flower"**

* 'f' (6) =\> `flower`
* 'l' (12) =\> `lfower`
* 'o' (15) =\> `olfwer`
* 'w' (23) =\> `wolfer`
* 'e' (5) =\> `weolfr`
* 'r' (18) =\> `rweolf`

**"pineapple"**

* 'p' (16) =\> `pineapple`
* 'i' (9) =\> `ipneapple`
* 'n' (14) =\> `nipeapple`
* 'e' (5) =\> `nipaepple`
* 'a' (1) =\> `nipepplea`
* 'p' (16) =\> `pnipeplea`
* 'p' (16) =\> `ppnipelea`
* 'l' (12) =\> `lppnipeea`
* 'e' (5) =\> `lppneipea` (make sure you move the *e* that hasn't been moved already! Here it doesn't matter, but below it does.)

*Thanks to @Neil for improving the test cases with these 3 additions:*

**"pizza"**

* 'p' (16) =\> `pizza`
* 'i' (9) =\> `ipzza`
* 'z' (26) =\> `zipza`
* 'z' (26) =\> `zzipa` (moving the second z!)
* 'a' (1) =\> `zzipa`

**"abracadabra"**

* 'a' (1) =\> `bracadabraa`
* 'b' (2) =\> `racadabraba`
* 'r' (18) =\> `racadabraba`
* 'a' (1) =\> `rcadabrabaa`
* 'c' (3) =\> `radabrabcaa`
* 'a' (1) =\> `rdabrabcaaa`
* 'd' (4) =\> `rabrabcdaaa`
* 'a' (1) =\> `rbrabcdaaaa`
* 'b' (2) =\> `rrabcdaaaba`
* 'r' (18) =\> `rrabcdaaaba`
* 'a' (1) =\> `rrbcdaaabaa`

**"characters"**

* 'c' (3) =\> `haractecrs`
* 'h' (8) =\> `arhactecrs`
* 'a' (1) =\> `rhactecrsa`
* 'r' (18) =\> `rhactecrsa`
* 'a' (1) =\> `rhctecrsaa`
* 'c' (3) =\> `rhtecrscaa`
* 't' (20) =\> `trhecrscaa`
* 'e' (5) =\> `trhcrescaa`
* 'r' (18) =\> `rtrhcescaa`
* 's' (19) =\> `srtrhcecaa`

# Answer
## CJam, ~~41~~ 38 bytes

```
lee_S+W%\{Xa-X1='`-/(Xa+\L*+}fX1>W%1f=

```

Test it here.
> 9 votes

# Answer
# Python 3, 78 bytes.

Saved 2 bytes thanks to orlp.
Saved 7 bytes thanks to DSM.

```
x=input()
y=[]
for z in x:m=max(len(x)-ord(z)+96,0);y[m:m]=z
print(''.join(y))

```

Builds the word as a list then joins it.
> 5 votes

# Answer
# Python 2, 86 bytes

```
a=input();k=list(a)
for i in a:k.remove(i);k.insert(ord(i)-97,i)
print"".join(k)[::-1]

```

---

# Python 3, 88 bytes

```
a=input();k=list(a)
for i in a:k.remove(i);k.insert(ord(i)-97,i)
print("".join(k)[::-1])

```

---

### Examples

Python 2:

```
$ python2 test.py
"flower"
rweolf

```

Python 3:

```
$ python3 test.py
flower
rweolf

```
> 3 votes

# Answer
## Javascript ES6, ~~136~~ ~~134~~ 131 bytes

```
s=>([...s].map(c=>{s=s.replace(c,'');p=s.length+97-c.charCodeAt();s=s.substr(0,p)+c.toUpperCase()+s.substring(p)}),s.toLowerCase())

```

Note that I take great care not to move the same character twice, otherwise `pizza` turns into `zipza` when it should be `zzipa`. There's also an edge case dealing with not removing characters prematurely; `characters` becomes maybe `srtrchaeac` or `srtrheccaa` if you do it wrongly but it should be `srtrhcecaa`. Another tricky word is `abracadabra` for which the output `rrabaaadcba` would be incorrect; `rrbcdaaabaa` would be correct.

Edit: Shaved off two bytes by using substring which automatically coerces its arguments to the range 0..length.

Edit: Shaved off three bytes by changing the first substring to substr as suggested by user81665.
> 2 votes

# Answer
# Knight (v2), 58 bytes

```
;=i~!=sP;W<=i+1iLs=sI>0=l-L=tSs iT@-A=cGs iT95+c tSt lFcOs

```

Try it online!

expanded:

```
; = idx ~1 # ie -1
; = str PROMPT
; WHILE < (= idx + idx 1) (LENGTH str)
    ; = chr GET str idx 1 # ie get the char at index `idx`
    ; = tmp SET str idx 1 "" # delete that chr
    ; = index - (LENGTH str) (- (ASCII chr) 95)
    : = str
        IF (> 0 index)
            : + chr tmp
        # ELSE:
            : SET tmp index 0 chr # insert the char there
: OUTPUT str

```
> 2 votes

# Answer
# Pyth, ~~18~~ 17 bytes

```
uXeS,Z-lzhx;HGHzk

```

Test Suite.

Iterates using reduce over the input string, inserting into a string, base case empty string, at the correct position.
> 1 votes

# Answer
# , 23 chars / 40 bytes

```
ᴉⓜΞăМƲ ïꝈ-ᶛą$,0),0,$;Ξ⨝

```

`Try it here (Firefox only).`

# Explanation

```
ᴉⓜΞăМƲ ïꝈ-ᶛą$,0),0,$;Ξ⨝ // implicit: ï=input, ᴉ=input split into chars, Ξ=empty array, ᶛ=lowercase alphabet
ᴉⓜ                      // map over input chars
   ΞăМƲ ïꝈ-ᶛą$,0),0,$;   // use splice to insert map item into Ξ at requested index
                      Ξ⨝ // join Ξ
                         // implicit output

```
> 1 votes

# Answer
# Ruby, 56 bytes

Port of Morgan Thrapp's Python answer.

```
->x{y=[]
x.chars{y[[x.size-_1.ord+96,0].max,0]=_1}
y*""}

```

Attempt This Online!
> 1 votes

# Answer
# 05AB1E, 25 bytes

```
.āDvyUΣNsXQiIgAXнk2t+-]€н

```

Outputs as a list of characters.

Try it online or verify all test cases.

**Explanation:**

Unfortunately 05AB1E lacks a builtin to insert a character at a certain index without removing the current character at that index. So instead I'm using a sort-by, where I only modify the index of the current character.

```
.ā                  # Enumerate the (implicit) input-string, pairing each character with
                    # its (0-based) index (to make them all unique)
  D                 # Duplicate it
   v                # Loop over each pair `y` in this list:
    yU              #  Put pair `y` in variable `X`
    Σ               #  Sort the list of pairs by:
     N              #   Push the current sort-index
     s              #   Swap so the current pair is at the top of the stack
      XQi           #   If it's equal to pair `X`:
         Ig         #    Push the input-length
           A        #    Push the lowercase alphabet
            Xн      #    Push the character of pair `X`
              k     #    Get the (0-based) index of this character in the alphabet
               2t+  #    Add sqrt(2) to it (+1 to make it 1-based, and +0.414 so it'll
                    #    come before the actual integer-index)
                  - #    Subtract this index from the input-length
   ]                # Close both the sort-by and loop
    €               # Map over each pair
     н              #  And only leave its character
                    # (after which the list of characters is output implicitly)

```
> 1 votes

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


title: The Tic Tac Toe Dictionary

text:
# Question
Title: The Tic Tac Toe Dictionary
A `TicTacToe` game can be represented by a string denoting the sequence of positions as the players make their move.

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

```

Assume `X` always plays first.

So a string of "012345678" denotes the game

```
X O X
O X O
X O X

```

Notice, the game is already won when Player `X` marks `6`, at that point the game ends, granting a win to `X`. (ie, ignore the remaining moves once a player wins)

Your challenge (code) is to print all the games (sorted order) and its results.

The Format

```
<movesequence>:<result>\n

```

eg:

```
012345678:X
012345687:X
012345768:X
...

```

Denote `X` for the 1st player winning, `O` for the second player, and `D` for Draws.

There will be `9!` (362880) games.

Here is some data to verify your results.

```
'X' Wins: 212256
'O' Wins: 104544
Draws : 46080

```

This is a codegolf, and runtime should be within a minute. Have Fun!

**EDIT:** Removed excess details, and just print it on `stdout`. No need to create a file.

# Answer
> 3 votes
## Ruby 1.9, 201 characters

```
r=*[*l=0..8,0,3,6,1,4,7,2,5,8,0,4,8,2,4,6].each_slice(3)
w=->a{r.any?{|b|b&a==b}}
[*l].permutation(9){|a|u=[[],[]];i=-1
u[i%2]<<a[i+=1]while !((x=w[u[1]])||o=w[u[0]])&&i<8
puts a*""+":#{x ??X:o ??O:?D}"}

```

Slightly golfed so far. Takes about 45 seconds to complete here.

* Edit: (268 -\> 249) Write to stdout instead of a file
* Edit: (249 -\> 222) Don't pre-fill the array with each player's moves.
* Edit: (222 -\> 208) Shorter way to find out if a player won
* Edit: (208 -\> 213) Back to 213, the previous solution was too slow.
* Edit: (213 -\> 201) Some rearrangements, removed whitespace

# Answer
> 4 votes
## J, 124 chars

```
((],~':',~1":[){&'DOX'@(</+2*>/)@:(<./"1)@:(((2{m/.@|.),(2{m/.),m"1,>./)"2)@(<:@(>:%2|]),:(%(2|>:)))@(3 3$]))"1((i.!9)A.i.9)

```

X win, O win and Draw counts check out.

Was a bit painful to debug though. :)

# Answer
> 3 votes
## Haskell, 224 222 characters

```
import Data.List
p=sort.permutations
a(e:_:z)=e:a z;a z=z
[c,d]%(e:z)|any((`elem`words"012 345 678 036 147 258 048 246").take 3).p.a.reverse$e=c|1<3=[d,c]%z;_%[]='D'
main=putStr$p['0'..'8']>>=(\s->s++':':"OX"%inits s:"\n")

```

Alas, the `permutations` function from `Data.List` doesn't produce permutations in lexographic order. So I had to expend 6 characters on the sort.

# Answer
> 2 votes
## APL (139)

This can probably be shortened more, but it was hard enough as it is. Believe it or not, it runs in about 45 seconds on my computer (excluding the time it takes to output everything, when output to the screen).

```
↑{⊃,/(,/⍕¨⍵-1),':',{1∊T←↑{∨/↑{⍵∘{⍵≡⍵∧⍺}¨↓⍉(9⍴2)⊤⎕UCS'㗀㐇㔤㑉㔑㑔'}¨↓(M∘.≥M)∧[2]M∊⍵}¨↓⍉5 2⍴0,⍨⍵:'XO'[1+</+/T]⋄'D'}⍵}¨↓{1≥⍴⍵:↑,↓⍵⋄↑⍪/⍵,∘∇¨⍵∘~¨⍵}M←⍳9

```

Explanation:

* `M←⍳9`: Store in M the numbers from 1 to 9. Internally, this program uses 1..9 instead of 0..8.
* `{`...`}`: a function to get all permutations:
    + `1≥⍴⍵:↑,↓⍵`: if the length is smaller or equal to 1, return the argument as a matrix.
    + `⋄↑⍪/⍵,∘∇¨⍵∘~¨⍵`: otherwise, remove each character in  from , get the permutations of that, and add the character back in.
* `¨↓`: for each permutation...
* `{`...`}`: a function that gives the winner for that permutation:
    + `⊃,/(,/⍕¨⍵-1),':',{`...`}⍵`: get the permutation as a string, with all the numbers decreased by 1 (to get the required 0..8 output instead of 1..9), followed by a colon, followed by the character denoting the winner:
        - `⍉5 2⍴0,⍨⍵`: separate the moves by X from the moves by O. Because O has one move less than X, that space is filled by `0`, which is unused and so does not influence the result.
        - `{`...`}¨↓`: for both the X board and the O board, run the following function which determines whether there is a win in one of the nine timesteps:
            * `(M∘.≥M)∧[2]M∊⍵`: Generate a bitboard from the move numbers, and `and` this bitboard with the bitstrings `100000000`, `110000000` ... `111111111` to get the state of the board at each of the nine moments in time.
            * `{`...`}¨↓`: for each of these, run the following function:
                + `⍉(9⍴2)⊤⎕UCS'㗀㐇㔤㑉㔑㑔'`: get the bitboards for each possible winning situation
                + `⍵∘{⍵≡⍵∧⍺}¨↓`: `and` each winning state with the current bitboard and check if said winning state is still there
            * `∨/↑`: `or` these together, giving whether there is a win on this bitboard
        - `1∊T←↑`: make a 9x2 matrix, with the 9 X-timesteps on the first row and the 9 O-timesteps on the second row. Store this in T. If there is a 1 in this matrix, someone has won.
        - `:'XO'[1+</+/T]`: If someone has won, give 'X' or 'O' depending on whose `1` was first.
        - `⋄'D'`: If nobody has won, give 'D'.
* : make a matrix out of these so that they are each displayed on a separate row.

# Answer
> 1 votes
# Python 2.7 (237)

```
from itertools import*
for z in permutations('012345678'):
 k,F=0,[9]*9
 for h in z:
    F[int(h)]=k=1-k
    if any(sum(a)in(0,3)for a in(F[:3],F[3:6],F[6:],F[::3],F[1::3],F[2::3],F[::4],F[2:8:2])):break
 else:k=2
 print"".join(z)+':','OXD'[k]

```

# Answer
> 1 votes
# JavaScript (V8), 174 bytes

```
f=(j,w,p,x,o)=>(A=[-1,7,56,73,84,146,273,292,448],g=n=>!A.every(q=>q&n^q),w=w||g(x)|2*g(o),x+o)^511?A.map((_,i)=>x+o>>i&1||f(!j,w,[p]+i,x|!j<<i,o|j<<i)):print(p+':','DXO'[w])

```

Try it online!

Or see the statistics

### How?

We use 8 bit-masks stored in the array \\$A\\$ to identify all possible winning patterns. There's a dummy leading \\$-1\\$ in \\$A\\$ (which will always cause the test to fail) so that we have 9 entries. This allows us to re-use \\$A\\$ to iterate on all squares of the grid.

The bit-masks for X and O are stored in the variables \\$x\\$ and \\$o\\$ respectively. The variable \\$j\\$ is a flag telling which turn it is (*false* or *undefined* for X, *true* for O). The variable \\$w\\$ holds the winner (\\$0\\$ for draw, \\$1\\$ for X, \\$2\\$ for O) and may not be changed anymore once it's non-zero. The variable \\$p\\$ is the permutation of moves as a string.

# Answer
> 0 votes
# Python 3 \+ `golfing-shortcuts`, 211 bytes

```
from s import*
for Z in Im('012345678'):
 K,F=0,[9]*9
 for H in Z:
    F[int(H)]=K=1-K
    if a(s(A)in(0,3)for A in(F[:3],F[3:6],F[6:],F[::3],F[1::3],F[2::3],F[::4],F[2:8:2])):break
 else:K=2
 p(sj('',Z)+':','OXD'[K])

```

A port of Daniel's answer.

---
Tags: code-golf, kolmogorov-complexity, restricted-time, tic-tac-toe
---