title: Print all Country Codes

text:
# Question
Title: Print all Country Codes
ISO 3166-1 is the standard that defines all the country codes. The well-known two-letter codes (US, GB, JP, etc.) are called Alpha-2 codes.

With two letters, there are only 262 = 676 possible codes, which can be nicely arranged in a grid. This table can be useful as an overview, to see which codes are actually in use, reserved, etc.

This challenge is simple: you're to print all *assigned* codes of this grid to STDOUT, using plain ASCII, exactly as shown below:

```
AA    AC AD AE AF AG    AI       AL AM AN AO AP AQ AR AS AT AU    AW AX    AZ
BA BB    BD BE BF BG BH BI BJ    BL BM BN BO    BQ BR BS BT BU BV BW BX BY BZ
CA    CC CD    CF CG CH CI    CK CL CM CN CO CP    CR CS    CU CV CW CX CY CZ
            DE    DG       DJ DK    DM    DO                            DY DZ
EA    EC    EE EF EG EH             EM       EP    ER ES ET EU EV EW
                        FI FJ FK FL FM    FO       FR                FX
GA GB GC GD GE GF GG GH GI       GL GM GN    GP GQ GR GS GT GU    GW    GY
                              HK    HM HN          HR    HT HU
   IB IC ID IE                   IL IM IN IO    IQ IR IS IT IU IV IW IX IY IZ
JA          JE                      JM    JO JP
            KE    KG KH KI          KM KN    KP    KR             KW    KY KZ
LA LB LC       LF       LI    LK                   LR LS LT LU LV       LY
MA    MC MD ME MF MG MH       MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
NA    NC    NE NF NG    NI       NL       NO NP    NR    NT NU             NZ
OA                                  OM
PA          PE PF PG PH PI    PK PL PM PN          PR PS PT       PW    PY
QA                                  QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ
RA RB RC    RE       RH RI       RL RM RN RO RP       RS    RU    RW
SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO       SR SS ST SU SV    SX SY SZ
TA    TC TD    TF TG TH    TJ TK TL TM TN TO TP    TR    TT    TV TW       TZ
UA                UG          UK    UM                US                UY UZ
VA    VC    VE    VG    VI             VN                   VU
               WF                WL       WO          WS       WV
XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ
            YE                                           YT YU YV
ZA                                  ZM             ZR             ZW       ZZ

```

(If I made any mistakes copying it down, the table here in this post is normative for the challenge, not the one on Wikipedia.)

You may or may not use trailing whitespace in each line which doesn't contain the `*Z` code, but not beyond the 77th character in that line (i.e., at most, you can make it a rectangular block, ending in `Z`s and spaces). Also, you may or may not use a single trailing new line at the end.

This is code golf, so the shortest answer (in bytes) wins.

# Answer
> 7 votes
# CJam, ~~125~~ ~~122~~ 121 bytes

```
"^Kéÿ·^?{ÿ·¿oÂ^Ú^À:ð^×à^Cé^Dÿ^Ýú^À^K^V^G^Áïþ ,^@^K^ÍBù(^_+óÿþºMa^À^H^@#ï^\¨^@ÿÿ¦|¨ÿþ}íßÕ^Ø\"^Â^Nª^P ^D^R$?ÿÿð^À^AÂ^@!^I"256b2b'[,65>_m*]z{~S2*?}%26/Sf*N*

```

The above uses caret notation for control characters.

Printable version (**141 bytes**) for the online interpreter:

```
"J`ki4#'Tr{$V!AcG)\d6o+rW97;#1|jN!WXL%GRuqYos0xCaaBzYgN97DOA'f@#@k'867BrCc1h?&d0LBq[st0YW^?b2Jfx.&gG:O(&"31f-95b2b'[,65>_m*]z{~S2*?}%26/Sf*N*

```

---

### Example run

```
$ base64 -d > cc.cjam <<< Igvp/7d/e/+3v2/CmoA68JfgA+kE/536gAsWB4Hv/iAsAAuNQvkoHyvz//66TWGACAAj7xyoAP//pnyo//597d/VmFwigg6qECAEEiQ////wgAHCACEJIjI1NmIyYidbLDY1Pl9tKl16e35TMio/fSUyNi9TZipOKg==
$ LANG=en_US cjam cc.cjam
AA    AC AD AE AF AG    AI       AL AM AN AO AP AQ AR AS AT AU    AW AX    AZ
BA BB    BD BE BF BG BH BI BJ    BL BM BN BO    BQ BR BS BT BU BV BW BX BY BZ
CA    CC CD    CF CG CH CI    CK CL CM CN CO CP    CR CS    CU CV CW CX CY CZ
            DE    DG       DJ DK    DM    DO                            DY DZ
EA    EC    EE EF EG EH             EM       EP    ER ES ET EU EV EW
                        FI FJ FK FL FM    FO       FR                FX
GA GB GC GD GE GF GG GH GI       GL GM GN    GP GQ GR GS GT GU    GW    GY
                              HK    HM HN          HR    HT HU
   IB IC ID IE                   IL IM IN IO    IQ IR IS IT IU IV IW IX IY IZ
JA          JE                      JM    JO JP
            KE    KG KH KI          KM KN    KP    KR             KW    KY KZ
LA LB LC       LF       LI    LK                   LR LS LT LU LV       LY
MA    MC MD ME MF MG MH       MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
NA    NC    NE NF NG    NI       NL       NO NP    NR    NT NU             NZ
OA                                  OM
PA          PE PF PG PH PI    PK PL PM PN          PR PS PT       PW    PY
QA                                  QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ
RA RB RC    RE       RH RI       RL RM RN RO RP       RS    RU    RW
SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO       SR SS ST SU SV    SX SY SZ
TA    TC TD    TF TG TH    TJ TK TL TM TN TO TP    TR    TT    TV TW       TZ
UA                UG          UK    UM                US                UY UZ
VA    VC    VE    VG    VI             VN                   VU
               WF                WL       WO          WS       WV
XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ
            YE                                           YT YU YV
ZA                                  ZM             ZR             ZW       ZZ

```

# Answer
> 10 votes
# Python 2, 240 bytes

Straightforward binary encoding implementation.

```
R=range(26)
print"\n".join(" ".join(chr(65+r)+chr(65+c)if int("8hfxckgq1olihfa47x3rrdkojzkklec7qk1hp4ht6avmzxfg7c4uv14xe0pzvvg93x81ag2bf88v2w0p3p08g8nwtuktbwosj9dytset3qmhdl72v5u62nepapgabdqqu7x",36)&1<<c+r*26 else"  "for c in R)for r in R)

```

The script for generating the integer is quick and dirty:

```
codes="""AA    AC AD AE AF AG    AI       AL AM AN AO AP AQ AR AS AT AU    AW AX    AZ
BA BB    BD BE BF BG BH BI BJ    BL BM BN BO    BQ BR BS BT BU BV BW BX BY BZ
CA    CC CD    CF CG CH CI    CK CL CM CN CO CP    CR CS    CU CV CW CX CY CZ
            DE    DG       DJ DK    DM    DO                            DY DZ
EA    EC    EE EF EG EH             EM       EP    ER ES ET EU EV EW
                        FI FJ FK FL FM    FO       FR                FX
GA GB GC GD GE GF GG GH GI       GL GM GN    GP GQ GR GS GT GU    GW    GY
                              HK    HM HN          HR    HT HU
   IB IC ID IE                   IL IM IN IO    IQ IR IS IT IU IV IW IX IY IZ
JA          JE                      JM    JO JP
            KE    KG KH KI          KM KN    KP    KR             KW    KY KZ
LA LB LC       LF       LI    LK                   LR LS LT LU LV       LY
MA    MC MD ME MF MG MH       MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ
NA    NC    NE NF NG    NI       NL       NO NP    NR    NT NU             NZ
OA                                  OM
PA          PE PF PG PH PI    PK PL PM PN          PR PS PT       PW    PY
QA                                  QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ
RA RB RC    RE       RH RI       RL RM RN RO RP       RS    RU    RW
SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO       SR SS ST SU SV    SX SY SZ
TA    TC TD    TF TG TH    TJ TK TL TM TN TO TP    TR    TT    TV TW       TZ
UA                UG          UK    UM                US                UY UZ
VA    VC    VE    VG    VI             VN                   VU
               WF                WL       WO          WS       WV
XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ
            YE                                           YT YU YV
ZA                                  ZM             ZR             ZW       ZZ
"""
n = sum(1 << (x/3) for x in range(0, len(codes), 3) if codes[x] != " ")
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
    return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
print baseN(n, 36)

```

# Answer
> 6 votes
# Ruby, ~~269 246 241 235~~ 227

```
g="b6wapsm769n90ongzuvadg5vdat6ap7v1oyyie3j5wxbq9xtycezrtt9xamn9riqnnxnsxjx0al8uk8rmk5snb7quly7t5i9rkq21r1vnns5vdm7gwzqtxwwwmj02nqxlhl".to_i 36
l=*?A..?Z
676.times{|i|print g.to_s(2)[i]==?1?l[i/26]+l[i%26]:"  ",i%26==25?$/:" "}

```

`g` is a matrix where each cell that has a country code is a `1` and all others are `0`. All rows are written behind and the resulting binary number has been converted to a base 36 representation. Then I just iterate over all cells and check if the code shall be printed.

# Answer
> 4 votes
## CJam, ~~152 149 148 145 144 140~~ 139 bytes, printable

```
". QH%$ydK0]cg:WSSlFu0z>O$T1<hO)Q63@D7;\KDJ^!NQN!tFr'>x@*!nf`Ut<s=N_[\%Ec0AXXZ`hayqIi'qj)jnonEj!n(ZjpjW("31f-96b2b'[,65>_m*]z{~SS+?S}%52/N*

```

Thanks Dennis for pointers.

Pretty straightforward approach. **How it works:**

```
". Q .... jW("                "Push this string to stack. This is a compressed string"
                              "which results to a 26 by 26 grid of 0 and 1 representing"
                              "whether that block contains country code or empty space";
              31f-96b2b       "Remove 31 from ASCII code of each of the character,"
                              "treat the number array as of base 96 and convert it to"
                              "a base 2 number";
'[,                           "Create an array of characters of ASCII code 0 to 91";
   65>                        "Take last 26 characters, which are A to Z";
      _m*                     "Copy the array and create all combinations {XX|X ∈ [A,Z]}";
         ]z                   "zip the first 26*26 array of 1 and 0 with the above"
                              "26*26 array of XX such that the final array element"
                              "is like ([B XX]|B={0,1},X∈[A,Z])";
           {~SS+?S}%          "For element, unwrap it from array, put "  " to stack,"
                              "if first number is 1, take XX otherwise, the spaces"
                              "and put a single space after each element";
                    52/       "split the array into chunks of 52,i.e 26 XX and 26 spaces";
                       N*     "Join each chunk of 52 elements with new line"

```

Try it online here

(Now only if I knew how to do a non printable character version)

# Answer
> 3 votes
# JavaScript ES6, 336 322

```
a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
alert(r='tr20d,yxurj,soeyn,1migz,rbh14,5hqc,13w82y,z1c,iqx33,l8dmo,1swln,zokqa,tukfz,r8voh,jzd34,mflqi,jzjen,10gn1k,13ycc7,sn0bd,kbb0j,qm2hs,mvf4,13ydj3,18y9c,jzdah'.split(',').map((n,i)=>(1e10+(parseInt(n,36).toString(2))).slice(-26).replace(/./g,(m,j)=>+m?a[i]+a[j]+' ':'   ')).join('\n'))
```

The big string is each row put into binary (`1` if there was a country code there, `0` if not) and then base36. Try it out in Firefox at http://jsfiddle.net/twduhqz6/1/.

# Answer
> 2 votes
# Bash+coreutils, 361

Basic regex removal of the combos we don't want. Some mild compression of the regex:

```
a=({A..Z})
f=(BHJKVY CKP BEJQT A-DFHILNP-X BDI-LNOQX-Z A-HNPQS-WYZ JKOVXZ A-JLO-QSV-Z AF-KP B-DF-LNQ-Z A-DFJ-LOQS-VX DEGHJL-QWXZ BIJ BDHJKMNQSV-Y B-LN-Z B-DJO-QUVXZ B-L DFGJKQRTVX-Z PQW BEIQSUXY B-FH-JLN-RT-X BDFHJ-MO-TV-Z A-EG-KMNP-RTUW-Z _ A-DF-SW-Z B-LN-QS-VXY)
for i in ${!a[@]};{
s+="${a[i]}[${f[i]}]|"
}
echo {A..Z}{A..Z}|sed -r "s/Z /Z\n/g;s/${s%|}/  /g"

```

# Answer
> 2 votes
# Haskell, 357

Damn, this is kinda hard.

```
import Data.List.Split
az=['A'..'Z']
k=0x9084004380010ffffffc24482004085570414419abfbb7be7fff153e65ffff001538f7c400100186b25d7fffcfd4f8149f42b1d00034047ff781e068d0015fb9ff2097c007e90f5c015943f6fdedffdefeedff97d
l i (a:b)|i`mod`2>0=a:l(i`div`2)b|1>0="  ":l(i`div`2)b
l _ _=[]
main=putStr$unlines$chunksOf 78$unwords$l k[a:[b]|a<-az,b<-az]

```

Prints to STDOUT when compiled (thus the main). Using proper compression would make this a lot shorter... ideas welcome

# Answer
> 1 votes
# JavaScript (E6) 350

Not the right tool for this task (maybe thanks to *String.fromCharCode*?)

```
r=0,Q=x=>String.fromCharCode(x+64),
console.log("2dff97d 3ff7bfb 3f6fded 3005650 7e90f5 825f00 15fb9ff 1a3400 3ff781e d011 342b1d0 13e0527 3fffcfd 21ac975 1001 14e3df1 3fff001 54f997 3be7fff 26afeed 3041441 102155 244820 3ffffff 380010 2421001"
.replace(/\w+./g,x=>{for(x='0x'+x,s=c=o='',++r;++c<27;s=' ',x/=2)o+=s+(x&1?Q(r)+Q(c):'  ');return o+'\n'}))

```

# Answer
> 1 votes
## J, 172 chars (printable)

```
echo}:"1,.u:32+(26 26$,(6#2)#:34-~3 u:
'QKa]?a@a`YQXa$HJ"\^+AB"`F&a[Y\B"N8#Z)QaD"N""P/2QFJ)TQUaa\\58("$""E]STJ"1aaKITJaa[_]?a7H$,$%LJ2*"24+%aaaa$"">*"*2F'
)*0,"1~33+,"0/~i.26

```

Line breaks for legibility. Straightforward binary packing, with six bits per string character (offset 34 to get into the printable range as well as avoid `'`).

# Answer
> 1 votes
# Wolfram language, 244 ~~255~~ bytes

```
Table[Table[If[BitGet[36^^b6wapsm769n90ongzuvadg5vdat6ap7v1oyyie3j5wxbq9xtycezrtt9xam\n9riqnnxnsxjx0al8uk8rmk5snb7quly7t5i9rkq21r1vnns5vdm7gwzqtxwwwmj02nqxl\hl,675-i*26-j]==1,FromCharacterCode[{i,j}+65]<>" ","   "],{j,0,25}]<>"\n",{i,0,25}]<>""

```

The number from fireflame241's answer was used and repacked into 36-ary form.

No builtin country data were used.

# Answer
> 0 votes
# PHP, 323 Bytes

```
$p=explode(_,"^BHJKVY_^CKP_^BEJQT_EGJKMOYZ_ACE-HMPR-W_I-MORX_^JKOVXZ_KMNRTU_^AF-KP_AEMOP_EGHIMNPRWYZ_ABCFIKR-VY_^BIJ_ACEFGILOPRTUZ_AM_AE-IK-NR-TWY_AM-Z_A-CEHIL-PSUW_^PQW_^BEIQSUXY_AGKMSYZ_ACEGINU_FLOSV_\w_ETUV_AMRWZ");
foreach($r=range(A,Z)as$k=>$v)
foreach($r as$w)echo preg_match("#[{$p[$k]}]#",$w)?$v.$w:"  ","
"[$w>Y];

```

Try it online!

# Answer
> 0 votes
# Jelly, ~~121~~ ~~120~~ ~~112~~ 110 bytes

```
“VV&ØṖgḳeƘKo⁾lc<Ṗɗẋ⁾ÆȤ¡rżQ5¤ø^k&`v®tḊẒḂṁz®ṙṂþ°~7<¹ṢƝƒ4ṇæÇZt9ẈÇḞƲY!u`İŀo0*dḅḥmȯḊȧṛƓXĠƈṾ’Bx2ða»32øØAp`OFµỌs2s26G

```

Try it online!

*-8 bytes thanks to @Dennis*

*-2 bytes thanks to @Dennis's idea of Cartesian products*

### How it works

**Simple:** The program multiplies one big binary list with another big list to get most of the output, then formats it

**Medium:** The program encodes the big binary list

```
1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1

```

into one big number, encoding which country codes are assigned. Each element is multiplied element-wise by each element of every possible country code to get a list of all assigned country codes, which is then formatted to the output list.

**Lower level:**

The bulk of the program uses data encoded in:

```
“VV&ØṖgḳeƘKo⁾lc<Ṗɗẋ⁾ÆȤ¡rżQ5¤ø^k&`v®tḊẒḂṁz®ṙṂþ°~7<¹ṢƝƒ4ṇæÇZt9ẈÇḞƲY!u`İŀo0*dḅḥmȯḊȧṛƓXĠƈṾ’

```

It is a base-250 integer which holds the decimal number `233462323092263584350936137603939798267906095227198731310610883427614237299604158551774020670253062350084519623333781892392013977676150946873601610983221266427394582295973500719992107281184544524840476937`, which gets turned into the above binary list.

For brevity, let's call this value `c` and replace the long string with `c` in the explanation

```
cBx2ða»32øØAp`OFµỌs2s26G   - main link, takes no input
c                          -  literal value
 B                         -  convert this to binary to get a list
                                       representing which codes are assigned
  x2                       -   repeat each element twice
    ða»32                  - element-wise product (dealing with
                                       spaces) with...
         øØAp`OF           -  every possible country code in ASCII codes.
                µỌs2s26G   - format the output to be correct

```

# Answer
> 0 votes
## C, 373 bytes

```
main(i,j){char e[]="0BHJKVY|0CKP|0BEJQT|EGJKLMOYZ|0BDIJKLNOQXYZ|IJKLMORX|0JKOVXZ|KMNRTU|0AFGHIJKP|AEMOP|EGHIMNPRWYZ|ABCFIKRSTUVY|0BIJ|0BDHJKMNQSVWXY|AM|0BCDJOPQUVXZ|0BCDEFGHIJKL|0DFGJKQRTVXYZ|0PQW|0BEIQSUXY|AGKMSYZ|ACEGINU|FLOSV|0|ETUV|AMRWZ",*t,*p=e,*s="|";for(i=0;t=strtok(p,s);p=0,i++)for(j=0;j<27;j++)printf(j-26?!strchr(t,65+j)^(*t!=48)?"%c%c ":"   ":"\n",65+i,65+j);}

```

Try it online

# Answer
> 0 votes
## Wolfram language, 389 bytes

```
c=CountryData;r=Riffle;StringReplace[""<>r[#~r~" "&/@Array[CharacterRange["A","Z"][[{##}]]&,{26,26}],n="
"],{"GZ"|"WE"->"  ",x:("X"~~_~~" "|n)|##&@@(Cases[#~c~"CountryCode"&/@c[],_String]~Join~(""<>#&/@Partition[Characters@"AACPSXQNICRANTAPEAQPEPEUMQQRCSXQXDGCWLRNTPEVAQUMQVEWLRPIXDYUMQSUMQWVEFRBQYVIBXEMQMQOAQZRBLFRBUKRLIBVIUKGSSFXHRMQTFLIVIWOARIYVIZZRHMFIOAXJA",2,1])):>x,Except@n->" "}]

```

More readable:

```
c = CountryData; r = Riffle; StringReplace[
 "" <> r[#~r~" " & /@
    Array[CharacterRange["A", "Z"][[{##}]] &, {26, 26}],
   n = "\n"], {"GZ" | "WE" -> "  ",
  x : ("X" ~~ _ ~~ " " | n) | ## & @@ (Cases[#~c~"CountryCode" & /@
        c[], _String]~
      Join~("" <> # & /@
        Partition[
         Characters@
          "AACPSXQNICRANTAPEAQPEPEUMQQRCSXQXDGCWLRNTPEVAQUMQVEWLRPIXDY\
UMQSUMQWVEFRBQYVIBXEMQMQOAQZRBLFRBUKRLIBVIUKGSSFXHRMQTFLIVIWOARIYVIZZR\
HMFIOAXJA", 2, 1])) :> x, Except@n -> " "}]

```

Wolfram has an in-built list of ISO country codes, so this should be the perfect language for the job. However, it only knows about the country codes that are actually the codes for countries, and not the ones reserved for other uses, which are still included in this table. We therefore need to add a lot of the country codes in manually.

Explanation:

* `""<>r[r[#," "]&/@Array[CharacterRange["A","Z"][[{##}]]&,{26,26}],n="\n"]` is a string array of all pairs of letters from "A" to "Z".
* `#~c~"CountryCode"&/@c[]` (where `c=CountryData` is defined earlier) gives a list of all country codes that Wolfram Language knows about. A couple of these are `Missing["NotApplicable"]`, so we remove those with `Cases[...,_String]`.
* `(""<>#&/@Partition[Characters@"AACP...AXJA",2,1])` makes 83 of the remaining country codes manually using a 138-character string, where the pairs of adjacent characters are the required country codes. This string was found more or less by hand (with the help of the `FindPostmanTour` function!), and there is some repetition, so there's potentially more golfing to be done here.
* `StringReplace[ <full array> ,{"GZ"|"WE"->" ",x:("X"~~_~~" "|n)|##&@@( <known country codes> ~Join~ <extra codes> ):>x,Except@n->" "}]` first gets rid of two codes, "GZ" and "WE", which Wolfram thinks are country codes but aren't according to the table; then matches all codes starting with "X", plus the known codes and the ones we added manually, and replaces them with themselves; then finally everything else which isn't a newline and hasn't already been matched is turned into a space.

# Answer
> 0 votes
# Deadfish~, 9662 bytes

```
{iiiiii}iiiiicc{ddd}dddcccc{iii}iiiciic{ddd}dddddc{iii}iiiciiic{ddd}ddddddc{iii}iiiciiiic{dddd}iiic{iii}iiiciiiiic{dddd}iic{iii}iiiciiiiiic{dddd}icccc{iii}iiic{i}ddc{dddd}dccccccc{iii}iiic{i}ic{dddd}ddddc{iii}iiic{i}iic{dddd}dddddc{iii}iiic{i}iiic{dddd}ddddddc{iii}iiic{i}iiiic{ddddd}iiic{iii}iiic{i}iiiiic{ddddd}iic{iii}iiic{i}iiiiiic{ddddd}ic{iii}iiic{ii}dddc{ddddd}c{iii}iiic{ii}ddc{ddddd}dc{iii}iiic{ii}dc{ddddd}ddc{iii}iiic{ii}c{ddddd}dddcccc{iii}iiic{ii}iic{ddddd}dddddc{iii}iiic{ii}iiic{ddddd}ddddddcccc{iii}iiic{ii}iiiiic{{d}ii}c{iiiii}iiiiiicdc{ddd}dddc{iii}iiiicc{ddd}ddddcccc{iii}iiiiciic{ddd}ddddddc{iii}iiiiciiic{dddd}iiic{iii}iiiiciiiic{dddd}iic{iii}iiiiciiiiic{dddd}ic{iii}iiiiciiiiiic{dddd}c{iii}iiiic{i}dddc{dddd}dc{iii}iiiic{i}ddc{dddd}ddcccc{iii}iiiic{i}c{dddd}ddddc{iii}iiiic{i}ic{dddd}dddddc{iii}iiiic{i}iic{dddd}ddddddc{iii}iiiic{i}iiic{ddddd}iiicccc{iii}iiiic{i}iiiiic{ddddd}ic{iii}iiiic{i}iiiiiic{ddddd}c{iii}iiiic{ii}dddc{ddddd}dc{iii}iiiic{ii}ddc{ddddd}ddc{iii}iiiic{ii}dc{ddddd}dddc{iii}iiiic{ii}c{ddddd}ddddc{iii}iiiic{ii}ic{ddddd}dddddc{iii}iiiic{ii}iic{ddddd}ddddddc{iii}iiiic{ii}iiic{dddddd}iiic{iii}iiiic{ii}iiiic{{d}ii}c{iiiiii}dddcddc{ddd}dddcccc{iii}iiiiicc{ddd}dddddc{iii}iiiiicic{ddd}ddddddcccc{iii}iiiiiciiic{dddd}iic{iii}iiiiiciiiic{dddd}ic{iii}iiiiiciiiiic{dddd}c{iii}iiiiiciiiiiic{dddd}dcccc{iii}iiiiic{i}ddc{dddd}dddc{iii}iiiiic{i}dc{dddd}ddddc{iii}iiiiic{i}c{dddd}dddddc{iii}iiiiic{i}ic{dddd}ddddddc{iii}iiiiic{i}iic{ddddd}iiic{iii}iiiiic{i}iiic{ddddd}iicccc{iii}iiiiic{i}iiiiic{ddddd}c{iii}iiiiic{i}iiiiiic{ddddd}dcccc{iii}iiiiic{ii}ddc{ddddd}dddc{iii}iiiiic{ii}dc{ddddd}ddddc{iii}iiiiic{ii}c{ddddd}dddddc{iii}iiiiic{ii}ic{ddddd}ddddddc{iii}iiiiic{ii}iic{dddddd}iiic{iii}iiiiic{ii}iiic{{d}ii}c{ii}ii{c}cc{iii}iiiiiicic{dddd}iiicccc{iii}iiiiiiciiic{dddd}iccccccc{iii}iiiiiiciiiiiic{dddd}ddc{iii}iiiiiic{i}dddc{dddd}dddcccc{iii}iiiiiic{i}dc{dddd}dddddcccc{iii}iiiiiic{i}ic{ddddd}iii{cc}cccccccc{iii}iiiiiic{ii}ic{dddddd}iiic{iii}iiiiiic{ii}iic{{d}ii}c{iiiiii}dcddddc{ddd}dddcccc{iiii}dddcddc{ddd}dddddcccc{iiii}dddcc{dddd}iiic{iiii}dddcic{dddd}iic{iiii}dddciic{dddd}ic{iiii}dddciiic{dddd}{c}ccc{iiii}dddc{i}ddc{dddd}dddddccccccc{iiii}dddc{i}ic{ddddd}iicccc{iiii}dddc{i}iiic{ddddd}c{iiii}dddc{i}iiiic{ddddd}dc{iiii}dddc{i}iiiiic{ddddd}ddc{iiii}dddc{i}iiiiiic{ddddd}dddc{iiii}dddc{ii}dddc{ddddd}ddddc{iiii}dddc{ii}ddc{ddddd}dddddccccccccc{dd}ddc{ii}ii{cc}cccc{iiii}ddciiic{dddd}dc{iiii}ddciiiic{dddd}ddc{iiii}ddciiiiic{dddd}dddc{iiii}ddciiiiiic{dddd}ddddc{iiii}ddc{i}dddc{dddd}dddddcccc{iiii}ddc{i}dc{ddddd}iiiccccccc{iiii}ddc{i}iic{ddddd}{c}cccccc{iiii}ddc{ii}ddc{ddddd}ddddddcccccc{dd}ddc{iiiiii}icddddddc{ddd}dddc{iiii}dcdddddc{ddd}ddddc{iiii}dcddddc{ddd}dddddc{iiii}dcdddc{ddd}ddddddc{iiii}dcddc{dddd}iiic{iiii}dcdc{dddd}iic{iiii}dcc{dddd}ic{iiii}dcic{dddd}c{iiii}dciic{dddd}dccccccc{iiii}dciiiiic{dddd}ddddc{iiii}dciiiiiic{dddd}dddddc{iiii}dc{i}dddc{dddd}ddddddcccc{iiii}dc{i}dc{ddddd}iic{iiii}dc{i}c{ddddd}ic{iiii}dc{i}ic{ddddd}c{iiii}dc{i}iic{ddddd}dc{iiii}dc{i}iiic{ddddd}ddc{iiii}dc{i}iiiic{ddddd}dddcccc{iiii}dc{i}iiiiiic{ddddd}dddddcccc{iiii}dc{ii}ddc{dddddd}iiiccc{dd}ddc{ii}ii{cc}{c}{iiii}ciiic{dddd}dddcccc{iiii}ciiiiic{dddd}dddddc{iiii}ciiiiiic{dddd}dddddd{c}{iiii}c{i}c{ddddd}cccc{iiii}c{i}iic{ddddd}ddc{iiii}c{i}iiic{ddddd}ddd{c}ccccc{dd}ddc{ii}iiccc{iiii}ic{d}iiic{ddd}ddddc{iiii}icddddddc{ddd}dddddc{iiii}icdddddc{ddd}ddddddc{iiii}icddddc{dddd}iii{c}ccccccccc{iiii}iciiic{dddd}ddddc{iiii}iciiiic{dddd}dddddc{iiii}iciiiiic{dddd}ddddddc{iiii}iciiiiiic{ddddd}iiicccc{iiii}ic{i}ddc{ddddd}ic{iiii}ic{i}dc{ddddd}c{iiii}ic{i}c{ddddd}dc{iiii}ic{i}ic{ddddd}ddc{iiii}ic{i}iic{ddddd}dddc{iiii}ic{i}iiic{ddddd}ddddc{iiii}ic{i}iiiic{ddddd}dddddc{iiii}ic{i}iiiiic{ddddd}ddddddc{iiii}ic{i}iiiiiic{dddddd}iiic{iiii}ic{ii}dddc{{d}ii}c{iiiiii}iiiic{d}ic{ddd}ddd{c}{iiii}iicdddddc{dddd}iii{cc}cc{iiii}iiciiic{dddd}dddddcccc{iiii}iiciiiiic{ddddd}iiic{iiii}iiciiiiiic{ddddd}ii{cc}{c}{dd}ddc{ii}ii{c}cc{iiii}iiicddddddc{dddd}iiicccc{iiii}iiicddddc{dddd}ic{iiii}iiicdddc{dddd}c{iiii}iiicddc{dddd}d{c}{iiii}iiiciic{dddd}dddddc{iiii}iiiciiic{dddd}ddddddcccc{iiii}iiiciiiiic{ddddd}iicccc{iiii}iiic{i}dddc{ddddd}{c}ccc{iiii}iiic{i}iic{ddddd}dddddcccc{iiii}iiic{i}iiiic{dddddd}iiic{iiii}iiic{i}iiiiic{{d}ii}c{iiiiii}iiiiiic{d}dc{ddd}dddc{iiii}iiiic{d}c{ddd}ddddc{iiii}iiiic{d}ic{ddd}dddddccccccc{iiii}iiiicddddddc{dddd}iiccccccc{iiii}iiiicdddc{dddd}dcccc{iiii}iiiicdc{dddd}ddd{c}ccccccccc{iiii}iiiiciiiiiic{ddddd}c{iiii}iiiic{i}dddc{ddddd}dc{iiii}iiiic{i}ddc{ddddd}ddc{iiii}iiiic{i}dc{ddddd}dddc{iiii}iiiic{i}c{ddddd}ddddccccccc{iiii}iiiic{i}iiic{dddddd}iiiccc{dd}ddc{{i}ddd}dddc{d}ddc{ddd}dddcccc{iiii}iiiiic{d}c{ddd}dddddc{iiii}iiiiic{d}ic{ddd}ddddddc{iiii}iiiiic{d}iic{dddd}iiic{iiii}iiiiic{d}iiic{dddd}iic{iiii}iiiiicddddddc{dddd}ic{iiii}iiiiicdddddc{dddd}ccccccc{iiii}iiiiicddc{dddd}dddc{iiii}iiiiicdc{dddd}ddddc{iiii}iiiiicc{dddd}dddddc{iiii}iiiiicic{dddd}ddddddc{iiii}iiiiiciic{ddddd}iiic{iiii}iiiiiciiic{ddddd}iic{iiii}iiiiiciiiic{ddddd}ic{iiii}iiiiiciiiiic{ddddd}c{iiii}iiiiiciiiiiic{ddddd}dc{iiii}iiiiic{i}dddc{ddddd}ddc{iiii}iiiiic{i}ddc{ddddd}dddc{iiii}iiiiic{i}dc{ddddd}ddddc{iiii}iiiiic{i}c{ddddd}dddddc{iiii}iiiiic{i}ic{ddddd}ddddddc{iiii}iiiiic{i}iic{dddddd}iiic{iiii}iiiiic{i}iiic{{d}ii}c{{i}ddd}ddc{d}dddc{ddd}dddcccc{iiii}iiiiiic{d}dc{ddd}dddddcccc{iiii}iiiiiic{d}ic{dddd}iiic{iiii}iiiiiic{d}iic{dddd}iic{iiii}iiiiiic{d}iiic{dddd}icccc{iiii}iiiiiicdddddc{dddd}dccccccc{iiii}iiiiiicddc{dddd}ddddccccccc{iiii}iiiiiicic{ddddd}iiic{iiii}iiiiiiciic{ddddd}iicccc{iiii}iiiiiiciiiic{ddddd}cccc{iiii}iiiiiiciiiiiic{ddddd}ddc{iiii}iiiiiic{i}dddc{ddddd}ddd{c}ccc{iiii}iiiiiic{i}iic{{d}ii}c{{i}ddd}dc{d}ddddc{ddd}ddd{cc}{c}cccc{iiiii}dddcddc{dddd}ddddd{cc}{c}ccccccccc{dd}ddc{{i}ddd}c{d}dddddc{ddd}ddd{c}{iiiii}ddc{d}dc{dddd}iiic{iiiii}ddc{d}c{dddd}iic{iiiii}ddc{d}ic{dddd}ic{iiiii}ddc{d}iic{dddd}c{iiiii}ddc{d}iiic{dddd}dcccc{iiiii}ddcdddddc{dddd}dddc{iiiii}ddcddddc{dddd}ddddc{iiiii}ddcdddc{dddd}dddddc{iiiii}ddcddc{dddd}dddddd{c}{iiiii}ddciic{ddddd}c{iiiii}ddciiic{ddddd}dc{iiiii}ddciiiic{ddddd}ddccccccc{iiiii}ddc{i}dddc{ddddd}dddddcccc{iiiii}ddc{i}dc{dddddd}iiiccc{dd}ddc{{i}ddd}ic{d}ddddddc{ddd}ddd{cc}{c}cccc{iiiii}dcddddc{dddd}dddddc{iiiii}dcdddc{dddd}ddddddc{iiiii}dcddc{ddddd}iiic{iiiii}dcdc{ddddd}iic{iiiii}dcc{ddddd}ic{iiiii}dcic{ddddd}c{iiiii}dciic{ddddd}dc{iiiii}dciiic{ddddd}ddc{iiiii}dciiiic{ddddd}dddc{iiiii}dciiiiic{ddddd}ddddc{iiiii}dciiiiiic{ddddd}dddddc{iiiii}dc{i}dddc{ddddd}ddddddc{iiiii}dc{i}ddc{dddddd}iiic{iiiii}dc{i}dc{{d}ii}c{{i}ddd}iic{dd}iiic{ddd}dddc{iiiii}c{d}ddddddc{ddd}ddddc{iiiii}c{d}dddddc{ddd}dddddcccc{iiiii}c{d}dddc{dddd}iiiccccccc{iiiii}c{d}c{dddd}c{iiiii}c{d}ic{dddd}dccccccc{iiiii}cddddddc{dddd}ddddc{iiiii}cdddddc{dddd}dddddc{iiiii}cddddc{dddd}ddddddc{iiiii}cdddc{ddddd}iiic{iiiii}cddc{ddddd}iiccccccc{iiiii}cic{ddddd}dcccc{iiiii}ciiic{ddddd}dddcccc{iiiii}ciiiiic{ddddd}dddddccccccccc{dd}ddc{{i}ddd}iiic{dd}iic{ddd}dddc{iiiii}ic{dd}iiic{ddd}ddddc{iiiii}ic{d}ddddddc{ddd}dddddc{iiiii}ic{d}dddddc{ddd}ddddddc{iiiii}ic{d}ddddc{dddd}iiic{iiiii}ic{d}dddc{dddd}iic{iiiii}ic{d}ddc{dddd}ic{iiiii}ic{d}dc{dddd}c{iiiii}ic{d}c{dddd}dc{iiiii}ic{d}ic{dddd}ddc{iiiii}ic{d}iic{dddd}dddc{iiiii}ic{d}iiic{dddd}ddddc{iiiii}icddddddc{dddd}dddddc{iiiii}icdddddc{dddd}ddddddc{iiiii}icddddc{ddddd}iiiccccccc{iiiii}icdc{ddddd}c{iiiii}icc{ddddd}dc{iiiii}icic{ddddd}ddc{iiiii}iciic{ddddd}dddc{iiiii}iciiic{ddddd}ddddcccc{iiiii}iciiiiic{ddddd}ddddddc{iiiii}iciiiiiic{dddddd}iiic{iiiii}ic{i}dddc{{d}ii}c{{i}ddd}iiiic{dd}ic{ddd}dddcccc{iiiii}iic{dd}iiic{ddd}dddddc{iiiii}iic{d}ddddddc{ddd}ddddddcccc{iiiii}iic{d}ddddc{dddd}iic{iiiii}iic{d}dddc{dddd}ic{iiiii}iic{d}ddc{dddd}cccc{iiiii}iic{d}c{dddd}ddc{iiiii}iic{d}ic{dddd}dddc{iiiii}iic{d}iic{dddd}ddddc{iiiii}iic{d}iiic{dddd}dddddc{iiiii}iicddddddc{dddd}ddddddc{iiiii}iicdddddc{ddddd}iiic{iiiii}iicddddc{ddddd}iicccc{iiiii}iicddc{ddddd}cccc{iiiii}iicc{ddddd}ddcccc{iiiii}iiciic{ddddd}ddddc{iiiii}iiciiic{ddddd}dddddccccccc{iiiii}iiciiiiiic{{d}ii}c{{i}ddd}iiiiic{dd}c{ddd}ddd{c}cccccc{iiiii}iiic{d}ddddc{dddd}i{c}{iiiii}iiic{d}c{dddd}dddcccc{iiiii}iiic{d}iic{dddd}ddddd{c}cccccc{iiiii}iiicddc{ddddd}d{c}cccccc{iiiii}iiiciiiic{dddddd}iiic{iiiii}iiiciiiiic{{d}ii}c{{i}ddd}iiiiiic{dd}dc{ddd}dddcccc{iiiii}iiiic{dd}ic{ddd}dddddcccc{iiiii}iiiic{dd}iiic{dddd}iiicccc{iiiii}iiiic{d}dddddc{dddd}icccc{iiiii}iiiic{d}dddc{dddd}d{c}ccc{iiiii}iiiic{d}iic{dddd}dddddd{c}ccccccccc{iiiii}iiiicdc{ddddd}ddd{c}ccccc{dd}ddc{ii}ii{c}ccccc{iiiii}iiiiic{dd}iiic{dddd}ii{c}cccccc{iiiii}iiiiic{d}dc{dddd}ddddccccccc{iiiii}iiiiic{d}iic{ddddd}iii{c}{iiiii}iiiiicddddc{ddddd}dccccccc{iiiii}iiiiicdc{ddddd}dddd{c}cc{dd}ddc{{i}dd}ddc{dd}dddc{ddd}dddc{iiiii}iiiiiic{dd}ddc{ddd}ddddc{iiiii}iiiiiic{dd}dc{ddd}dddddc{iiiii}iiiiiic{dd}c{ddd}ddddddc{iiiii}iiiiiic{dd}ic{dddd}iiic{iiiii}iiiiiic{dd}iic{dddd}iic{iiiii}iiiiiic{dd}iiic{dddd}ic{iiiii}iiiiiic{d}ddddddc{dddd}c{iiiii}iiiiiic{d}dddddc{dddd}dc{iiiii}iiiiiic{d}ddddc{dddd}ddc{iiiii}iiiiiic{d}dddc{dddd}dddc{iiiii}iiiiiic{d}ddc{dddd}ddddc{iiiii}iiiiiic{d}dc{dddd}dddddc{iiiii}iiiiiic{d}c{dddd}ddddddc{iiiii}iiiiiic{d}ic{ddddd}iiic{iiiii}iiiiiic{d}iic{ddddd}iic{iiiii}iiiiiic{d}iiic{ddddd}ic{iiiii}iiiiiicddddddc{ddddd}c{iiiii}iiiiiicdddddc{ddddd}dc{iiiii}iiiiiicddddc{ddddd}ddc{iiiii}iiiiiicdddc{ddddd}dddc{iiiii}iiiiiicddc{ddddd}ddddc{iiiii}iiiiiicdc{ddddd}dddddc{iiiii}iiiiiicc{ddddd}ddddddc{iiiii}iiiiiicic{dddddd}iiic{iiiii}iiiiiiciic{{d}ii}c{ii}ii{c}cc{iiiiii}dddc{dd}c{dddd}iii{cc}{cc}ccc{iiiiii}dddcdddddc{ddddd}ddc{iiiiii}dddcddddc{ddddd}dddc{iiiiii}dddcdddc{ddddd}dddd{c}cc{dd}ddc{{i}dd}c{dd}dddddc{ddd}ddd{cc}{c}cccc{iiiiii}ddc{d}dddc{dddd}ddddd{c}ccc{iiiiii}ddc{d}iic{ddddd}{c}ccc{iiiiii}ddcdddc{ddddd}dddddccccccc{iiiiii}ddcc

```

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


# Question
Title: Put the line in the code you nut and shake it all up
Using one programming language write 5 single-line programs, each of which outputs a different line of the first verse to Harry Nilsson's 1972 song "Coconut" when run individually:

> Brother bought a coconut, he bought it for a dime
> His sister had another one, she paid it for a lime
> She put the lime in the coconut, she drank them both up
> She put the lime in the coconut, she drank them both up
> She put the lime in the coconut, she drank them both up

(full lyrics)

The last 3 lines have the same lyrics, so your last 3 programs might be as well.

There are 5 factorial or 120 ways these 5 single-line programs can be arranged one per line in a single 5-line program. You must optimize your single-line programs such that for as many of these 120 combinations as possible the 5-line program outputs the **entire verse in its proper order**, exactly as it appears above.

# Example

The simplest answer would have 5 single line print statements, the last 3 identical:

```
print('Brother bought a coconut, he bought it for a dime')
```

```
print('His sister had another one, she paid it for a lime')
```

```
print('She put the lime in the coconut, she drank them both up')
```

```
print('She put the lime in the coconut, she drank them both up')
```

```
print('She put the lime in the coconut, she drank them both up')
```

The output to the 5-line programs will be the verse in its proper order as long as the first two single-liners are in their correct places. Only 6 of the 120 possible arrangements accomplish this.

# Scoring

The submission with the most working cases out of all 120 wins. Tie breaker goes to the set of programs with the lowest cumulative byte count (newlines not counted). The example has 309 bytes.

# Details

* **Your programs may not read their own source code.** Nor should they read other external files or require a network connection.
* Output to stdout or closest alternative. You may also output to a file with the name of your choice.
* "Single-line programs" are strings that contain any characters except line terminators (you'll probably just need to worry about newlines) .
* When composing the single-liners into the 5-liners you should add exactly 4 newlines, one between each adjacent pair of single-liners. You may optionally add a trailing newline.

# Answer
> 10 votes
# CJam, 120 valid permutations, ~~334 299~~ 290 bytes

```
"She put the lime in the coconut, she drank them both up"N+
"Brother bought a coconut, he bought it for a dime"N+]$~
"She put the lime in the coconut, she drank them both up"N+
"His sister had another one, she paid it for a lime"N+]$~
"She put the lime in the coconut, she drank them both up"N+

```

Pretty simple logic:

* Put each line of the song in each of the 5 programs
* Wrap everything on stack in an array
* Sort the array
* Unwrap the array so that the next program can use the same logic
* In each step, we have the partial lyrics in an array. Luckily, sorting the array gives the correct order of the lyrics.

**UPDATE**: Turns out that you don't need the wrap-sort-unwrap cycle after the 3 similar and appearing at the end lines of the song. I can explain why if its not that apparent :)

# Answer
> 8 votes
# Prelude, 120 permutations, ~~2045~~ 2035 bytes

```
9-9-9-9-9-9-9-9-9-5-97+993++09-9-9-9-9-9-9-1-8992++96+209-9-9-9-9-9-9-1-94+58992++09-9-9-9-9-9-9-1-92+95+199+409-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-95+909-9-9-9-9-9-9-1-594+993+09-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-992++993++97+09-9-9-9-9-9-9-1-5809-4-                                                                          (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-594+9409-9-9-9-9-9-9-1-109-9-9-9-9-9-9-1-99+96+609-9-9-9-9-9-9-1-992++909-9-9-9-9-9-9-1-992++87993++96+209-9-9-9-9-9-9-1-5809-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-109-9-9-9-9-9-9-1-992++87993++96+209-9-9-9-9-9-9-1-99+58992++96+99+09-9-9-3-                                             (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-97+993++09-9-9-9-9-9-9-1-8992++96+209-9-9-9-9-9-9-1-94+58992++09-9-9-9-9-9-9-1-92+95+199+409-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-95+909-9-9-9-9-9-9-1-594+993+09-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-992++993++97+09-9-9-9-9-9-9-1-5809-4-                                                 (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-594+993+09-9-9-9-9-9-9-1-109-9-9-9-9-9-9-1-99+96+609-9-9-9-9-9-9-1-992++909-9-9-9-9-9-9-1-49197+09-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-595+96+09-9-9-9-9-9-9-1-99+58992++96+95+109-9-9-9-9-9-9-1-41809-9-9-9-9-9-9-1-99+5992++991++9991++09-9-9-9-9-9-9-1-991++909-9-6-                                                           (9+9+9+9+9+9+9+9+9+9+6+!)
9-9-9-9-9-9-9-9-9-5-97+993++09-9-9-9-9-9-9-1-8992++96+209-9-9-9-9-9-9-1-94+58992++09-9-9-9-9-9-9-1-92+95+199+409-9-9-9-9-9-9-1-58991++09-9-9-9-9-9-9-1-09-9-9-9-9-7-992++993++95+96+396+309-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-95+909-9-9-9-9-9-9-1-594+993+09-9-9-9-9-9-9-1-58992++09-9-9-9-9-9-9-1-992++993++97+09-9-9-9-9-9-9-1-5809-4-                                                                                (9+9+9+9+9+9+9+9+9+9+6+!)

```

This has ultimately convinced me that Prelude and CJam need a child. If it wasn't for Prelude's very limited instruction set, this submission would actually be very competitive, if it wouldn't even beat CJam.

The basic idea is the following

```
"push line 4"               print
"push line 1"print
"push line 3"          print
"push line 2"     print
"push line 5"                    print

```

In Prelude, each line is its own "voice" with its own stack, and these voices are executed in parallel. That is, in the full program, each line will just individually construct the string and at print it at the end. But due to the offsets of the print statements, the order of the lines doesn't matter at all for the order of the output, since execution is left-to-right, not top-to-bottom.

Now, why are the lines so long? Prelude only stores numbers on its stack. Furthermore, it can only push a single-digit number at a time, so larger numbers have to be constructed from addition and subtraction (there is no multiplication either or other arithmetic either). So the largest part of code is simply calculating and pushing the right character codes. To shorten this a bit, I offset them by `96`. At the end, to print, I loop until the stack is empty (i.e. a `0` is encountered), add 96 to each number, and print it.

Note that the strings are pushed in reverse, since they're printed from last to first character.

This assumes the Python interpreter with `NUMERIC_OUTPUT = False` (which is how the spec defines I/O).

I used the following CJam code to generate the string construction:

```
"Brother bought a coconut, he bought it for a dime
"W%{i96-_0<{zLa*9/:,'-*'-+0\+}{La*9/:,_,'+*W<}?}%

```

Lastly, just for fun, why I think this would be really short if Prelude had a concept of strings:

```
"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"N+!
"emid a rof ti thguob eh ,tunococ a thguob rehtorB"N+!
"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"N+!
"emil a rof ti diap ehs ,eno rehtona dah retsis siH"N+!
"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"N+!

```

Now the print statements `!` are already in the right order, so I wouldn't even need to offset them. I think I'll get down to implementing this some time.

# Answer
> 7 votes
# Ruby, 120 valid permutations, 430 bytes

```
$*[1]='His sister had another one, she paid it for a lime';a||=at_exit{puts($*-[p])}
$*[0]='Brother bought a coconut, he bought it for a dime';a||=at_exit{puts($*)}
$*[2]='She put the lime in the coconut, she drank them both up';a||=at_exit{puts($*-[p])}
$*[3]='She put the lime in the coconut, she drank them both up';a||=at_exit{puts($*-[p])}
$*[4]='She put the lime in the coconut, she drank them both up';a||=at_exit{puts($*-[p])}

```

Works in any order, or individually. Each line modifies global state, then sets a hook to be executed at the end of the program unless the hook has already been set.

# Answer
> 6 votes
# \>\<\>, 120 permutations, 703 bytes

```
<    /a"emid a rof ti thguob eh ,tunococ a thguob rehtorB"0a.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
<   / a"emil a rof ti diap ehs ,eno rehtona dah retsis siH"09.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
<  /  a"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"08.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
< /   a"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"07.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"
</    a"pu htob meht knard ehs ,tunococ eht ni emil eht tup ehS"06.#.!50padpacpabpaapa9pa8pa7p97p87p77p67p57p95p84p73p62p51"/////\\\\\>l0=?;o"

```

The one-liner restriction was pretty tough for a 2D language, so I had to find a way to make the most of the `.` teleport instruction.

The initial `<` makes program flow leftward, wrapping around and executing

```
"o;?=0l>\\\\\\/////"15p26p37p48p59p75p76p77p78p79p7ap8ap9apaapbapcapdap

```

This is a series of `p` (put) instructions which places chars until the board looks like this:

```
<    /<lyrics1>0a.#.!50<blah>
<   / <lyrics2>09.#.!50<blah>
<  /  <lyrics3>08.#.!50<blah>
< /   <lyrics4>07.#.!50<blah>
</    <lyrics5>06.#.!50<blah>
 /     \
  /    \
   /   \
    /  \
     / \
       >l0=?;o

```

The `#.!50` then flips program flow back to rightward again, before jumping to line 5. What follows is this:

* Following the `/` mirror on line 5 finds lyrics 5, which is pushed onto the stack. We then teleport to line 6.
* Following the `/` mirror on line 6 finds lyrics 4, which is pushed onto the stack. We then teleport to line 7.
* Following the `/` mirror on line 7 finds lyrics 3...

This happens until we push lyrics 1, at which point we teleport to line 10. This is a loop to print the whole stack until it is empty.

If only one line of the program is present, then the `\` mirrors do the same job as the teleports on each lyric line.

If the program is scrambled, then the explanation above still applies, so the program works for all permutations!

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

```
a=setTimeout;a(_=>a(_=>print`She put the lime in the coconut, she drank them both up`))
a=setTimeout;a(_=>a(_=>print`She put the lime in the coconut, she drank them both up`))
a=setTimeout;a(_=>a(_=>print`She put the lime in the coconut, she drank them both up`))
setTimeout(_=>print`His sister had another one, she paid it for a lime`)
print`Brother bought a coconut, he bought it for a dime`

```

Try it online!

Silly

# Answer
> 0 votes
# Deadfish~, 6 (it's probably not possible to do more)

```
{iiiiii}iiiiiic{iiiii}ddcdddciiiiic{d}ddcdddc{i}iiic{{d}ii}ddc{iiiiii}iiiiiic{i}iiiciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{iiiiii}iiiiic{dddddd}dddddc{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}ddd}iicdddc{{d}iii}ic{iiiiii}iiiiiic{i}iiiciiiiiic{d}ddddcic{i}iic{{d}ii}ddddc{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}c{i}dciiic{{d}ii}ddc{iiiiii}iiiiic{dddddd}dddddc{{i}ddd}ddciiiiiciiiic{d}iic

```

```
{iii}iic{iiii}c{iii}iiic{i}c{{d}ii}dddc{{i}dd}iiic{d}c{i}cic{d}dddddc{i}iiic{{d}ii}ddc{{i}ddd}iic{d}iiiciiic{{d}iii}iic{iiiiii}iiiiic{i}iiiciciiiiic{d}ddcdddc{i}iiic{{d}ii}ddc{{i}dd}dcdc{d}ic{dddddd}iiic{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}dd}c{d}dddddc{i}ddcdddddc{{d}iii}iic{{i}ddd}iiic{i}ic{{d}ii}ddddc{{i}ddd}c{i}dciiic{{d}ii}ddc{iiiiii}iiiiic{dddddd}dddddc{{i}ddd}iiiiiicdddciiiic{d}iic

```

```
{iii}iic{iiiii}ic{ii}icdddc{{d}iii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiiiicdddciiiic{d}iic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddc{i}iiiic{dd}iiic{i}iiicdddc{{d}iii}dddddc{{i}dd}iiiic{d}ddcdddc{i}ddc{{d}ii}iiic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}dd}iiiiicdddddc

```

```
{iii}iic{iiiii}ic{ii}icdddc{{d}iii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiiiicdddciiiic{d}iic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddc{i}iiiic{dd}iiic{i}iiicdddc{{d}iii}dddddc{{i}dd}iiiic{d}ddcdddc{i}ddc{{d}ii}iiic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}dd}iiiiicdddddc

```

```
{iii}iic{iiiii}ic{ii}icdddc{{d}iii}ic{{i}dd}ciiiiicdc{{d}ii}ddddc{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}iiiiiicdddciiiic{d}iic{{d}iii}ic{{i}ddd}iiiciiiiic{{d}ii}iic{{i}dd}iiiic{d}ddcdddc{{d}iii}ic{{i}ddd}dddc{i}iic{d}ddc{i}iicdc{i}dddcdc{{d}iii}ddc{d}ddc{{i}dd}iiic{d}dcdddc{{d}iii}ic{{i}ddd}ddc{i}iiiic{dd}iiic{i}iiicdddc{{d}iii}dddddc{{i}dd}iiiic{d}ddcdddc{i}ddc{{d}ii}iiic{iiiiii}iiiiiic{i}iiiciiiiic{d}ddc{{d}iii}ddc{{i}dd}iiiiicdddddc

```

This is so long.....

---
Tags: code-challenge, kolmogorov-complexity, source-layout
---


title: Remove common leading spaces

text:
# Question
Title: Remove common leading spaces
When coding in Python, sometimes you want a multiline string within a function, e.g.

```
def f():
    s = """\
    Line 1
    Line 2
    Line 3"""

```

<sup>(The backslash is to remove a leading newline)</sup>

If you try to actually print out `s`, however, you'll get

```
    Line 1
    Line 2
    Line 3

```

That's not what we want at all! There's too much leading whitespace!

## The challenge

Given a multiline string consisting of only alphanumeric characters, spaces and newlines, remove all common spaces from the beginning of each line. Each line is guaranteed to have at least one non-space character, and will have no trailing spaces. The output may not have extraneous whitespace, whether it be before or after the entire output or an individual line (with the exception of a single optional trailing newline).

Input may be via STDIN or function argument, and output may be via STDOUT or function return value. You **cannot** use any builtins which are designed to dedent multiline strings or perform this exact task, e.g. Python's `textwrap.dedent`.

This is , so the solution in the fewest bytes wins. Standard loopholes apply.

## Test cases

```
"a"                                  ->   "a"
"   abc"                             ->   "abc"
"   abc\n def\n  ghi"                ->   "  abc\ndef\n ghi"
"    a\n    b\n    c"                ->   "a\nb\nc"
"    a\n    b\n    c\nd"             ->   "    a\n    b\n    c\nd"
"   a   b\n     c     d\n    e f"    ->   "a   b\n  c     d\n e f"

```

For example, the last test case is

```
   a   b
     c     d
    e f

```

and should look like this after stripping leading spaces:

```
a   b
  c     d
 e f

```

# Answer
> 12 votes
# CJam, ~~20~~ 14 bytes

```
qN/_z{S-}#f>N*

```

**Algorithm**:

* We first split the input on newlines and take a copy (`qN/_`)
* Then the smallest column with non space character is calculated by transposing the newline separated array and then simply looking for the index of the first non-all-space row (`z{S-}#`)
* Then we simply remove that many characters away from each line (`f>`)
* Finally, we join by newline again (`N*`)

**Code Expansion**

```
qN/               e# Read the entire input and split it on newline
   _z             e# Take a copy and transpose rows with columns.
                  e# Now we would have a bunch of all space rows. These rows are the ones
                  e# we want to remove (in form of columns)
     {  }#        e# Get the index of the first item from the transposed array that returns
                  e# true for this block
      S-          e# From each part, remove spaces. If the part is all-space, it will return
                  e# an empty string, which is false in CJam. We finally will get the index
                  e# of the first non-all-space row (or column)
          f>      e# We take that index and remove that many characters from starting of each
                  e# row of the initial newline separated input
            N*    e# Join the array back using newlines and automatically print the result

```

Try it online here

# Answer
> 9 votes
# sed - 26 bytes

```
:;/(^|\n)\S/q;s/^ //mg;b

```

run with `-rz`

Pretty straightforward:

```
  /(^|\n)\S/q;           - quit if there is a line that starts with non-space
              s/^ //mg;  - remove exactly one space in each line
:;                     b - repeat

```

`-r` option turns on extended regexps, `-z` reads whole input as a single string (actually uses NUL-byte as line delimiter)

# Answer
> 8 votes
# Pyth, 19 18 17 14 bytes

```
jbu>R!rhCG6G.z

```

The implementation is pretty cool.

1. `u .z` grabs all lines of stdin in an array, puts it in `G`. Then it evaluates the inner body, puts the result in `G`, and keeps doing this until it no longer changes (fixed point).
2. `!rhCG6` transposes `G`, gets the first element of the transposed array (the first column), strips it of any whitespace, and checks if there are any non-whitespace characters left.
3. The value from 2 is a boolean, which can be seen as an int 0 or 1. `>R G` grabs this number and slices off that many characters off the left of each line in `G`. Step 1, 2 and 3 combined basically means that it will keep stripping off columns of whitespace until there is no pure whitespace column left.
4. `jb` joins the array of lines by newlines and prints it.

# Answer
> 7 votes
# SWI-Prolog, ~~233~~ ~~223~~ 217 bytes

```
a(A):-b(A,0,0,0,N),w(A,N,0).
b([A|T],P,K,M,N):-P=1,(A=10,b(T,0,0,M,N);b(T,1,0,M,N));A\=32,(M=0;K<M),b(T,1,0,K,N);I=K+1,b(T,0,I,M,N).
b(_,_,_,N,N).
w([A|T],N,P):-P<N,A=32,Q=P+1,w(T,N,Q);put(A),A=10,w(T,N,0);w(T,N,P);!.

```

**Edit**: Completely changed my answer. It now uses character codes instead of strings.

An example of calling this would be `a(` a b\n c d\n e f`).`, with backquotes. You may need to use double quotes `"` instead if you have an old SWI-Prolog distrib.

# Answer
> 5 votes
# Julia, ~~93~~ ~~92~~ 81 bytes

Saved 10 bytes thanks to Glen O.

```
s->for i=(p=split(s,"\n")) println(i[min([search(j,r"\S")[1]for j=p]...):end])end

```

This creates an unnamed function that accepts a string and prints to stdout.

Ungolfed + explanation:

```
function f(s)
    # Split s into an array on newlines
    p = split(s, "\n")

    # Get the smallest amount of leading space by finding the
    # position of the first non-space character on each line
    # and taking the minimum
    m = min([search(j, r"\S")[1] for j in p]...)

    # Print each line starting after m
    for i in p
        println(i[m:end])
    end
end

```

# Answer
> 4 votes
# Java, 159

Because there's a conspicuous lack of Java...

```
void f(String...a){int s=1<<30,b;a=a[0].split("\n");for(String x:a)s=(b=x.length()-x.trim().length())<s?b:s;for(String x:a)System.out.println(x.substring(s));}

```

It's just loops comparing length to trimmed length, then spitting out substrings. Nothing too fancy. For the scrollbar-impaired:

```
void f(String...a){
    int s=1<<30,b;
    a=a[0].split("\n");
    for(String x:a)
        s=(b=x.length()-x.trim().length())<s?b:s;
    for(String x:a)
        System.out.println(x.substring(s));
}

```

# Answer
> 4 votes
# Perl, 47 33

Thanks @ThisSuitIsBlackNot for suggestion to use Perl's implicit loop

```
#!/usr/bin/perl -00p
/^( +).*(\n\1.*)*$/&&s/^$1//mg

```

The above is scored as 30 bytes for the line of code + 3 for `00p` flags.

### Original version, as a function:

```
sub f{$_=@_[0];/^( +).*(\n\1.*)*$/&&s/^$1//mgr}

```

This puts the argument into `$_`, then attempts to greedily match whitespace that's present on all lines with `/^( +).*(\n\1.*)*$/` \- if successful, `$1` now contains the longest common prefix, and we execute the replacement `s/^$1//mgr` to delete it from the beginning of every line and return the resulting string.

### Test

```
$ cat 53219.data
   a   b
     c     d
    e f
$ ./53219.pl <53219.data
a   b
  c     d
 e f

```

# Answer
> 3 votes
# Python 2, ~~86~~ ~~79~~ 75 Bytes

This can almost definitely be shortened some more, but right now it's not bad.

*Thanks to xnor for saving 4 bytes!*

```
s=input().split('\n')
for k in s:print k[min(x.find(x.strip())for x in s):]

```

# Answer
> 3 votes
# Ruby: ~~77~~ ~~73~~ ~~70~~ ~~66~~ ~~65~~ ~~58~~ ~~57~~ 40 characters

```
f=->t{t.gsub /^#{t.scan(/^ */).min}/,""}

```

Sample run:

```
irb(main):001:0> f=->t{t.gsub /^#{t.scan(/^ */).min}/,""}
=> #<Proc:0x00000001855948@(irb):1 (lambda)>

irb(main):002:0> puts f["   a   b\n     c     d\n    e f"]
a   b
  c     d
 e f
=> nil

irb(main):003:0> f["   a   b\n     c     d\n    e f"] == "a   b\n  c     d\n e f"
=> true

```

# Answer
> 2 votes
# C#, 18 + 145 = 163 bytes

Requires (18 bytes):

```
using System.Linq;

```

Method (145 bytes):

```
string R(string s){var l=s.Split('\n');return string.Join("\n",l.Select(x=>string.Concat(x.Skip(l.Select(z=>z.Length-z.Trim().Length).Min()))));}

```

The method calculates the lowest amount of leading spaces on the lines and creates a new string built of all lines, with *N* chars skipped (where *N* is the previously calculated number).

# Answer
> 1 votes
## **C#, 149 bytes total**

Practically the same solution as ProgramFOX's, although the number of characters to trim is calculated manually.

```
using System.Linq;

```

And the function itself:

```
string D(string s){var l=s.Split('\n');int i=0;while(l.All(a=>a[i]==' '))i++;return string.Join("\n",l.Select(b=>b.Substring(i)));}

```

# Answer
> 1 votes
## bash + sed + coreutils, 74, 56, 55

### Test data

```
s="\
   a   b
     c     d
    e f"

```

### Answer

```
cut -c$[`grep -o '^ *'<<<"$s"|sort|line|wc -c`]-<<<"$s"

```

### Output

```
a   b
  c     d
 e f

```

# Answer
> 1 votes
# Python 3, 100

```
def f(s):t=s.split("\n");return"\n".join([c[min([len(c)-len(c.lstrip(" "))for c in t]):]for c in t])

```

# Answer
> 1 votes
# JavaScript, ES6, ~~89~~ 86 bytes

This one is totally using just RegEx matching and substitutions.

```
f=x=>eval(`x.replace(/(^|\\n) {${--`
${x}`.match(/\n */g).sort()[0].length}}/g,"$1")`)

// Snippet related stuff
B.onclick=x=>P.innerHTML=f(T.value)
```

```
<textarea id=T></textarea><br>
<button id=B>Trim</button>
<pre id=P></pre>
```

As always, Firefox only, since ES6. Will add ES5 version later.

# Answer
> 1 votes
# K, 31 bytes

```
{`0:(&/{(0;#*=x)@*x}'" "=x)_'x}

```

Takes input a list of strings and prints the result to stdout.

# Answer
> 1 votes
# Haskell, 52 bytes

```
unlines.until(any(/=' ').map head)(map tail).lines

```

Usage example: `unlines.until(any(/=' ').map head)(map tail).lines $ " abc\n def\n ghi"` -\> `" abc\ndef\n ghi\n"`

How it works:

```
                                           lines    -- split the input at newlines into a list of lines
        until                                       -- repeat the 2nd argument, i.e.
                                 map tails          -- cut off the heads of all lines
                                                    -- until the the first argument returns "True", i.e.
             any(/=' ').map head                    -- the list of heads contains at least one non-space
unlines                                             -- transform back to a single string with newlines in-between

```

# Answer
> 1 votes
# Python, 94/95

lambda (94 bytes):

```
f=lambda s:'\n'.join(l[min(l.find(l.strip()) for l in s.split('\n')):] for l in s.split('\n'))

```

def (95 bytes)

```
def f(s):l=s.split('\n');m=min(i.find(i.strip())for i in l);return '\n'.join(i[m:] for i in l);

```

# Answer
> 1 votes
# R, ~~118~~ 111 bytes

Using the wonderful string functions of R :) This is similar/same to other solutions already posted. Input is through STDIN and cats to STDOUT.

```
cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n')

```

Test and explanation

```
> cat(substring(a<-scan(,'',sep='|'),Reduce(min,lapply(strsplit(a,' '),function(x)min(which(x>''))-1))),sep='\n')
1:                  a<-scan(,'',sep='|') # get the input lines
2:                                                         strsplit(a,' ') # split lines on spaces
3:                                                  lapply(                ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line
4:                                      ,Reduce(min,                                                      ) # get the min of those
5:        substring(                                                                                ) # trim it off
6:    cat(                                                                                ,sep='\n') # output each line
7:
Read 6 items
              a<-scan(,'',sep='|') # get the input lines
                                                     strsplit(a,' ') # split lines on spaces
                                              lapply(                ,function(x)min(which(x>''))-1) # get min index - 1 for non space of each line
                                  ,Reduce(min,                                                      ) # get the min of those
    substring(                                                                                ) # trim it off
cat(                                                                                ,sep='\n') # output each line
>

```

# Answer
> 1 votes
# Julia, ~~72~~ ~~62~~ ~~61~~ ~~57~~ ~~54~~ 49 bytes

```
g=s->ismatch(r"^\S"m,s)?s:g(replace(s,r"^ "m,""))

```

Ungolfed:

```
g(s)=
if ismatch(r"^\S"m,s)       # Determines if there's a newline followed by something other than a space
                            # Note: the m in r"^ "m says to work in multiline mode.
    s                       # If there is, return the string as the final result.
else                        # otherwise...
    m=replace(s,r"^ "m,"")  # Remove first space after each newline, and space at start of string.
    g(m)                    # Feed back into the function for recursion
end

```

Older solution (57 bytes):

```
g(s)=ismatch(r"
\S","
"s)?s:g(replace(s,"
 ","
")[2:end])

```

Original solution (72 bytes):

```
g(s)=all([i[1]<33for i=split(s,"\n")])?g(replace(s,"\n ","\n")[2:end]):s

```

# Answer
> 1 votes
# k (24 bytes)

Takes a string as an argument and returns a string (with trailing new-line).

```
{`/:(&//&:'~^s)_'s:`\:x}

```

Example:

```
k) f:{`/:(&//&:'~^s)_'s:`\:x};
k) f"   a   b\n     c     d\n    e f"
"a   b\n  c     d\n e f\n

```

# Answer
> 1 votes
# 05AB1E, 10 bytes

```
|©ζ®gð*Ûζ»

```

Try it online!

# Answer
> 0 votes
# JavaScript (*ES6*) 56

Recursive, trying to remove one space at a time from each row until a non-space is found.

Test running the snippet below - being ES6, Firefox only

```
f=s=>(r=s.replace(/^./gm,x=>(k|=x>' ',''),k=0),k?s:f(r))

// Test
test=
[[ "a", "a" ]
,["   abc", "abc" ]
,["   abc\n def\n  ghi", "  abc\ndef\n ghi" ]
,["    a\n    b\n    c", "a\nb\nc" ]
,["    a\n    b\n    c\nd", "    a\n    b\n    c\nd" ]
,["   a   b\n     c     d\n    e f","a   b\n  c     d\n e f" ]]

var tb=''
test.forEach(t=>{
  t[2]=f(t[0])
  t[3]=t[2]==t[1]?'OK':'FAIL'
  tb+='<tr><td>'+t.join('</td><td>')+'</td></tr>'
})
B.innerHTML=tb
```

```
td { white-space: pre; font-family: monospace; border: 1px solid#444; vertical-align:top}
#I,#O { height:100px; width: 200px }
```

```
<b>Your test:</b>
<table><tr><td><textarea id=I></textarea></td>
<th><button onclick='O.innerHTML=f(I.value)'>-></button></th>
<td id=O></td></tr></table>
<b>Test cases:</b><br>
<table ><tr><th>Input</th><th>Expected</th><th>Output</th><th>Result</th></tr>
<tbody id=B></tbody></table>
```

# Answer
> 0 votes
# Gawk, 101 100

```
{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}

```

For example...

```
cat input.txt | gawk '{match($0,/^( +)/,t);if(t[1]<s||s==""){s=t[1]};z[NR]=$0;}END{for(r in z){sub(s,"",z[r]);print z[r]}}'

```

Output...

```
a   b
  c     d
 e f

```

# Answer
> 0 votes
# Stacked, noncompeting, 43 bytes

```
:lines'^ +'match$#'"!MIN' '*0# '^'\+''mrepl

```

Try it online!

This works by finding the amount of spaces at the beginning of each line (`'^ +'match$#'"!`), getting the minimum, repeat a space that many times, and replacing that with nothing on each line.

# Answer
> 0 votes
# Vim, ~~33~~, 31 bytes

```
qq/\v%^(\s.*\n?)*%$
:%s/.
@qq@q## Heading ##

```

Try it online!

Old version:

```
qq:g/\v%^(\s.*\n?)*%$/%s/.
n@qq@q

```

# Answer
> 0 votes
# Stax, 9 bytes

```
ü═≤+Σî║┘`

```

Run and debug it

# Answer
> 0 votes
# Python 3, 63 bytes

```
def f(s):return '\n'.join([l.strip() for l in s.splitlines()]);

```

# Answer
> -1 votes
## CoffeeScript, 112 bytes

```
f=(x)->(a=x.split "\n").map((v)->v[Math.min.apply(null,a.map((v)->(r=/^ +/.exec v)&&r[0].length))...]).join "\n"

```

# Answer
> -1 votes
## JavaScript (ES6), ~~106~~ 98 bytes

The newlines are necessary and are counted as 1 byte each:

```
f=x=>(a=x.split`
`).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join`
`

```

### Demo

As with other ES6 answers, they only work in Firefox at the moment.

```
f=x=>(a=x.split`
`).map(v=>v.slice(Math.min(...a.map(v=>(r=/^ +/.exec(v))&&r[0].length)))).join`
`

// For demonstration purposes
console.log = x => X.innerHTML += x + `\n<hr>`;

console.log(f("a"));
console.log(f("   abc"));
console.log(f("   abc\n def\n  ghi"));
console.log(f("    a\n    b\n    c"));
console.log(f("    a\n    b\n    c\nd"));
console.log(f("   a   b\n     c     d\n    e f"));
```

```
<pre id=X></pre>
```

# Answer
> -1 votes
# JavaScript ES6, 85 bytes

```
s=>s.split`
`.map(z=>z.slice(Math.min(...s.match(/^ */gm).map(l=>l.length)))).join`
`

```

The new lines are significant

ES5 Demo:

```
function t(s) {
  return s.split("\n").map(function(z) {
    return z.slice(Math.min.apply(0, s.match(/^ */gm).map(function(l) {
      return l.length;
    })));
  }).join('');
}

// Demo
document.getElementById('go').onclick = function() {
  document.getElementById('r').innerHTML = t(document.getElementById('t').value)
};
```

```
Input:
<br>
<textarea id="t"></textarea>
<br>
<button id="go">Run</button>
<br>Output:
<br>
<pre style="background-color:#DDD;" id="r"></pre>
```

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


title: (Σ*)² ⟲ Σ* (Round-Trip a String Pair)

text:
# Question
Title: (Σ*)² ⟲ Σ* (Round-Trip a String Pair)
We're back! And this time with an objective scoring criteria!

---

This is a challenge I thought of recently which I think is not hard but allows for a wide range of possible solutions. Seems like a perfect fit for the creativity of PPCG users :)

## Your Task

Define two functions `combine` and `separate` with respective types `String × String → String` and `String → String × String` such that `separate ∘ combine = id`.

More precisely, define two functions (or methods/procedures/etc), which I will refer to as `combine` and `separate`, and which exhibit the following characteristics:

* When invoked with a single string, `separate` produces two strings as results. (You may use any reasonable string type. Most languages don't canonically allow producing multiple values, so feel free to to do something equivalent, such as returning a 2-tuple or modifying two global variables.)
* When invoked with two strings, `combine` produces a single string as result. (You may accept input to `separate` in the same form that `combine` produces, or any other reasonable form.)
* For any two strings `a` and `b`, `separate(combine(a, b))` must result in two strings which are (structurally) equivalent to `a` and `b`.
* The above bullets are the *only* restrictions on `combine` and `separate`. So, for instance, `combine ∘ separate` need not be `id`, and `separate` can even be a partial function, if you like.
* The functions need not actually be named `combine` and `separate`

## Intent

My goal with this challenge is to inspire creative and interesting solutions. As such, in order to avoid priming/suggesting your thinking about how to solve this problem, I will not be providing test cases, and I **strongly** suggest that you do not look at the existing answers until you submit your own.

## Winning Criteria

This challenge is ; the answer with the lowest score wins. Score is defined as number of bytes, **except that it's -75% if** `combine ∘ separate = id` as well (i.e., if `combine` is bijective and `separate = combine⁻¹`).

For brownie points, also try making your solution, in principle,

* work on any alphabet rather than `char`, possibly including alphabets of size- 0, 1, or 2
* generalize nicely to \\$n\\$-tuples or lists

---

Have fun!

# Answer
# Jelly, 2 bytes

## `combine`

Try it online!

## `separate`

```
V

```

Try it online!

A boring, but short, solution. Uses Jelly's `repr` and `eval` atoms.

is the right-inverse of `V`, meaning that `ṾV` (the Jelly way of composing 2 functions) returns the argument unchanged. Therefore, if passed `[A, B]`, `ṾV` will return `[A, B]`

The first program takes input as a pair `[A, B]` and unevals it. The second takes a string as input and evals it as a Jelly program

---

Just a quick precursor on strings and Jelly. Jelly does not like strings. At all. Internally, strings are just lists of characters to Jelly, and when outputting, Jelly will do all it can to "mash" everything together so that it doesn't look like it should. An example that you'd expect to output `['a', 'b', 'c', 2]`, or even `['abc', 2]`. As such, the Footers of the two programs above contain code to print the strings as-is, as lists of characters. Unfortunately, this can make them difficult to read.

But how do the programs work? Well, most of the work is done by the `combine` function. The `separate` function is simply "eval the argument as Jelly code".

##

is a weird atom, as Jelly atoms go. It's entire purpose is to act as the inverse to `V` (as a side note, if an character has an "underdot" below it in Jelly, it's likely to be the "inverse" to the atom without that underdot. For example, `O`/ (ord/chr) or `Y`/ (join/split at newlines)) and the function it uses in the interpreter, `jelly_uneval`, is only used by one other atom, , which just prints the same value as .

However,  does a pretty good job at yielding some Jelly code that, when evaluated, yields it's argument. I won't break down into the exact details, but it's able to handle when string delimiters such as  are contained in the input, so is a pretty solid "uneval" atom, as these things go.
> 5 votes

# Answer
# , ~~280~~ ~~202~~ ~~207~~ 196 (39+157) bytes

*Edit: +5 bytes to fix bug pointed-out by ChartZ Belatedly*

**Combine, 39 bytes**

```
function(a,b,`-`=nchar)paste(-a,-b,a,b)

```

Try it online!

**Separate, 157 bytes**

```
function(x,`-`=nchar,s=substring,q=as.double(el(strsplit(x," "))[1:2]),y=s(x,sum(3,-q)))`if`(any(is.na(q))||-y!=sum(q)+1,c(x,""),s(y,c(1,q[1]+2),c(q[1],-y)))

```

Try it online!

Not bijective and probably not shorter than a Cantor-pairing based approach, but I like this because all the output is kind-of readable.

`combine` function calculates the lengths of strings `a` and `b`, encodes them as printable-ASCII, and prefixes them to the concatenated strings (with single space separators).
`separate` reads the characters before the first spaces, converts these to expected string-lengths, and splits-up the string accordingly. If there are any problems (which will almost always occur if the string wasn't contructed using `combine`) it outputs a zero-length second string.

---

# , ~~111~~ 84 (41+43) bytes

*Edit: -27 bytes by simply filling the first output string of 'separate' with an error message if the input string wasn't generated by 'combine'.*

**Combine, 41 bytes**

```
function(a,b)capture.output(dput(c(a,b)))

```

Try it online!

**Separate, 43 bytes**

```
function(x)c(try(eval(parse(t=x))),'')[1:2]

```

Try it online!

Still not bijective, but a bit more competitive at the cost of being boring. A loose port of ChartZ's Jelly eval-uneval approach, but adjusted so that it will yield 2 strings as output with any string, not just with `eval`-able  code.

`combine` function constructs a string expression representing  vector containing the two strings `a` and `b`.
`separate` tries to evaluate its argument as  code, and puts an error message into an output string if it fails. It then appends an empty string, and returns the first two elements (so non- code, as well as valid  code that would output more than one string-like return value, all finally output 2 strings).
> 2 votes

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

```
c=lambda *args:repr(args)
s=lambda x:eval(x)

```

Try it online!
> 1 votes

# Answer
# Husk, 59 (21+38) bytes -75% = score of 14.75

**Combine, 21 bytes:**

```
mcB128FS+ȯΣḣ+moB128mc

```

Try it online!

**Separate, 38 bytes**

```
momcB128₁B128mc
§e_o+₂¹-¹½S*→₂
÷2←√→*8

```

Try it online!

Bijective functions: each functions converts the input string(s) to a number by interpreting the codepoints in base-128, and then applies Cantor pairing to exchange between an integer and a pair of integers, before converting back to a string. This can result in strings that contain unprintable characters, so the following testing links use modified versions that output the codepoints:

separate to codepoints = converts "abcd" into the strings with codepoints \[6,5\] and \[1,24,21\]
combine from codepoints = converts that back to "abcd"

combine to codepoints = converts strings "abc" and "def" to the string with codepoints \[1,26,2,55,4,35,112\]
separate from codepoints = converts that back to "abc", "def"

Alternatively, here (combine (27 bytes); separate (44 bytes) - score of 17.75) are versions with input/output restricted to the printable ASCII values 32-126.
> 1 votes

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

```
import itertools as i
c=lambda a,b:(f:=chr(ord((sorted(a[-1:]+b[-1:])or'\x00')[-1])+1))+''.join(sum(i.zip_longest(a,b,fillvalue=f),start=()))
s=lambda x:(x[1::2].rstrip(x[0]),x[2::2].rstrip(x[0]))

```

Try it online!

Slightly less boring than my other try, at the expense of being much longer. Unfortunately `c(s(x))` might not return exactly the same string, if a different fill value is specified than automatically would be determined.

# How it works

`c`(ombine) interleaves the two strings, with input `a` on the even positions and input `b` on the odd positions. As the strings need not be of equal lenght the shortest one is padded with fill character `f`. This is determined by taking the last character of both strings, sorting them and then taking the next codepoint as fillvalue. This fill value is then also prepended to the output to tell separate which characters to strip.

`s` simply takes every other character from the second character on, and strips all occurences of the fill value that's stored in the first character of the input, and then does the same for every other character from the third character on.
> 1 votes

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


title: Calculate the Super-Logarithm

text:
# Question
Title: Calculate the Super-Logarithm
This should be a simple challenge.

Given a number \\$n \ge 0\\$, output the super-logarithm (or the \\$\log^\*\\$, log-star, or iterated logarithm, which are equivalent since \\$n\\$ is never negative for this challenge.) of \\$n\\$.

$$\log^\*(n) = \begin{cases} 0 & \text{ if } n \le 1 \\ 1 + \log^\*(\log(n)) & \text{ if } n \> 1 \end{cases}$$

This is one of the two inverse functions to tetration. The other is the super-root, which is in a related question.

### Examples

```
Input       Output
0           0
1           0
2           1
3           2
4           2
...
15          2
16          3
...
3814279     3
3814280     4

```

### Rules

* You do not need to support decimals, though you may.
* You need to support input of at least \\$3814280 = \left\lceil e^{e^e} \right\rceil\\$.
* **You may not hard-code the values like `3814280`. (Your program must *theoretically* support higher numbers.) I want an algorithm to be implemented.**
* Shortest code wins.

**Related OEIS**

# Answer
> 17 votes
# Jelly, 8 bytes

```
ÆlÐĿĊḊi1

```

Try it online! or verify all test cases.

### Background

We start by successively taking natural logarithms of the input and the subsequent results until the result no longer changes. This works because the extension of the natural logarithm to the complex plane has a fixed point; if **z = e-W(-1) ≈ 0.318 + 1.337i** – where **W** denotes the Lambert W function – we have **log(z) = z**.

For input **n**, after computing **\[n, log(n), log(log(n)), …, z\]**, we first apply the ceiling function to each of the results. Jelly's implementation (`Ċ`) actually computes the imaginary part of *complex* number instead, but we're not interested in these anyway.

Once the **k**th application of **log** yields a value less than or equal to **1**, `Ċ` will return **1** for the first time. The 0-based index of that first **1** is the desired result.

The straightforward implementation (compute 1-based index, decrement) fails because of edge case **0**, which does not have a **1** in its list of logarithms. In fact, for input **0**, the sequence of logarithms is

```
[0, None]

```

This is because Jelly's logarithm (`Æl`) is overloaded; it first tries `math.log` (real logarithm), then `cmath.log` (complex logarithm), and finally "gives up" and returns `None`. Fortunately, `Ċ` is similarly overloaded and simply returns it argument if it cannot round up or take an imaginary part.

Likewise, input **1** returns

```
[1, 0, None]

```

which may create problems in other approaches that do or do not involve `Ċ`.

One way to fix this problem is apply  (dequeue; removes first element) to the array of logarithms. This maps

```
0ÆlÐĿ -> [0, None]    -> [None]
1ÆlÐĿ -> [1, 0, None] -> [0, None]

```

so neither list has a **1** now. This way, finding the index of the first **1** will return **0** (not found), which is the desired output for inputs **0** and **1**.

### How it works

```
ÆlÐĿĊḊi1  Main link. Argument: n (non-negative integer)

  ÐĿ      Apply the following link until the results are no longer unique.
Æl          Natural logarithm.
          Return the array of all unique results.
    Ċ     Round all resulting real numbers up to the nearest integer. This takes
          the imaginary part of complex numbers and does nothing for non-numbers.
     Ḋ    Dequeue; remove the first item (n) of the array of results.
      i1  Find the first index of 1 (0 if not found).

```

---

This is one of the only three atoms in Jelly that are overloaded in a non-obvious manner.

# Answer
> 12 votes
# Jelly, 9 bytes

```
Æl>1$Ð¿L’

```

Try it online!

Test suite. (Slightly modified.)

### Explanation

```
Æl>1$Ð¿L’
     Ð¿    while loop, collect all intermediate results.
  >1$      condition: z>1
Æl         body: natural logarithm.
       L   length of the array containing all intermediate results,
           meaning number of iterations
        ’  minus one.

```

# Answer
> 8 votes
# Javascript, ~~45~~ ~~27~~ 26 bytes

```
l=a=>a>1&&1+l(Math.log(a))

```

Here is test suite (3rd rev)

Thanks @LeakyNun for saving 1 byte with conditional and then converting function to lambda, and @Neil for pointing out false is ok return value for \<=1 (changed test to be == instead of ===)

# Answer
> 7 votes
# C, 38 bytes

```
f(double n){return n>1?1+f(log(n)):0;}

```

Pretty self-explanatory.

Try it on ideone.

# Answer
> 6 votes
# Mathematica, 21 bytes

```
If[#>1,1+#0@Log@#,0]&

```

Recursive anonymous function. Takes an integer as input and returns its super-logarithm as output. Just uses the given definition.

# Answer
> 5 votes
# Pyth, 10 bytes

```
L&>b1hy.lb

```

Test suite.

This defines a function.

# Answer
> 5 votes
# Dyalog APL, 13 bytes

Direct translation of OP:

```
{⍵≤1:0⋄1+∇⍟⍵}

```

TryAPL online!

# Answer
> 5 votes
## Haskell, 23 bytes

```
l x|x>1=1+l(log x)|1<2=0

```

Usage example: `l 3814280` -\> `4`.

# Answer
> 4 votes
## 05AB1E, ~~16~~ 13 bytes

```
[Dî2‹#¼žr.n]¾

```

**Explanation**

```
              # implicit input n
[          ]  # infinite loop
 Dî2‹#        # break if n rounded up is less than 2
      ¼       # else, increase counter
       žr.n   # set next n = log(n)
            ¾ # push counter and implicitly print

```

Try it online

# Answer
> 4 votes
# , ~~21~~ ~~19~~ ~~18~~ 16 bytes

*Saved 2 bytes to Leaky Nun, 1 byte to Galen Ivanov, and 2 bytes to FrownyFrog!*

```
2#@}.(0>.^.)^:a:

```

Try it online!

## Test cases

```
ls =: >:@$:@^.`0:@.(<:&1)
   ls 0
0
   ls 1
0
   ls 2
1
   ls 3
2
   ls 4
2
   ls 15
2
   ls 16
3
   ls 3814280
4

```

# Answer
> 4 votes
# Python 3, 45 bytes

```
import math
s=lambda x:x>1and-~s(math.log(x))

```

For `x <= 1`, this returns `False` (which is `== 0` in Python).

# Answer
> 3 votes
# MATL, ~~15~~ 12 bytes

```
0`ZetG>~}x@q

```

Try it online! Or verify all test cases (slightly modified version to handle several inputs).

### How it works

Starting with 0, apply iterated exponentiation until exceeding the input. The output is the number of iterations minus 1.

```
0       % Push 0
`       % Do...while loop
  Ze    %   Exponential
  t     %   Duplicate
  G     %   Push input
  >~    %   Is current value less than or equal to the input? If so: next iteration
}       % Finally (code executed at the end of the last iteration)
  x     %   Delete
  @q    %   Iteration index minus 1
        % Implicitly end loop
        % Implicitly display stack

```

# Answer
> 3 votes
# Julia, 17 bytes

```
!x=x>1&&1+!log(x)

```

Try it online!

# Answer
> 3 votes
# Java 7, 47 bytes

```
int c(double n){return n>1?1+c(Math.log(n)):0;}

```

Try it online.

The recursive Java 7 style method above is 2 bytes shorter than an iterative Java 8 style lambda:

```
n->{int c=0;for(;n>1;c++)n=Math.log(n);return c;}

```

Try it online.

**Explanation:**

```
int c(double n){      // Method with double parameter and integer return-type
  return n>1?         //  If the input is larger than 1:
    1+                //   Return 1 +
      c(Math.log(n))  //   A recursive call with log(input)
   :                  //  Else:
    0;                //   Return 0 instead

n->{                  // Method with double parameter and integer return-type
  int c=0;            //  Create a counter, starting at 0
  for(;n>1;           //  Loop as long as the input is still larger than 1:
    c++)              //   Increase the counter by 1
    n=Math.log(n);    //   And update the input to log(input)
  return c;}          //  After the loop: return the counter as result

```

# Answer
> 2 votes
# Jelly, 8 bytes

```
-Ælß$Ị?‘

```

Straightforward implementation of the definition. Try it online! or verify all test cases.

### How it works

```
-Ælß$Ị?‘  Main link. Argument: x

     Ị    Insignificant; test if |x| ≤ 1.
      ?   If the result is 1:
-           Return -1.
          Else:
   $        Execute the monadic chain formed by the two links to the left.
Æl            Apply natural logarithm to x.
  ß           Recursively call the main link.
       ‘  Increment the result.

```

# Answer
> 2 votes
# R, ~~38~~ 37 bytes

```
f=function(x)if(x>1)1+f(log(x))else 0

```

Thanks @user5957401 for the extra byte!

Test cases:

```
> f(0)
[1] 0
> f(1)
[1] 0
> f(2)
[1] 1
> f(3)
[1] 2
> f(4)
[1] 2
> f(3814279)
[1] 3
> f(3814280)
[1] 4

```

# Answer
> 2 votes
# MATLAB / Octave, 44 bytes

`function a=g(n);a=0;if n>1;a=1+g(log(n));end`

Tried to do it all as one anonymous function, but I forgot that MATLAB/Octave continues to evaluate expressions even if they are multiplied by a boolean false (zero) value:

`f=@(n)(n>1)*(1+f(log(n)))`

# Answer
> 2 votes
**Mathematica, 29 bytes**

Simple as all hell, and works for comically large as well as negative inputs:

```
f[x_]:=If[x>1,1+f[Log[x]],0]

```

# Answer
> 2 votes
# , 34 bytes

```
f=pryr::f(`if`(n>1,1+f(log(n)),0))

```

Try it online!

A non-recursive approach is possible: **36** bytes and takes input from stdin.

```
n=scan()
while((n=log(n))>0)F=F+1
+F

```

# Answer
> 1 votes
## Emacs Lisp, 38 bytes

```
(defun l(n)(if(> n 1)(1+(l(log n)))0))

```

Testcases:

```
(mapcar 'l '(0 1 2 3 4 15 16 3814279 3814280))
;; (0 0 1 2 2 2 3 3 4)

```

# Answer
> 1 votes
## Perl 5, 35 bytes

Very simple, requires `-M5.016` (which is free) to enable the `__SUB__` keyword for anonymous recursion.

```
sub{$_[0]>1?1+__SUB__->(log pop):0}

```

Another alternative is

```
sub{$_[0]>1?1+__SUB__->(log pop):0}

```

which is 34 bytes, and gives the same output for all inputs \> 1, but returns the special false value for inputs \<= 1. False is numerically equal to zero, but prints as "" (empty string), so it probably doesn't qualify.

# Answer
> 1 votes
## CJam (16 bytes)

```
rd{_1>}{_ml}w],(

```

Online demo

Simple while loop with pre-condition. (What I really want here is a Golfscript-style unfold operation, but CJam doesn't have one, and floating point in GolfScript is messy and not at all golfy).

# Answer
> 1 votes
# PARI/GP, 24 bytes

Just the straightforward recursion.

```
f(n)=if(n>1,1+f(log(n)))

```

# Answer
> 1 votes
# Racket, 61 bytes

```
(λ(x)(letrec([a(λ(b)(if(> b 1)(+ 1 (a(log b)))0))])(a x)))

```

# Answer
> 1 votes
# Maple, ~~32,30~~ 29 bytes

```
f:=x->`if`(x>1,1+f(log(x)),0)

```

Test cases:

```
> f(0.);
  0
> f(1.);
  0
> f(2.);
  1
> f(3.);
  2
> f(4.);
  2
> f(3814279.);
  3
> f(3814280.);
  4

```

# Answer
> 1 votes
# R, 36 bytes

Slightly different approach from Plannapus

```
->n;a=0;while(n>1){a=a+1;n=log(n)};a

```

Uses a right assign to run the code -- so the desired number must precede it. i.e.

```
10->n;a=0;while(n>1){a=a+1;n=log(n)};a

```

# Answer
> 1 votes
# Whispers v3, 9 bytes

```
>> ln*(L)

```

Try it online!

Note that I had to push a bug fix in order to make this work. The `ln*` function had already been added before September 1st 2020, but I hadn't noticed a bug in the parsing that was fixed today

This is a function, going by the standards defined here for Whispers functions. It can be called by appending the code in the Footer to the file.

Whispers v3 also has the `slog`, `lg*` (uses \\$\log\_2\\$) and `log*` (uses \\$\log\_{10}\\$) functions

# Answer
> 0 votes
### Ruby, 29 bytes

```
l=->n{n<=1?0:1+l[Math.log n]}

```

# Answer
> 0 votes
# Perl 6, 21 bytes

```
{($_,*.log...1>=*)-1}

```

Try it online!

The parenthesized expression is a sequence. `$_`, the argument to the function, is the first element. `*.log` generates each successive element by taking the log of the previous element. The sequence continues until the ending condition, `1 >= *`, is true: 1 is greater than or equal to the current element. Subtracting 1 from the sequence coerces it to a number: its length.

---
Tags: code-golf, math
---