title: Baba is golf, flag is win

text:
# Question
Title: Baba is golf, flag is win
If you haven't played the game Baba is You, I think you really should. Whether you’ve played it or not, have a go at implementing it as a code golf.

The idea behind this challenge is to have a bit more complicated, non-standard task with a bit longer answers.

## Game rules

Alas, the challenge is not to implement the entire game, impressive though that may be (I'm sure there is a single 05ab1e instruction for it. If not, someone should submit an issue. It's a gross omission from the language ). This will be a simplified version of the game:

* There are only 3 entities: `Baba`, `Rock` and `Flag` and the corresponding nouns (*lowercase* `baba`, `rock` and `flag`)
* There is only one operator - `is`
* There are only 3 properties: `you`, `win` and `push`
* Everything is always `stop` (N.b. `stop` is not a property which exists on the board) This prevents anything from overlapping and makes the management of the game grid simpler.
* *Because* everything is always `stop`, there is an alternate win condition. You can win if:
    + `noun is you` and `noun is win` -- just like in the original
    + `noun` which is `you` attempts to push something which is `win`, but that something cannot move (whether because it's not `push`, or it is `push` and is somehow blocked form moving). See examples for more details.
* Just like in the main game text (nouns `you`, `win` and `push` and the operator `is`) are always `push`
* There is only one level. This one:

```
. . . . . . . . . . . . .
. r i p . . . . R R R . .
. . . . . . . R . . . R .
. b i y . B . R . F . R .
. . . . . . . R . . . R .
. f i n . . . . R R R . .
. . . . . . . . . . . . .

```

where uppercase letter correspond to entities and lowercase to their respective nouns. `.` is empty, `p` is `push`, `y` is `you` and `n` is `win` (originally I've implemented walls, and there was a namesake crash so I've made win `n` instead).

* The grid is parsed for rules just like in the original game. There are two types of rules:
    + `noun is property`, for example `baba is you` or `flag is push`. These type of rules are referred to as *behaviours*.
    + `noun is noun`, for example `baba is rock`. These type of rules are referred to as *swaps*. Since this grid does not have two of any of the nouns, one does not have to worry about the case like `rock is rock` (which would, otherwise, affect the execution of other rules)
* The rules work only from left to right, and from top to bottom.
* The only allowed moves are up, down, left and right. No idle, no undo.
* When a move is made, every entity which is `you` attempts to move in the direction specified.
* The order of actions in a single step is as follows:
    + Search the grid for all the current rules
    + Parse the rules into behaviours and swaps
    + Apply all the swaps to the grid in an alphabetical order *(Only one swap per cell)*
    + Perform an action for the turn according to the behaviours

Here is an example game where the rule `rock is push` has been changed into `rock is win`.

## Golfing challenge rules

Your task is to implement the above game of Baba is You, using the smallest number of source code bytes (the usual). Your program will take a sequence of moves as an input, and output `1`, or `True`, or otherwise something meaningful if this sequence of moves leads to a victory on the above grid (and only on this grid. Just hardcode it in). Otherwise, the program will output `0`, or `False` or nothing.

You can assume that every sequence of moves is a *valid* sequence in any format. I've used symbols `^V<>^` for example, but you're most welcome to assume it's `udlr` instead.

You can assume any input sequence either ends on a win, or does not lead to one. This means you do not have to worry about there being any more moves past the winning one. If such sequence is passed to your program, it's an undefined behaviour and your program can do anything.

I've implemented this version of the game in python. You can find it here. Some of the more tricky behaviour is specified in the readme (If you find any weird edge cases I haven't thought of let me know or send me a PR). There is a minimal self-contained version of the code in `/golf/golfing_full.py` and the abbreviated version in `/golf/golfing_short.py`. The sum total comes to 1930 bytes (sans the test at the end).

## Test cases

```
- Fastest win
1: >>^>>V
- Fastest loss (you don't actually have to check for loss explicitly)
0: <^<V
- Baba is win
1: <VV<V<<^V>>^<
- Rock is baba
1: <^^^<<V>V<>>
- Rock is you
1: <^^^<<V^<<VV>><<^>><<
- Rock is win
1: <VVV<^<^>V>^^V<<<<^^^>^>>>>VVV<^>>>
- Rock is win but also push
1: <^<<<<V>>>V>VV<<^^^>^<VV>>V<V<^^>^<V>>>>>>>V<^^^^>^<<<<<<<<<
- Baba is flag
0: <V<<<<V>>V>^^>>^^>>^>>V
- Baba is you is win
0: <V<<<<V>>V>>^^VV>^^
- Flag is rock is win
1: <V<<V^<V>>>^^<^>^^<<V^<<VV>>>^>VVVV^^^<<<<^>>^>VVVV>>V^<<V>>^^>>
- Flag is rock is win, but win on what used to be the flag
1: >VV>^^<^>V>^VV<<<<<<<V^>V>>^>V^^<<^>^^<<V^<<VV>>>^>VVVV^^^<<<<^>>^>VVVVV^^>>>>>>
- Rules don't work upside down
0: <V<<<<V>>V>>>^V<<<^>V>>^V<<^>V>>^^^>>^>>V
- Rules don't work backwards
0: <V<<<<V>>V>>>^V<<<^>V>>^V<<^>><^^^>V>V<^<V<VV>>>>^<<<>^^>>^>>V
- Rules (swaps) are applied alphabetically
1: <^<<<<V>>^<<^^>>V^<<VV>>^><V><V><<<VVV>^^<^>>V>^^<^>VVV>VV<<^^^<^>V>^<^>><<V<<^>>>>>V<^<VV<<
- Rules (swaps) are applied alphabetically, case 2
1: <^<<<<V>>^<<^^>>VV<V>V>>VV<<^V<<^>^^^<^>^>VV>V<V<V>^^>V>V>>>^^<<
- Rock is baba is flag
0: <^^^<<V^<<V><VVVVV>>^V<<^>^<^><
- Rock is baba is flag, case 2
0: <^^^<<V^<<V>>>><<<V>>><<<<VVVV>>^V<<<^^>>>><<<<V>>>><<<<^^>>>><
- Walk into the corner for a while and make a circle around the board
1: VVVV>>>>>>>>^^^^^^^>^^>^>^<<<<<<<<<<<<<VVVVVVV^^>>>>>>>>^>
- Win at the last moment
1: >>V>V<<<V<<<^V<<^><^^^^^>>V^<<V><VV><

```

# Answer
# Python, ~~1930~~ ~~1927~~ 1686 bytes

* 1927 (-3) by replacing tabs with spaces
* 1686 (-241) Thanks to @pppery (silently ignoring errors)

This is the 'proof-of-principle' solution. I'm sure some more bytes can be shaved off with better eval tricks.

Expanded code + explanation

Try it online! \<- With the tests appended at the end

```
e=enumerate;v=reversed;t=tuple;z=zip
P=t('ypn');N=t('bfr');E=t('BFR')
exec('''exec('ip%sxP;io%sxN;ie%sxE;tr%s[c cz(*x)];f%s[t(v(r))rx]'%(('=lambda x:',)*5))
exec('rp%sf(tr(g));rm%str(f(g));rh%sf(tr(f(tr(g))));rz%sg'%(('=lambda g:',)*4))
from collections import deque
def et(seq):
 w=deque(maxlen=3);i=3
 _map(w.append,seq):
  i-=1
  if not i:i=1; yield t(w)
def F(g):
 iu=lambda t:(io(t[0])and t[1]=='i')and(io(t[2])or ip(t[2]));s=[]
 rg:
  tet(r):if iu(t):s.append((t[0],t[2]))
 cz(*g):
  tet(c):if iu(t):s.append((t[0],t[2]))
 sorted(s)
def R(r):
 b={n:dict(z(P,(False,)*3))nN};s=[]
 j,ar:
  if ip(a):b[j][a]=True
  else:s.append((j,a))
 b,sorted(s)
def at(p,b):
 len(p)or Z
 if p[0]=='.':p
 elif len(p)==1:Z
 h=lambda c:(ie(c)and b[c]['p'])or c(*P,*N,'i')
 if not h(p[0]):Z
 if p[1]=='.':(p[1],p[0],*p[2:])
 else:q=at(p[1:],b);(q[0],p[0],*q[1:])
S=t('^V<>')
qp=dict(z(S,(rz,rh,rp,rm)));qm=dict(z(S,(rz,rh,rm,rp)))
def T(g,b,s):
 g=qp[s](g);h=[['.'_r]rg];iy=lambda c:ie(c)and b[c]['y'];iw=lambda c:ie(c)and b[c]['n']
 j,re(g):
  k,celle(r):if not iy(cell):h[j][k]=cell;continuep=[h[l][k]lv(range(j))]try: q=at(p,b) l,me(v(q)):h[l][k]=m h[j-1][k]=cellexcept: len(p)and iw(p[0])and Z h[j][k]=cell
 qm[s](h)
def S(g,s):
 h=[[c cr]rg]
 a,bs:
  j,re(g):k,ce(r): if ie(c)and c==a and h[j][k]is c:h[j][k]=b.upper()
 h
def Y(q):
 g=[[c cr]r('.'*13+'|.rip....RRR..|.......R...R.|.biy.B.R.F.R.|.......R...R.|.fin....RRR..|'+'.'*13).split('|')]
 try:
  p(*q,None):b,s=R(F(g))nb: if b[n]['y']and b[n]['n']:Zg=S(g,s)if p:g=T(g,b,p)
 except:1
 0'''.translate({2:"for ",3:"return ",4:".lower()",5:" in ",6:"\n   "}))

```
> 7 votes

# Answer
# Python 3, ~~707~~ ~~646~~ 615 bytes

```
e=enumerate
S=eval(input())
exec('''g=[[int(k/10**i)%10FiIrange(11,-2,-1)]FkI[0,71800004440,40004,51902040304,40004,61000004440,0]];g[5][3]=10
R=lambda a,b:(4<a<8)*any([*r[i:i+3]]==[a,1,b]FrI[*g,*zip(*g)]Fi,pIe(r[2:]))
FsIS:
 G=[[([b-3FbI(5,6,7)if R(c+3,b)]+[c])[0]FcIr]FrIg]
 F_I' '*s:G=[*zip(*G)][::-1]
 Fj,rIe(G):
  r=G[j]=[*r]
  Fk,CIe(G[j]):
   l=0
   if R(C+3,9):
    Fi,cIe(r[:k]):l=(c<2or c>4or R(c+3,8))and[l,i+1][c<1]
    if l<1:0<k and R(r[k-1]+3,10)and E
    else:r[l-1:k]=r[l:k+1];r[k]=0
 g=G
 F_Irange(s):g=[*zip(*g[::-1])]
 FaI5,6,7:R(a,10)and R(a,9)and E'''.replace("I"," in ").replace("F","for "))

```

Try it online! (all testcases, simulates stdin)

Essentially a rewrite from the ground up, loosely based on MarcinKonowalczyk's `golfing_full.ipynb`.

Takes input through STDIN as a list of integers, where 0,1,2,3 correspond to left, up, right, down respectively. Throws an error on win and does not throw on loss as per this default.

* -61 bytes: use integers instead of characters, take input through STDIN instead of as function, other small changes
* -31 bytes: exec-replace on `for`  and  `in`

### Ungolfed

```
def grid_has_rule(grid, rule):
    return any(rule in ''.join(row) for g in [grid, zip(*grid)] for row in g)

def print_grid(grid):
    print('\n'.join(''.join(row) for row in grid), end='\n\n')

def play(sequence):
    grid = [[x for x in row] for row in '.............|.rip....RRR..|.......R...R.|.biy.B.R.F.R.|.......R...R.|.fiw....RRR..|.............'.split('|')]

    for step in sequence:
        # (clone)
        new_grid = [row*1 for row in grid]

        # Perform swaps
        # automatically alphabetical order because 'bfr' is sorted
        new_grid = [
            [
                (
                    [b.upper() for b in 'bfr' if grid_has_rule(grid,chr(ord(c)+ord('a')-ord('A'))+'i'+b)] # priorities "<c>ib", then "<c>if", then "<c>ir"
                    +[c] # then no rule: c unchanged
                )[0]
                for c in row
            ]
            for row in grid
        ]

        # we can't modify grid because it stores the current rules
        # grid = new_grid

        # Step
        # re-orient new_grid until movement direction is left
        for _ in range(step):
            # rotate 90 CCW: transpose followed by reflect
            new_grid = [*zip(*new_grid)][::-1]

        for j, row in enumerate(new_grid):
            new_grid[j] = list(row)
            for k, cell in enumerate(new_grid[j]):
                if not grid_has_rule(grid,chr(ord(cell)-ord('A')+ord('a'))+"iy"):
                    # cell is not you
                    new_grid[j][k] = cell
                    continue

                # try pushing left from (j, k)
                # might not be push: B,F,R
                # get the rightmost cell to the left which isn't push:
                last_unpushable_i = [i for i,c in enumerate(new_grid[j][:k]) if c in 'BFR' and not grid_has_rule(grid,c.lower()+'ip')]
                last_unpushable_i = last_unpushable_i[-1] if last_unpushable_i else -1
                last_gap = [i for i,c in enumerate(new_grid[j][:k]) if c=='.' and last_unpushable_i<i] # (maybe slice from list(enumerate))
                if not last_gap:
                    # no gaps left, unpushable
                    if k > 0:
                        if grid_has_rule(grid, chr(ord(new_grid[j][k-1])-ord('A')+ord('a')) + 'iw'):
                            # object can't move and is win
                            return True
                    new_grid[j][k] = cell
                else:
                    # maybe del trick?
                    L = last_gap[-1]
                    new_grid[j][L:k] = new_grid[j][L+1:k+1]
                    new_grid[j][k] = '.'
        grid = new_grid
        # revert orientation (maybe just take this-last instead)
        for _ in range(step):
            # rotate 90 CW: reflect followed by transpose
            grid = [*zip(*grid[::-1])]

        # I'm leaving this here for future debugging
        # print('<^>V'[step])
        # print_grid(grid)

        # Check for you is win condition
        # Doesn't need to be at top because can't have yiw at start
        for a in 'bfr':
            if grid_has_rule(grid, a+'iw') and grid_has_rule(grid, a+'iy'):
                return True

```

### Golfed, commented (old)

```
# does grid g have the rule u, either horizontally or vertically?
R=lambda g,u:any(u in''.join(r)for g in[g,zip(*g)]for r in g)
e=enumerate
# main: play, given sequence S
# "<^>v" --> [0,1,2,3]
def P(S):
    # generate grid g
    g=[*map(list,['.'*13,'.rip....RRR..','.......R...R.','.biy.B.R.F.R.','.......R...R.','.fiw....RRR..','.'*13])]

    # for each step s
    for s in S:
        G=[ # create a new grid G, which consists of the swaps applied to g
        [
            (
                [b.upper()for b in'bfr'if R(g,chr(ord(c)+32)+'i'+b)]# priorities "<c>ib", then "<c>if", then "<c>ir"
                +[c])[0] # then no swap: plain c
                for c in r
            ]
            for r in g
        ]
        # rotate grid counter-clockwise s times until movement direction pointing left
        for _ in range(s):G=[*zip(*G)][::-1]
        # for each row of the rotated grid G
        for j,r in e(G):
            # side effect of the zip is that it produces tuples
            # no good since we have to modify them
            r=G[j]=[*r]
            # go from left to right in the row
            # this allows us to modify the row
            for k,C in e(G[j]):
                # test if the cell is you
                if R(g,chr(ord(C)+32)+"iy"):
                    l=0 # l shall be 1 more than index of the last empty cell to the left of this cell but not
                        # to the left of an entity that is not push; 0 if none exists
                        # Travel from left to right in the list of cells to the left of this cell
                        # (negative logic) If the cell is an entity and is not push, then l=0
                    for i,c in e(r[:k]):l=(c not in'BFR'or R(g,c.lower()+'ip')) and\
                            [l,i+1][c=='.']                  # otherwise set l=i+1 if c is empty, else l
                    # l<1: no empty cell to the left exists
                    # If not at the edge
                    # and the cell to the left is win, throw a NameError: win
                    if l<1:0<k and\
                        R(g,chr(ord(r[k-1])+32)+'iw') and\
                        E
                    # there is an empty cell at index l-1, so push
                    # shift cells over by one; set the cell you are pushing from to empty
                    else:r[l-1:k]=r[l:k+1];r[k]='.'
        g=G
        # rotate grid clockwise s times until back to normal
        for _ in range(s):g=[*zip(*g[::-1])]
        # test for X is win and X is you:
        for a in'bfr':R(g,a+'iw')and R(g,a+'iy')and E

```
> 7 votes

# Answer
# , <sup>~~456~~ ~~441~~</sup> 399 bytes

Takes in the list of directions, with `V < ^ >` as `0 1 2 3`.

```
0=[:+./@,@><@(4 o@,&4(4 o@,&0])13#.inv 36bdnnshw5d 85686 36ba491bbil 85686 36bbvydg17b)([:(([*0=[:+/@,y*w)r)@(([:><@[([+-~/@]*(={.))~&.>/@,~[:<"1@\:~@;e(<@(l,.4-~])~"{~+&4)~])r)(4-[)o(o=:|.@|:~&0)(([*0=[:+/@,y*1|.(w=:e.l&11)*0=p)([((*-.)+_1|.*)2=[:z&.|.(p*0<[)>.2*(y=:e.l&10)*1|.p=:((0=[:(z=:(2*4<3#.|:@,:)/\.)*@[+e.)e-.l&10,(l=:#&e@e.~(4+(e=:1+i.4),.5)&,.)&12))])(r=:3[\"1(,@,|:))@])&.>/@,~<"0@|.@]

```

Try it online!

Or play around with the version that prints the board after each step.

### How it (roughly) works

It goes quite well as an tacit definition, as we're just working on the matrix itself. It maps the characters to numbers according to the list in `level`.

Ungolfed:

```
 NB. map stored as base 13, then padded with floors and walls
walls=:4 rot@,&4(4 rot@,&0])13#.inv 36bdnnshw5d 85686 36ba491bbil 85686 36bbvydg17b
 NB. rotate matrix x times
rot=:|.@|:~&0
 NB. BFRW as numbers
objs=:1 2 3 4
 NB. get all 1x3 lists of the original and the transposed matrix
rules=:(3 [\"1 (,@,|:))
 NB. check if rule exists, e.g isrule&10 -> things that can be pushed
isrule =: (#&objs@e.~ (4 + objs ,. 5)&,.)
 NB. 0 2 0 0 1 1 2 1 0 -> 0 2 0 0 2 2 2 0 0
 NB. used for checking which fields can move/get pushed
red=:(2* 4< 3#. |: @ ,:)/\.
 NB. places that can be walked into
pass=:((0 = [: red *@[ + e.)  objs -. isrule&10 , isrule&12)
 NB. win place can't be walked into (not pushable or blocked),
 NB. with a you-entity that walks down -> won
wonpush=: ([ * 0 = [: +/@, (e. isrule&10) * 1 |. (e. isrule&11) * 0 = pass)
 NB. exists entity that is you and win?
wonyou =: ([ * 0 = [: +/@, (e. isrule&10) * (e. isrule&11))
 NB. calculate which places gets moved or pushed down in a step
shifts=:( 2 = [: red&.|. (  pass * 0 < [) >. 2 * (e. isrule&10) * 1 |. pass)
 NB. actually move down entities
move_down=:([ ((*-.)+_1 |.  *) shifts)
 NB. get all rules of the form (objs is objs), sort them, replace them
replace=: ([: > <@[ ([ + -~/@] * (={.))~&.>/@,~ [: <"1@\:~@; objs (<@(isrule ,. 4-~])~"{~ +&4)~ ])
 NB. rotate so movement goes down, check wonpush, move down, rotate back, replace, check wonyou
move=: ([: (wonyou rules)@(replace rules) (4-[) rot rot (wonpush move_down ]) rules@] )
 NB. append moves to the matrix and reduce from right to left with move,
 NB. e.g. 0 move 1 move 0 move walls
sim2=: (<@walls move&.>/@,~ <"0@|.@])
 NB. after everything is finished, does contain matrix only 0? if yes -> won

```
> 6 votes

# Answer
# BaBa Is You,  ~~663~~  615 bytes

File `.l`:

```
00000000: 4143 4854 554e 4721 0501 4d41 5020 0200  ACHTUNG!..MAP ..
00000010: 0000 0000 4c41 5952 b301 0000 0300 0f00  ....LAYR........
00000020: 0000 0c00 0000 0c00 0c00 00ff 0000 0000  ................
00000030: 0000 0000 0000 803f 0000 803f 0000 0100  .......?...?....
00000040: 0080 3fff ffff 024d 4149 4e87 0000 0078  ..?....MAIN....x
00000050: 5e63 2004 5819 3959 19b9 5958 d9b9 9918  ^c .X.9Y..YX....
00000060: 9919 3919 9999 1819 58b8 9958 9840 1a39  ..9.....X..X.@.9
00000070: 99d8 18b8 1959 3838 1919 9959 8098 9389  .....Y88...Y....
00000080: 8583 1bcc 061b cbc2 0085 dc40 9a1b c666  ...........@...f
00000090: 038a 02a5 ffe3 040c 6059 4ea0 7ddc cc30  ........`YN.}..0
000000a0: 45cc 0c20 08e2 3160 e865 6680 a802 d150  E.. ..1`.ef....P
000000b0: bd40 3770 b3fc ffcf 0894 018b 32fd ff8f  .@7p........2...
000000c0: 9045 b618 532f c8fd 5c44 d98b 6c0e a160  .E..S/..\D..l..`
000000d0: 0400 5728 8923 4441 5441 0100 0000 0030  ..W(.#DATA.....0
000000e0: 0000 0078 5e63 4603 0c0c cc0c 70c0 8cc4  ...x^cF.....p...
000000f0: 060a 6270 3135 3380 84c0 4ae1 7220 21b8  ..bp153...J.r !.
00000100: 30d0 7466 10c6 2ecb 0cb6 8199 1000 006d  0.tf...........m
00000110: d701 660f 0000 000c 0000 000c 000c 0000  ..f.............
00000120: ff00 0000 0000 0000 0000 0080 3f00 0080  ............?...
00000130: 3f00 0001 0000 803f ffff ff02 4d41 494e  ?......?....MAIN
00000140: 1600 0000 785e fb4f 1660 e4c4 af8d 91f9  ....x^.O.`......
00000150: ff28 4009 0100 74d2 62ba 4441 5441 0100  .(@...t.b.DATA..
00000160: 0000 0012 0000 0078 5e63 c60d 18d0 a418  .......x^c......
00000170: 9807 0900 00bc 3402 170f 0000 000c 0000  ......4.........
00000180: 000c 000c 0000 ff00 0000 0000 0000 0000  ................
00000190: 0080 3f00 0080 3f00 0001 0000 803f ffff  ..?...?......?..
000001a0: ff02 4d41 494e 0d00 0000 785e fb3f 0ae8  ..MAIN....x^.?..
000001b0: 1202 00e6 5866 a844 4154 4101 0000 0000  ....Xf.DATA.....
000001c0: 0b00 0000 785e 631e 8200 00bf 9a02 1d    ....x^c........

```

File `.ld`:

```
[tiles]
changed_short=016,082,
object082_name=text_phantom
changed_count=2
object016_name=text_feeling
changed=object016,object082,
object016_argtype=2,

```

Summon a `phantom` item to detect win

Weaken thing that are on others

`feeling` and `phantom` looks bad since image take extra bytes
> 3 votes

---
Tags: code-golf, decision-problem, grid, game
---


title: The Nine Pattern

text:
# Question
Title: The Nine Pattern
# Introduction

I stumbled across this (useless) pattern the other day while I was watching TV. I named it "the 9 pattern" because the first number to use it was 9. The gist of it is, you enter a number (let's say **x**), and then you get back:

* **x**
* **x** \+ (**x** / 3) \[let's call this **y**\]
* two-thirds of **y** \[let's call this **z**\]
* **z** \+ 1

So, if I put inside this pattern the number **9** as **x**, this is what would come out:

* 9 (**9**)
* 12 (**9** \+ **9** / 3) \[9 over 3 is 3, and 9 + 3 is 12\]
* 8 (**12** times two-thirds) \[a third of 12 is 4, and 4 * 2 is 8\]
* 9 (**8** \+ 1 is 9)

# Challenge

Write me a function (in any programming language) that takes in a number, and outputs an integer array using the pattern.
Somewhat like this psuedo-code:

```
function ninePattern(int myInt) returns IntegerArray {
    int iterationA = myInt + (myInt / 3);
    int iterationB = iterationA * (2 / 3);
    int iterationC = iterationB + 1;
    IntegerArray x = [myInt, iterationA, iterationB, iterationC];
    return x;
}

```

# Clarifications

Discussions have been arousing in comments regarding the specifications of the question. This section is meant to clarify some of those.

## "better to count in bytes than characters"

I picked characters because (for me, at least) it would be easier to judge. Of course, I can't change that now. (lots of answers are already posted)

## "rounding"

Rounding follows this rhyme:

> If it's 5 or more, raise the score
> If it's 4 or less, let it rest

Simply, put, if it is something like 4.7 or 3.85, round them to 5 and 4 respectively.

### Examples

```
Input => Result
9 => [9, 12, 8, 9]
8 => [8, 11, 7, 8]
6 => [6, 8, 5, 6]
23 => [23, 31, 21, 22]
159 => [159, 212, 141, 142]

```

If, however, the numbers are something like 2.3 or 10.435446, round them to 2 and 10 respectively.

## "language support"

You are free to not use functions and/or arrays **IF AND ONLY IF** the language of your choice does not support them. If it does (even if it will increase your characters count), **you must use them**.

# Answer
> 12 votes
# MarioLANG, ~~659~~ ~~621~~ ~~591~~ ~~582~~ ~~556~~ ~~543~~ ~~516~~ ~~458~~ ~~418~~ ~~401~~ ~~352~~ ~~308~~ 369 bytes

rounding is quite expensive :/

**Try it online**

```
;>>[![( [( [( [( [( [<(([!)))!+(((-<>( >((+
:"==#================"===#== #=====""[ "==
)(  -[!)>>[![)  [)[<(!>)[<)) >))) [!!-[!((
 (  )"#="==#======="=#==="=<="=====##==#==<
 +  +>) )-+<>+)[!)+! +))![-[)>[ [([-[![<<:
 +  )-+ )(=""===#==#  ==#===)"=======#=====
 +  >!>)!>  !(- < !:+:))<  ))!((++)))<
 )  "#"=#===#===" ======" ===#======="
 !
=#========================

```

Well this was more fun than expected, this is probably not optimal but I guess i'm getting there.

**Explanation time:**

(for the **352** bytes version)

first we get the argument and print it :

```
;
:

```

simple enough

we then move to the bulk of the program : the division **input / 3**

```
;>>[![              [( [( [<result
:"==#======================"======
)   -[!)>>[![        [<((((!
)   )"#="==#=========="====#
+(  +>) )  +>(+)[!)+))!
+(  )-+ )  -"====#====#
+   >!>)!  >! -  <
    "#"=#  "#===="
 !
=#

```

which is a slightly modified conversion of the brainfuck division

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

```

which take for input

```
n 0 d 0 0

```

and give you back

```
0 n d-n%d n%d n/d

```

once we got the division we use it to get the sum of **n** and **n/d** and print it

```
;>>[![              [( [( [<    !+(((-<
:"==#======================"===)#====="
)   -[!)>>[![        [<((((!    >))) [!(((
)   )"#="==#=========="====#   ="=====#==:
+(  +>) )  +>(+)[!)+))!
+(  )-+ )  -"====#====#
+   >!>)!  >! -  <
    "#"=#  "#===="
 !
=#

```

we then need to do another division : **( 2 * ( n + n / d ) ) / 3**

so we get **( 2 * ( n + n / d )**

```
;>>[![              [( [( [<    !+(((-<
:"==#======================"===)#====="
)   -[!)>>[![        [<((((!    >))) [!(((
)   )"#="==#=========="====#   ="=====#==:
+(  +>) )  +>(+)[!)+))! 2*2n/d>[   -[![  <
+(  )-+ )  -"====#====# ======"======#====
+   >!>)!  >! -  <            !((++))<
    "#"=#  "#===="            #======"
 !
=#

```

and put it with 3 back into the division

```
;>>[![              [( [( [<    !+(((-<
:"==#======================"===)#====="
)   -[!)>>[![        [<((((!    >))) [!(((
)   )"#="==#=========="====#   ="=====#==:
+(  +>) )  +>(+)[!)+))!      )>[   -[![  <
+(  )-+ )  -"====#====#      )"======#====
+   >!>)!  >! -  <       +++))!((++))<
    "#"=#  "#====" ===========#======"
 !
=#=================

```

at that point everything explose, mario is stuck in an infinite loop doing division on bigger and bigger number, forever.

and to fix that we need a way to diferenciate between the first and the second division, it end up that, oh joy, we do have a way

```
;>>[![              [( [( [<([!)!+(((-<
:"==#======================"==#)#====="
)   -[!)>>[![        [<((((!))< >))) [!(((
)   )"#="==#=========="====#)="="=====#==:
+(  +>) )  +>(+)[!)+))!!:+:)))>[   -[![  <
+(  )-+ )  -"====#====#======)"======#====
+   >!>)!  >! -  <       +++))!((++))<
    "#"=#  "#====" ===========#======"
 !
=#=================

```

basically we look if the x in

```
x 0 n d-n%d n%d n/d

```

is 0, if it is it mean we are on the first division

else we are on the second division, and we just print the result of the division, add 1 then print it again

and *voilà* easy as pie.

# Answer
> 9 votes
# Emotinomicon 99 bytes, 33 characters

```
,⏬➗➕⏬✖➗⏬➕

```

Explanation:

```
                                 clear output
                                 begin quote string
  ,
                                 end quote string
                                 duplicate top of stack
                                 duplicate top of stack
                                 take numeric input
                                 duplicate top of stack
                                 pop N and output as a number
                                 reverse stack
          ⏬                       pops and outputs top of stack as character
                                 reverse stack
                                 duplicate top of stack
                                 push 3 to the stack
              ➗                   divide top two elements on stack
               ➕                  add top two elements on stack
                                 duplicate top of stack
                                 pop N and output as a number
                                 reverse stack
                   ⏬              pops and outputs top of stack as character
                                 reverse stack
                                 push 2 to the stack
                      ✖           multiply top two elements on stack
                                 push 3 to the stack
                        ➗         divide top two elements on stack
                                 duplicate top of stack
                                 pop N and output as a number
                                 reverse stack
                            ⏬     pops and outputs top of stack as character
                                 reverse stack
                                 push 1 to the stack
                               ➕  add top two elements on stack
                                 pop N and output as a number

```

# Answer
> 4 votes
# MATL, 14 bytes

```
Xot4*3/tE3/tQv

```

**Try it Online**

Pretty simple, `v` concatenates the stack into an array. `Xo` converts to an integer data-type, and all operations thereafter are integer operations.

# Answer
> 4 votes
# Cheddar, 27 bytes

```
b=8/9*$0
[$0,$0+$0/3,b,b+1]

```

`$0` is variable with input. Cheddar just isn't a golfy language ¯\\\_(ツ)\_/¯ , also this is non-competing because Cheddar's input functionality was made after this challenge.

Ungolfed:

```
IterationB := 8 / 9 * $0  // 8/9ths of the Input
[ $0,                     // The input
  $0 + $0 / 3,            // Input + (Input/3)
  IterationB,             // (see above)
  IterationB + 1          // above + 1
]

```

# Answer
> 3 votes
# Java, 86 82 84 85 characters

```
class c{int[]i(int I){int a=I+(I/3),b=(int)(a*(2d/3d));return new int[]{I,a,b,b+1};}}

```

The letter `d` placed right after an integer makes the integer a `double`.

Ungolfed:

```
class c{
    int[] i(int I) {
        int a = I + (I / 3),
            b = (int)(a * (2d / 3d));
        return new int[]{I, a, b, b + 1};
    }
}

```

Without the class (`class c{}` is 8 chars long), it downsizes to 76 characters:

```
int[]i(int I){int a=I+(I/3),b=(int)(a*(2d/3d));return new int[]{I,a,b,b+1};}

```

More accurate version in 110 chars (118 with the enum) - it uses `float`s because ain't nobody got space for casting `Math#round(double)`:

```
int[]i(int I){float a=I+(I/3f),b=(a*(2f/3f));return new int[]{I,Math.round(a),Math.round(b),Math.round(b+1)};}

```

# Answer
> 3 votes
# Java, ~~56~~ 80 Bytes

As some users pointed out, this solution (as some others in java) does not round data properly. So now I'm presenting slightly longer solution which should return correct result

```
int[]h(int a){int[]b={a,Math.round(a+a/3f),a=Math.round(a*8f/9),++a};return b;}

```

or 60 bytes lamda version

```
a->new int[]{a,Math.round(a+a/3f),a=Math.round(a*8f/9),++a}

```

~~Golfed version~~

~~```
int[]g(int a){int[]b={a,a+a/3,a*8/9,a*8/9+1};return b;}

```
and ungolfed
```
int[] g(int a) {
        int[] b = { a, a + a / 3, a * 8 / 9, a * 8 / 9 + 1 };
        return b;
    }

```
or 36 bytes defined as lambda
```
a->new int[]{a,a+a/3,a*8/9,a*8/9+1}

```~~

# Answer
> 3 votes
# Scratch, 33 bytes

(source: cubeupload.com)

Asks for input, sets `a` to input rounded, sets `b` and `c` to their respective changes, then says all four numbers, seperated by commas.

# Answer
> 2 votes
# 05AB1E, 15 bytes

Code:

```
Ð3/+D·3/D>)1;+ï

```

Uses **CP-1252** encoding. Try it online!.

# Answer
> 2 votes
## Java 8 lambda, ~~109~~ ~~81~~ ~~79~~ 75 characters

Because... you know... even Java can be golfed...

```
a->{int b=(int)(.5+a*4./3),c=(int)(.5+b*2./3);return new int[]{a,b,c,++c};}

```

Lambda ungolfed into class:

```
class C {
   static int[] a(int a) {
        int b = (int) (.5 + a * 4. / 3),
            c = (int) (.5 + b * 2. / 3);
        return new int[]{a, b, c, ++c};
    }
}

```

~~I assume I'm allowed to use longs as they are also an integer type. Sadly one needs to correctly round integers and thus a "short" cast doesn't work. By using longs we don't need to cast the rounding results back to ints.~~

### Update

Using the nice little + 0.5 and casting afterwards trick we keep the correct rounding and save 2 chars!

Also this trick doesn't require the use of long any longer thus we can switch back to ints shaving of 4 more chars.

# Answer
> 2 votes
# Java, 64 bytes

```
int[]f(int i){return new int[]{i,i+=i/3+0.5,i-=i/3-0.5,i+=1.5};}

```

### Notes

* This has the required rounding build in, not sure if you can do it shorter if mixed with @user902383's solution.

### Ungolfed

```
int[] f(int i) {
    return new int[]{
            i,
            i += i / 3 + 0.5,
            i -= i / 3 - 0.5,
            i += 1.5};
}

```

### Output with i=9

```
[9, 12, 8, 9]

```

# Answer
> 2 votes
# Python 3, 52 bytes

```
f=lambda n,i=4:1//i*[n+1]or[n]+f(round(i*n/3),i%3+1)

```

Try it online!

Contrary to the previous Python answer, this one rounds in between cycles.

Every next value can be calculated using `i*n/3`, where `n` is the current value and `i` is taken from `[4,2,3]`. To complete the sequence, `1` is added to the result of the final iteration.

# Answer
> 2 votes
# MathGolf, 14 bytes

```
3/+_∞3/_)Γ2∩+i

```

Try it online.

**Explanation:**

```
3/             # Divide the (implicit) input by 3
  +            # Add it to the (implicit) input
   _           # Duplicate this
    ∞          # Double the copy
     3/        # Divide it by 3
       _       # Duplicate this
        )      # Increase the copy by 1
         Γ     # Wrap four values into a list (since the stack only contains three, it
               # will use the implicit input as fourth):
          2∩+  # Add 1/2 to each
             i # And cast each float to an integer, removing any decimal values
               # [int(i+1/2),int(i+i/3+1/2),int((i+i/3)*2/3+1/2),int((i+i/3)*2/3+1+1/2)]
               # (after which the entire stack joined together is output implicitly)

```

# Answer
> 2 votes
# Thunno, 18 chars

```
D4*3/D2*3/D1+ZMrZv

```

Attempt This Online!

(This is actually a bit less in bytes but the challenge asks for chars, not bytes.)

This is a full program since Thunno doesn't have functions.

#### Explanation

```
D4*3/D2*3/D1+ZMrZv  # Implicit input
D                   # Duplicate
 4*3/               # Push x*(4/3)
     D              # Duplicate
      2*3/          # Push y*(2/3)
          D         # Duplicate
           1+       # Push z+1
             ZMr    # Push the stack
                Zv  # Round each number
                    # Implicit output

```

# Answer
> 1 votes
# Mathematica - 21 bytes

Just got Mathematica from my brothers RPi, so trying it out for fun, and what better way than a PPCG challenge.

```
{#,4#/3,8#/9,8#/9+1}&

```

Defines an anonymous function. Try it out like:

```
In[26]:= x:={#,4#/3,8#/9,8#/9+1}&

In[27]:= x[9]

Out[27]= {9, 12, 8, 9}

```

# Answer
> 1 votes
## Actually, 21 bytes

```
`;;3@/+;32/*;uk1½+♂≈`

```

This program declares a function that performs the required operations on the top stack value.

Try it online! (the extra `.` at the end evaluates the function and prints the result)

Explanation:

```
`;;3@/+;32/*;uk1½+♂≈`
 ;;                    make two copies of x
   3@/+                divide by 3, add that to x to get y
       ;32/*           make a copy of y and multiply by 2/3 to get z
            ;u         make a copy of z and add one
              k        push stack as a list
               1½+     add 0.5 to each element
                  ♂≈   apply int() to each element (make integers from floats by flooring; this is equivalent to rounding half-up because of adding 0.5)

```

# Answer
> 1 votes
## Python 3, 45 bytes

```
f=lambda i:map(round,[i,i*4/3,i*8/9,i*8/9+1])

```

See this code running on ideone.com

# Answer
> 1 votes
## Lua, 52 Bytes

This program takes a number by command-line argument and return the corresponding array. Programs in lua are technically functions, as the interpreter will always encapsulate them in a function. This is also this mechanic that is used when you "call" codes in other files (it basically uses `loadfile`/`dofile`).

```
m=math.floor x=...z=m(x*8/9)return{x,m(x*4/3),z,z+1}

```

# Answer
> 1 votes
## Pyke, 11 bytes

```
D}[}3/bD)[h

```

Try it here!

```
            - implicit input()
D           - a,b = ^
 }          - b*=2
  [}3/bD)   - macro:
   }        -   tos*=2
    3/      -   tos/=3
      b     -   tos = round(tos)
       D    -   old_tos = tos = tos
            - macro
         [  - macro
          h - d +=1

```

# Answer
> 1 votes
# Mathcad, \[tbd\] bytes

---

Mathcad codegolf byte equivalance is yet to be determined. Taking a keyboard count as a rough equivalent, the solution is approx 40 bytes.

# Answer
> 1 votes
# C++0x - 95 102 185 189 109 129 chars

```
int * n(int p){static int a[3];a[0]=p;a[1]=round(p+(p/3));a[2]=round((a[1]/3)*2);a[3]=a[2]+1;return a;}

```
* This requires the **cmath** header to work.

## Degolfed

```
#include <cmath>
int * ninePattern(int p) {
        static int a[3]; // pattern array
        a[0] = p; // sets first iteration
        a[1] = round(p + (p / 3)); // sets second iteration
        a[2] = round((a[1] / 3) * 2); // sets third iteration
        a[3] = a[2] + 1; // sets fourth iteration
        return a; // returns array
}

```

# Answer
> 1 votes
# Javascript, 51 bytes

I convert my java solution to JavaScript and skimmed it down little bit.

```
var r=Math.round,g=a=>[a,a=r(a+a/3),a=r(a*2/3),++a]

```

# Answer
> 1 votes
# Arturo, 55 bytes

```
$[x][map@[x,y:round x+x//3y,1+dup round 2*y//3]=>floor]

```

Try it

# Answer
> 1 votes
# JavaScript, 47 bytes

```
(a,r=Math.round)=>[a,a=r(a*4/3),a=r(a*2/3),++a]

```

Try it:

```
f=(a,r=Math.round)=>[a,a=r(a*4/3),a=r(a*2/3),++a]

console.log(JSON.stringify(f(9)));
console.log(JSON.stringify(f(8)));
console.log(JSON.stringify(f(6)));
console.log(JSON.stringify(f(23)));
console.log(JSON.stringify(f(159)));
```

# Answer
> 0 votes
**Erlang, 80 bytes**

```
-module(f).
-export([f/1]).
f(X)->Y=X+(X/3),Z=trunc(Y*(2/3)),[X,trunc(Y),Z,Z+1].

```

To run, save as *f.erl*, compile and call the function. It will return a list of ints:

```
fxk8y@fxk8y:/home/fxk8y/Dokumente/erlang/pcg# erl
Erlang/OTP 18 [erts-7.0] [source] [64-bit] [smp:4:4] [async-    threads:10] [kernel-poll:false]

Eshell V7.0  (abort with ^G)
1> c(f).
{ok,f}
2> f:f(9).
"\t\f\b\t"
3>

```

Note that Erlang automatically converts *int*s to ASCII chars if you are in the ASCII value range because Erlang doesn't have a *char* type. Calling the function with 100 gives you the better readable *\[100,133,88,89\]*.

Ungolfed:

```
-module(f).
-export([f/1]).

f(X) ->
  Y = X+(X/3),
  Z = trunc(Y*(2/3)),
  [X, trunc(Y), Z, Z+1].

```

# Answer
> 0 votes
# Erlang, 46 bytes

Answer inspired by @fxk8y (I couldn't post a comment to his answer)

```
F=fun(X)->Z=round(X*4/9),[X,Z*3,Z*2,Z*2+1]end.

```

Also you can see the results with:

```
2> io:fwrite("~w~n", [F(9)]).
[9,12,8,9]
ok

```

# Answer
> 0 votes
# Pyth, 20 bytes

```
m.RdZ[Jc*4Q3Kc*2J3hK

```

Explanation:

```
            (Implicit print)
m           For each d in array, d =
.RdZ        Round d to zero decimal places
[           The array of
  J         The result of setting J to
    c       The float division of
      *4Q   Input * 4
      3     and 3
            ,
  K         The result of setting K to
    c       The float division of
      *2J   J * 2
      3     and 3
            , and
  hK        K + 1.
            (Implicit end array)

```

Test here

# Answer
> 0 votes
# Jolf, 17 bytes

```
Ώ‘Hγ+H/H3Βώ/γ3hΒ’

```

Defines a function `Ώ`. It takes input implicitly, so it also doubles as a full program. Try it here!

# Answer
> 0 votes
## Mathematica, 51 bytes

```
FoldList[#2@#&,{#,Round[4#/3]&,Round[2#/3]&,#+1&}]&

```

Anonymous function that conforms to the current (at time of posting) version of post, which implies rounding at every step.

`FoldList` is a typical operation in programming. It is invoked as `FoldList[f, list]` and applies the two-argument function `f` repeatedly to the result (or the first element of the list in the first iteration), taking the next element of the list as its second argument.

Ungolfed: `#2 @ # &` is an anonymous functions that applies its second argument to the first. Therefore, the list argument of `FoldList` consists of the successive functions to be applied to the input.

```
FoldList[#2 @ # &,
  {#, (* note the absence of '&' here,
         this '#' stands for the argument
         of the complete function and is
         covered by the & at the end      *)
   Round[4 # / 3] &, (* anonymous function that rounds 4/3 of its input *)
   Round[2 # / 3] &, (* ditto, 2/3 *)
   # + 1 &           (* add one function *)
  }] &               (* and the '&' makes the entire
                        thing an anonymous function,
                        whose argument is the '#' up
                        at the top.                  *)

```

Because input is integer and the divisions are by 3, there will never be a result like 4.5, therefore there's no need to worry about rules of rounding when the last digit is a `5`: it will always be clearly closer to one integer, or another.

# Answer
> 0 votes
# Dyalog APL, 33 bytes

```
(⌽,{1+⊃⍵})∘{⍵,⍨3÷⍨2×⊃⍵}(3÷⍨4∘×),⊢

```

# Answer
> 0 votes
# Desmos, 37 bytes

```
a=9
b=a+\frac{a}{3}
c=\frac{2}{3}b
d=c+1

```

Try it online
Yay for unconventional languages!

# Answer
> 0 votes
# CJam, 21 bytes

```
qi__3d/+mo_2d3/*i_)]`

```

Feedback is welcome

# Explanation

* `qi__` \- Read the input as an integer and duplicate it twice
* `3D/+mo` \- Divide one instance of the input by 3, then add it to the second instance to make y
* `_2d3/*i` \- Duplicate y, then multiply it by .6
* \_)\]\` - Dupe, increment, wrap in array, print as array (not in code because of the \` operator :( )

Edit: Forgot to make the first three a double, so the program was broken. Fixed.

# Answer
> 0 votes
# Axiom, 59 bytes

```
g(x)==round(x)::INT;f(x)==[x,a:=g(x+x/3.),b:=g(a*2./3),b+1]

```

test

```
(3) -> [[i,f(i)] for i in [9,8,6,23,159]]
   (3)
   [[9,[9,12,8,9]], [8,[8,11,7,8]], [6,[6,8,5,6]], [23,[23,31,21,22]],
    [159,[159,212,141,142]]]
                                                      Type: List List Any

```

# Answer
> 0 votes
# PHP, 60 Bytes

```
print_r([$a=$argn,$b=round($a+$a/3),$c=round($b*2/3),$c+1]);

```

Try it online!

# Answer
> 0 votes
# PHP, 67 bytes

```
function f($x){return [$x,$y=round($x*4/3),$z=round($y*2/3),$z+1];}

```

# Answer
> 0 votes
# Zsh\*, 58 bytes

```
r()<<<${$(($1+.5))%.*}
r $1;r $[_+_/3];r $[2*_/3];r $[_+1]

```

Try it online!

(\*) Using `force_float` and `extendedglob` options.

---
Tags: code-golf, array, integer
---


title: Fit a word into an alphabet grid

text:
# Question
Title: Fit a word into an alphabet grid
Inspired by a meme I saw earlier today.

# Challenge description

Consider an infinite alphabet grid:

```
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ
...

```

Take a word (`CODEGOLF` in this example) and make it a subsequence of the grid, replacing unused letters by a space and removing letters at the end of the infinite grid altogether:

```
  C           O
   DE G       O
           L
     F

```

# Examples

`STACKEXCHANGE`

```
                  ST
A C       K
    E                  X
  C    H
A            N
      G
    E

```

`ZYXWVUTSRQPONMLKJIHGFEDCBA`

```
                         Z
                        Y
                       X
                      W
                     V
                    U
                   T
                  S
                 R
                Q
               P
              O
             N
            M
           L
          K
         J
        I
       H
      G
     F
    E
   D
  C
 B
A

```

`F`

```
     F

```

`ANTIDISESTABLISHMENTARIANISM`

```
A            N     T
        I
   D    I         S
    E             ST
AB         L
        I         S
       H    M
    E        N     T
A                R
        I
A            N
        I         S
            M

```

# Notes

* Trailing whitespaces are allowed.
* You don't need to pad the last any line with spaces. For example, if the input is `ABC`, you may output just `ABC` without 23 trailing spaces.
* You may assume input will match `[A-Z]+` regex.
* Alternatively, you may use lower-case alphabet, in which case output will match `[a-z]+`.
* You must use a newline (`\n`, `\r\n` or equivalent) to separate lines, that is a list of strings is not a proper output format.
* This is a challenge, so make your code as short as possible!

# Answer
> 11 votes
# Husk, 15 bytes

```
TṪS`?' €…"AZ"ġ>

```

Try it online!

## Explanation

```
TṪS`?' €…"AZ"ġ>  Implicit input, e.g. "HELLO"
             ġ>  Split into strictly increasing substrings: x = ["H","EL","LO"]
        …"AZ"    The uppercase alphabet (technically, the string "AZ" rangified).
 Ṫ               Outer product of the alphabet and x
  S`?' €         using this function:
                   Arguments: character, say c = 'L', and string, say s = "EL".
       €           1-based index of c in s, or 0 if not found: 2
  S`?'             If this is truthy, then c, else a space: 'L'
                 This gives, for each letter c of the alphabet,
                 a string of the same length as x,
                 containing c for those substrings that contain c,
                 and a space for others.
T                Transpose, implicitly print separated by newlines.

```

# Answer
> 7 votes
# Java 10, ~~161~~ ~~159~~ 152 bytes

```
s->{var x="";int p=0;for(var c:s)x+=p<(p=c)?c:";"+c;for(var y:x.split(";"))System.out.println("ABCDEFGHIJKLMNOPQRSTUVWXYZ".replaceAll("[^"+y+"]"," "));}

```

-2 bytes thanks to *@Nevay*.
-7 byte printing directly instead of returning a String, and converting to Java 10.

**Explanation:**"

Try it here.

```
s->{                      // Method with String parameter and no return-type
  var x="";               //  Temp-String
  int p=0;                //  Previous character (as integer), starting at 0
  for(var c:s)            //  Loop (1) over the characters of the input
    x+=p<(p=c)?           //   If the current character is later in the alphabet
                          //   (replace previous `p` with current `c` afterwards)
        c                 //    Append the current character to Temp-String `x`
       :                  //   Else:
        ";"+c;            //    Append a delimiter ";" + this character to Temp-String `x`
  for(var y:x.split(";")) //  Loop (2) over the String-parts
    System.out.println(   //   Print, with trailing new-line:
     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                          //    Take the alphabet,
        .replaceAll("[^"+y+"]"," "));}
                          //    and replace all letters not in the String-part with a space

```

The first part of the method splits the input-word into parts with a delimiter.
For example: `CODEGOLF``CO;DEGO;L;F` or `BALLOON``B;AL;LO;O;N`.

The second part loops over these parts, and uses the regex `[^...]` to replace everything that isn't matched with a space.
For example `.replaceAll("[^CO]"," ")` leaves the `C`, and `O`, and replaces everything else with a space.

# Answer
> 6 votes
# C (gcc), 69 bytes

```
i;f(char*s){for(i=64;*s;putchar(*s^i?32:*s++))i+=i^90?1:puts("")-26;}

```

Try it online!

# Answer
> 5 votes
# MATL, ~~24~~ 23 bytes

```
''jt8+t1)wdh26X\Ys(26e!

```

Uses lowercase letters.

Try it at MATL Online!

### Explanation

```
''     % Push empty string
jt     % Push input string. Duplicate
8+     % Add 8 to each char (ASCII code). This transforms 'a' 105,
       % 'b' into 106, which modulo 26 correspond to 1, 2 etc
t1)    % Duplicate. Get first entry
wd     % Swap. COnsecutive differences.
h      % Concatenate horizontally
26X\   % 1-based modulo 26. This gives a result from 1 to 26
Ys     % Cumulative sum
(      % Write values (converted into chars) at specified positions
       % of the initially empty string
26e    % Reshape into a 26-row char matrix, padding with char 0
!      % Transpose. Implicitly display. Char 0 is shown as space

```

# Answer
> 4 votes
# Perl 5, 44 bytes

**40 bytes code + 4 for `-lF`.**

```
print map/$F[0]/?shift@F:$",A..Z while@F

```

Try it online!

# Answer
> 4 votes
# Python 2, 92 bytes

```
f=lambda x,y=65:x and(y<=ord(x[0])and" "*(ord(x[0])-y)+x[0]+f(x[1:],-~ord(x[0]))or"\n"+f(x))

```

Try it online!

# Answer
> 4 votes
# Japt, ~~18~~ 16 bytes

*-2 bytes thanks to @Shaggy*

```
;ò¨ £B®kX ?S:Z
·

```

Uppercase input only.

Try it online!

## Explanation

```
;

```

Switch to alternate variables, where `B` is the uppercase alphabet.

```
ò¨

```

Split the input string between characters where the first is greater than or equal to (`¨`) the second.

```
£

```

Map each partition by the function, where `X` is the current partition.

Map each character in the uppercase alphabet to the following, with `Z` being the current letter.

```
kX

```

Remove all letters in the current partition from the current letter. If the current letter is contained in the current partition, this results in an empty string.

```
?S:Z

```

If that is truthy (not an empty string), return a space (`S`), otherwise return the current letter.

```
·

```

Join the result of the previous line with newlines and print the result.

# Answer
> 4 votes
# JavaScript (ES6), 79

*Edit* As a leading newline is accepted, I can save 2 bytes

```
s=>eval("for(o='',v=i=0;c=s.charCodeAt(i);v%=27)o+=v++?c-63-v?' ':s[i++]:`\n`")

```

For 1 byte more, I can accept lowercase or uppercase input:

```
s=>eval("for(o='',v=i=0;c=s[i];v%=27)o+=v++?parseInt(c,36)-8-v?' ':s[i++]:`\n`")

```

*Less golfed*

```
s=>{
  var i,o,c,v
  for(o = '', v = 1, i = 0; c = s.charCodeAt(i); v %= 27)
    o += v++ ? c-63-v ? ' ' : s[i++] : '\n'
  return o
}

```

**Test**

```
f=s=>eval("for(o='',v=i=0;c=s.charCodeAt(i);v%=27)o+=v++?c-63-v?' ':s[i++]:`\n`")

function update() {
  var i=I.value
  i=i.replace(/[^A-Z]/gi,'').toUpperCase()
  O.textContent=f(i)
}

update()
```

```
<input id=I value='BALLOON' oninput='update()' >
<pre id=O></pre>
```

# Answer
> 4 votes
# C (gcc), ~~91~~ 63 bytes

-28 thanks to ASCII-only

```
_;f(char*s){for(_=64;*s;)putchar(++_>90?_=64,10:*s^_?32:*s++);}

```

Try it online!

---

Previous:

```
i,j;f(char*s){while(s[i]){for(j=65;j<91;j++)s[i]==j?putchar(s[i++]):printf(" ");puts("");}}

```

Yes, there's a shorter solution, but I noticed after I wrote this one... Try it online!

# Answer
> 3 votes
# Pyth, 18 bytes

```
#pbVGp?JqhzNNd=>zJ

```

Try it here.

Leading newline in output, lowercase alphabet.

# Answer
> 3 votes
# Jelly, 19 bytes

```
<2\¬0;œṗfȯ⁶$¥€@€ØAY

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 18 bytes

```
ćIgµ¶?AvDyÊið?ë¼?ć

```

Try it online!

Got trouble with 05AB1E `ć` (extract 1) leaving an empty string/list on the stack after the last element is extracted. This solution would be 1-2 bytes shorter if it weren't for that.

```
ćIgµ¶?AvDyÊið?ë¼?ć  Implicit input
ć                   Extract the 1st char from the string
 Igµ                While counter != length of the string
    ¶?              Print a newline
      Av            For each letter of the lowercased alphabet
        DyÊ         Is the examined character different from the current letter?
           ið?      If true, then print a space

              ë¼?ć  Else increment the counter, print the letter and push
                    the next character of the string on the stack

```

# Answer
> 3 votes
# Mathematica, 101 bytes

```
StringRiffle[
  Alphabet[]/.#->" "&/@
   (Except[#|##,_String]&@@@
     Split[Characters@#,#==1&@*Order]),"
",""]&

```

`Split` the input into strictly increasing letter sequences, comparing adjacent letters with `Order`. If `Order[x,y] == 1`, then `x` precedes `y` in the alphabet and thus can appear on the same line.

For each sequence of letters, create a pattern to match strings `Except` for those letters; `#|##` is a shorthand for `Alternatives`. Replace letters of the `Alphabet` that match the pattern with spaces.

---

Illustration of the intermediate steps:

```
"codegolf";
Split[Characters@#,#==1&@*Order]  &@%
Except[#|##,_String]&@@@         #&@%
Alphabet[]/.#->" "&/@               %

```

```
{{"c", "o"}, {"d", "e", "g", "o"}, {"l"}, {"f"}}

{Except["c" | "c" | "o", _String],
 Except["d" | "d" | "e" | "g" | "o", _String],
 Except["l" | "l", _String],
 Except["f" | "f", _String]}

{{" "," ","c"," "," "," "," "," "," "," "," "," "," "," ","o"," "," "," "," "," "," "," "," "," "," "," "},
 {" "," "," ","d","e"," ","g"," "," "," "," "," "," "," ","o"," "," "," "," "," "," "," "," "," "," "," "},
 {" "," "," "," "," "," "," "," "," "," "," ","l"," "," "," "," "," "," "," "," "," "," "," "," "," "," "},
 {" "," "," "," "," ","f"," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "}}

```

# Answer
> 3 votes
# Zsh, 65 bytes

***-4 bytes** thanks to @pxeger, **-2 bytes** thanks to @roblogic*

```
repeat $#1;echo&&for y ({A-Z})printf ${(Ml:1:)1[1]%$y}&&1=${1#$y}

```

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

Append to `$s` a `(M)` matched letter, `(l:1:)` left-padded to one character, then remove the letter if it matches the start of `$1`.

# Answer
> 2 votes
# Retina, ~~130~~ 126 bytes

```
$
¶A
{-2=`
$'
}T`RL`_o`.$
+`(?<=(.)*)((.).*¶(?<-1>.)*(?(1)(?!)).+\3.*$)
 $2
(?<=(.)*)((.).*¶(?<-1>.)*(?<-1>\3.*$))
¶$2
}`¶.*$

```

Try it online! Edit: Saved 4 bytes by using @MartinEnder's alphabet generator. Explanation:

```
$
¶A
{-2=`
$'
}T`RL`_o`.$

```

Append the alphabet.

```
+`(?<=(.)*)((.).*¶(?<-1>.)*(?(1)(?!)).+\3.*$)
 $2

```

Align as many letters as possible with their position in the alphabet.

```
(?<=(.)*)((.).*¶(?<-1>.)*(?<-1>\3.*$))
¶$2

```

Start a new line before the first letter that could not be aligned.

```
}`¶.*$

```

Delete the alphabet, but then do everything over again until there are no misaligned letters.

# Answer
> 2 votes
# Golfscript, ~~22~~ 21 bytes

Try it online!

*-1 byte thanks to careful final redefining of the `n` built-in.*

```
{.n>{}{'
'\}if:n}%:n;

```

Explanation (with a slightly different version):

```
{.n>{}{"\n"\}if:n}%:n; # Full program
{                }%    # Go through every character in the string
 .n>         if        # If ASCII code is greater than previous...
                       # (n means newline by default, so 1st char guaranteed to fit)
    {}                 # Do nothing
      {"\n"\}          # Else, put newline before character
               :n      # Redefine n as the last used character
                   :n; # The stack contents are printed at end of execution
                       # Literally followed by the variable n, usually newline
                       # So because n is by now an ASCII code...
                       # ...redefine n as the new string, and empty the stack

```

# Answer
> 2 votes
# Retina, 80 bytes

```
^
;¶
{`;.*
¶;ABCDEFGHIJKLMNOPQRSTUVWXYZ
¶¶
¶
)+`;(.*)(.)(.*¶)\2
$.1$* $2;$3
;.*

```

Try it online!

There is always exactly one leading newline. The code somewhat clunkily prepends the word with the alphabet along with a marker (semicolon). It then moves the marker up to the first letter of the word, while changing all other letters it passes into spaces. It also removes the first letter of the word. It repeats this until the first letter of the word isn't after the marker anymore. Then it clears that marker and the rest of the alphabet, and replaces it with a new line and the alphabet with a marker again. It keeps repeating this until the input word is empty, then it cleans up the last alphabet and marker, leaving the desired output.

# Answer
> 2 votes
# q/kdb+, ~~48~~ 45 bytes

**Solution:**

```
-1{@[26#" ";.Q.A?x;:;x]}@/:(0,(&)(<=':)x)_x:;

```

Try it online!

**Note:** Link is to a K (oK) port of this solution as there is no TIO for q/kdb+.

**Examples:**

```
q)-1{@[26#" ";.Q.A?x;:;x]}@/:(0,(&)(<=':)x)_x:"STACKEXCHANGE";
                  ST
A C       K
    E                  X
  C    H
A            N
      G
    E

q)-1{@[26#" ";.Q.A?x;:;x]}@/:(0,(&)(<=':)x)_x:"BALLOON";
 B
A          L
           L  O
              O
             N

```

**Explanation:**

Q is interpreted right-to-left. The solution is split into two parts. First split the string where the next character is less than or equal to the current:

`"STACKEXCHANGE"` -\> `"ST","ACK","EX","CH","AN","G","E"`

Then take a string of 26 blanks, and apply the input to it at the indices where the input appears in the alphabet, and print to stdout.

`"__________________________"` -\> `__________________ST______`

Breakdown:

```
-1{@[26#" ";.Q.A?x;:;x]}each(0,where (<=':)x) cut x:; / ungolfed solution
-1                                                  ; / print to stdout, swallow return value
                                                  x:  / store input as variable x
                                              cut     / cut slices x at these indices
                            (               )         / do this together
                                     (<=':)x          / is current char less-or-equal (<=) than each previous (':)?
                               where                  / indices where this is true
                             0,                       / prepended with 0
                        each                          / take each item and apply function to it
  {                    }                              / lambda function with x as implicit input
   @[      ;      ; ; ]                               / apply[variable;indices;function;arguments]
     26#" "                                           / 26 take " " is "      "...
            .Q.A?x                                    / lookup x in the uppercase alphabet, returns indice(s)
                   :                                  / assignment
                     x                                / the input to apply to these indices

```

**Notes:**

* -3 bytes by replacing prev with the K4 version

# Answer
> 2 votes
# , ~~129~~ 117 bytes

```
function(s){z={}
y=diff(x<-utf8ToInt(s)-64)
z[diffinv(y+26*(y<0))+x[1]]=LETTERS[x]
z[is.na(z)]=" "
write(z,1,26,,"")}

```

Try it online!

Explanation (ungolfed):

```
function(s){
 z <- c()                  # initialize an empty vector
 x <- utf8ToInt(s)-64      # map to char code, map to range 1:26
 y <- diff(x)              # successive differences of x
 idx <- cumsum(c(          # indices into z: cumulative sum of:
    x[1],                  # first element of x
    ifelse(y<=0,y+26,y)))  # vectorized if: maps non-positive values to themselves + 26, positives to themselves
 z[idx] <- LETTERS[x]      # put letters at indices
 z[is.na(z)] <- " "        # replace NA with space
 write(z,"",26,,"")        # write z as a matrix to STDOUT ("") with 26 columns and empty separator.

```

# Answer
> 2 votes
# Python 3, ~~87~~ 85 bytes

```
def f(s,l=65):c,*t=s;o=ord(c)-l;return o<0and'\n'+f(s)or' '*o+c+(t and f(t,o-~l)or'')

```

Try it online!

# Answer
> 2 votes
# , 39 bytes

```
(_65+3 u:[)}&(26{.'')/.~0+/\@,2>:/\3&u:

```

Try it online!

# Answer
> 2 votes
# Charcoal, 15 bytes

```
Ｆθ«Ｊ⌕αι⁺ⅉ‹⌕αιⅈι

```

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

```
 θ              Input string
Ｆ «             Loop over characters
     α     α    Uppercase letters predefined variable
      ι     ι   Current character
    ⌕     ⌕     Find index
             ⅈ  Current X co-ordinate
         ‹      Compare
        ⅉ       Current Y co-ordinate
       ⁺        Sum
   Ｊ            Jump to aboslute position
              ι Print current character

```

# Answer
> 2 votes
# APL (Dyalog Classic), 20 bytes

```
⊃¨⎕a∘.∩⍨⊢⊂⍨1,2≥/⎕a⍳⊢

```

Try it online!

# Answer
> 2 votes
# K (ngn/k), ~~29~~ 28 bytes

```
{{x@x?`c$65+!26}'(&~>':x)_x}

```

Try it online!

`{` `}` function with argument `x`

`>':x` for each char, is it greater than the previous char?

`~` negate

`&` where (at which indices) do we have true

`(` `)_x` cut `x` at those indices, return a list of strings

`{` `}'` for each of those strings

```
`c$65+!26

```

the English alphabet

`x?` find the index of the first occurrence of each letter in `x`, use `0N` (a special "null" value) if not found

`x@` index `x` with that; indexing with `0N` returns `" "`, so we get a length-26 string in which the letters from `x` are at their alphabetical positions and everything else is spaces

# Answer
> 2 votes
# Powershell, ~~70~~ 63 bytes

*-7 bytes thanks @Veskah*

```
$args|%{if($_-le$p){$x;rv x}
$x=("$x"|% *ht($_-65))+($p=$_)}
$x

```

Try it online!

Explanation:

For each character in the splatted argument:

* Output string `$x` and clear `$x` value (`rv` is alias for Remove-Variable), if a code of the current character less or equivalent (`-le`) to a code of the previous character.
* Append spaces and the current character to `$x`, store it to `$x`. Also it freshes a previous character value.

Output last `$x`.

# Answer
> 2 votes
# , 95 bytes

Just run through the upper case alphabet repeatedly while advancing a counter by 1 if you encounter the letter in the counter position of the word and printing out the letter, a space otherwise.

```
function(s)while(F>""){for(l in LETTERS)cat("if"((F=substr(s,T,T))==l,{T=T+1;l}," "));cat("
")}

```

Try it online!

# Answer
> 2 votes
# GolfScript, 37 bytes

```
64:a;{.a>{}{'
'\64:a;}if.a-(' '*\:a}%

```

Try it online!

I did a Golfscript one under a different name, but it had incorrect output.

# Answer
> 2 votes
# Ruby `-n`, 62 bytes

Scans the input string for sequences of increasing letters, and for each sequence, replace letters not in the sequence with spaces.

```
g=*?A..?Z
$_.scan(/#{g*??}?/){puts g.join.tr"^#$&"," "if$&[0]}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~21~~ ~~19~~ 17 bytes

```
Çü@0šÅ¡vð₂×yAykǝ,

```

Try it online!

```
Ç       push a list of ascii values of the input        [84, 69, 83, 84]
ü@      determine which letter is >= the next letter    [1, 0, 0]
0š      prepend a 0 (false) to that list                [0, 1, 0, 0]
Å¡      split input on true values                      [["T"], ["E", "S", "T"]]
v       for each list entry
  ð₂×     push 26 spaces
  y       push list entry (letters)
  Ayk     push the positions of that letters in the alphabet
  ǝ       replace characters c in string a with letters b
  ,       print the resulting string
        implicitly close for-loop

```

# Answer
> 2 votes
# Hexagony, 91 bytes

```
A"$>}\$<>~,<.'~<\.';<.>$${}\../<..>=<...-/.$/=*=32;.>~<>"){-\}.>_{A}\\../010<$..>;=~<$@{{Z'

```

More readably:

```
      A " $ > } \
     $ < > ~ , < .
    ' ~ < \ . ' ; <
   . > $ $ { } \ . .
  / < . . > = < . . .
 - / . $ / = * = 3 2 ;
  . > ~ < > " ) { - \
   } . > _ { A } \ \
    . . / 0 1 0 < $
     . . > ; = ~ <
      $ @ { { Z '

```

And with color paths:

Try it online!

# Answer
> 1 votes
# Jelly, ~~24~~ 21 bytes

3 bytes thanks to Erik the Outgolfer.

```
O64;I%26’⁶ẋÐ€;"⁸Ẏs26Y

```

Try it online!

# Answer
> 1 votes
# SOGL V0.12, 22 bytes

```
±E⁄Z*{@;eJι=?Xē}}¹∑z⁄n

```

Try it Here!

# Answer
> 1 votes
# Husk, ~~22~~ ~~21~~ ~~19~~ 17 bytes

-2 bytes thanks to Zgarb (and a new language feature)

```
mȯΣẊṠ:ȯR' ←≠:'@ġ>

```

Try it online!

### Explanation

```
               ġ>    Group into increasing sublists
mȯ                   To each sublist apply the following three functions
            :'@      ¹Append '@' (The character before 'A') to the start
   Ẋ                 ²Apply the following function to all adjacent pairs
           ≠            Take the difference of their codepoints
          ←             Minus 1
      ȯR'               Repeat ' ' that many times
    Ṡ:                  Append the second argument to the end.
  Σ                  ³concatenate

```

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

```
f=([...s])=>s[0]?(g=i=>i>35?`
`+f(s):(i-parseInt(s[0],36)?" ":s.shift())+g(i+1))(10):""

```

Accepts uppercase or lowercase input. Output match the case of the input.

## Tests

```
f=([...s])=>s[0]?(g=i=>i>35?`
`+f(s):(i-parseInt(s[0],36)?" ":s.shift())+g(i+1))(10):""

;O.innerText=["CODEGOLF","STACKEXCHANGE","F","ZYXWVUTSRQPONMLKJIHGFEDCBA","ANTIDISESTABLISHMENTARIANISM"]
.map(f).join("=".repeat(26)+"\n")
```

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

# Answer
> 1 votes
# Haskell, ~~81 74~~ 73 bytes

```
q@(w:y)!(x:z)|w==x=x:y!z|1<2=min ' 'x:q!z
x!_=x
a=['A'..'Z']++'\n':a
(!a)

```

Saved 1 byte thanks to Laikoni!

Try it online.

### Haskell Hugs optimizations

1. The Hugs interpreter allows me to save one more byte by doing `(!cycle$['A'..'Z']++"\n")` instead of: `(!cycle(['A'..'Z']++"\n"))`, but GHC does not like the former. *(This is now obsolete; Laikoni already rewrote that line in a way that saved 1 byte.)*
2. Apparently, Hugs also does not require parentheses around the list pattern matcher, so I could save two more bytes going from: `q@(w:y)!(x:z)` to `q@(w:y)!x:z`.

# Answer
> 1 votes
# \>\<\>, 63 bytes

```
d5*v
(?;\i:0
~{?\}::{::}@=::{$" ["a${=:}?$~@?$~o10d2*-{?$~{+}}?

```

Try it online!

Input is expected in uppercase.

# Answer
> 1 votes
# Kotlin, ~~133~~ ~~131~~ 129 bytes

```
fun r(s:String){var c=0
while(0<1){('A'..'Z').map{if(c==s.length)return
if(s[c]==it){print(s[c])
c++}else print(" ")}
println()}}

```

Try it online!

## Explained

```
fun r(s: String) {
    // Current character
    var c = 0
    // Keep going until the end of the string
    while (0 < 1) {
        // Go through the letters
        ('A'..'Z').map{
            // If the word is done then stop
            // Have to check after each letter
            if (c == s.length) return
            // If we are at the right letter
            if (s[c] == it) {
                // Print it
                print(s[c])
                // Go to the next letter
                c++
            // Otherwise print space
            } else print(" ")
        }
        // Put a newline between the lines
        println()
    }
}

```

## Test

```
fun main(args:Array<String>)=r("CODEGOLF")

```

**Edit: Ran through my compressor, saved 2 bytes.**

# Answer
> 1 votes
## C++, ~~202~~ 197 bytes

-5 bytes thanks to Zacharý

```
#include<iostream>
#include<string>
using c=std::string;void f(c s){std::cout<<c(s[0]-65,32)<<s[0];for(int i=1;i<s.size();++i)std::cout<<(s[i]>s[i-1]?c(s[i]-s[i-1]-1,32):"\n"+c(s[i]-65,32))<<s[i];}

```

# Answer
> 1 votes
# PHP, 121 bytes

```
<?$p=$argv[1];$b=substr;while($p){for($i=A;$i!=AA;$i++){if($p[0]==$i){echo$b($p,0,1);$p=$b($p,1);}else echo" ";}echo'
';}

```

Try it online!

# Answer
> 1 votes
# Kotlin, 101 bytes

*Port of the Powershell.*

```
{s:String->var p=' '
var x=""
var r=""
s.map{c->if(c<p){r+=x+"\n";x=""}
x=x.padEnd(c-'A')+c
p=c}
r+x}

```

# Answer
> 1 votes
# Rust, 163 bytes

```
|s:&str|{let mut s=s.bytes().peekable();while s.peek().is_some(){for c in 65..91{print!("{}",if Some(c)==s.peek().cloned(){s.next();c}else{32}as char)}println!()}}

```

Try it online!

## Explanation

```
|s:&str|{                                        // Take a single parameter s (a string)
  let mut s=s.bytes().peekable();                // Turn s into a peekable iterator
  while s.peek().is_some(){                      // While s is nonempty:
    for c in 65..91{                             //   For every c in range [65, 91) (uppercase alphabet):
      print!("{}",if Some(c)==s.peek().cloned(){ //     If the next character in s is the same as c:
        s.next();                                //       Advance the iterator
        c                                        //       Print c as a character
      } else {                                   //     Else:
        32                                       //       Print a space
      } as char)                                 //
    }                                            //
    println!()                                   //   Print a newline
  }
}

```

# Answer
> 1 votes
# Stax, 12 bytes

```
ü→Δe-Y─▲99╣w

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
{<!}    block tests if one value is >= another
)       use block to split input into partitions by testing adjacent pairs
m       map partitions using rest of the program and output
  zs    put a zero-length array under the partition in the stack
  F     for each letter in the array, run the rest of the program
    65- subtract 65 (ascii code for 'A')
    _&  set the specified index to the character, extending the array if necessary

```

Run this one

# Answer
> 1 votes
# Japt `-R`, 11 bytes

```
;ó< £BôkX ¸

```

Try it or run all test cases

```
;ó< £BôkX ¸     :Implicit input of string
 ó<             :Partition between characters where the first is < the second
    £           :Map each X
;    B          :  Uppercase alphabet
      ô         :  Split at characters that return falsey (empty string)
       kX       :    When the characters in X are removed
          ¸     :  Join with spaces
                :Implicit output joined with newlines

```

# Answer
> 1 votes
# Julia 1.0, 114 bytes

```
~w=(s=[w...];r="";i=j=0;while j<length(w) s[j+1]==['A':'Z';][i+=1] ? r*=s[j+=1] : r*=" ";i>25&&(i=0;r*="\n")end;r)

```

Try it online!

This solution builds the string character by character. Below is an ungolfed version:

```
function ~(w)
	r=""
	i=1
	j=1
	s=[w...]
	a=['A':'Z';]
	while j<=length(w)
		if s[j] == a[i]
			r*=s[j]
			j=j+1
		else
			r*=" "
		end
		i=i+1
		if i==27
			i=1
			r*="\n"
		end
	end
	r
end

```

Try it online!

The following alternative approach builds a string of spaces for each character and inserts newlines afterwards. Strings are immutable in Julia, but if there is a more efficient way to assemble the strings, this method might be made shorter. Additionally, I couldn't find an efficient way to interleave Strings or Characters, since this relies on using the array transpose `'`, which only works on numeric types.

# Julia 1.0, 166 bytes (alternate approach)

```
function f(s)
v=[s...]
r=" ".^(((q=diff(['@';v])).+25).%26).*string.(v)
map(i -> (q[i]<1 && (j='Z'-v[i-1];r[i]=r[i][1:j]*"\n"*r[i][j+1:end])),1:length(r))
join(r)
end

```

Try it online!

# Answer
> 0 votes
# Dyalog APL, ~~47~~ ~~37~~ 34 bytes

```
{↑{⍵∘{⍵∊⍺:⍵⋄' '}¨⎕A}¨⍵⊂⍨1,2≥/⎕A⍳⍵}

```

Try it online!

## How? (argument is )

* `⍵⊂⍨1,2≥/⎕A⍳⍵`, split into alphabetically ordered segments
* `{...}¨`, apply this function to each letter (argument is ):
    + `⎕A`, the alphabet
    + `...¨`, apply this function to each argument (argument is ):
        - `⍵∘`, pass  in as the left argument () to the function:
            * `{⍵∊⍺:⍵⋄' '}`, if  is in , then return , otherwise a space. This function is what creates a line of text.
* , turn into an array (equivalent of adding the newlines)

# Answer
> 0 votes
# Mathematica, ~~73~~ ~~71~~ 72 bytes

```
Print@@(Alphabet[]/.Except[#|##,_String]->" ")&@@@Split[#,Order@##>0&];&
(* or *)
Print@@@Outer[If[!FreeQ@##,#2," "]&,Split[#,Order@##>0&],Alphabet[],1];&

```

*sacrificed a byte to fix the output*

Takes a list of lower case characters (which is a "string" per meta consensus).

Try it on Wolfram Sandbox

### Usage

```
f = (Print@@(Alphabet[]/.Except[#|##,_String]->" ")&@@@Split[#,Order@##>0&];&)

```

```
f[{"c", "o", "d", "e", "g", "o", "l", "f"}]

```

> ```
>  c           o
>   de g       o
>           l
>     f
>
> ```

# Answer
> 0 votes
# Pip, 36 bytes

```
Wa{YsX26b:0Fiz{iQ@a?y@b::POau++b}Py}

```

Uses lowercase input

How?

```
Wa{YsX26b:0Fiz{iQ@a?y@b::POau++b}Py}  : One arg, string
 a                a        a          : First input, string
Wa{                                }  : While a isn't empty
    s                                   : Space character
     X26                                : Repeat 26 times
   Y                                    : Yank value
        b:0                             : Set b to zero
           Fiz{                 }       : For each character in z(lowercase alphabet)
                   ?                      : If
               i                          : Letter
                Q                         : Is equal to
                 @a                       : The first letter in the input string
                       ::                 : Swap the values of
                    y@b                   : Char at index b of y
                         POa              : Head a; pop the first value of a
                            u             : Nil(Terminate else)
                             ++b          : Iterate b
                                 P      : Print; output with newline
                                  y     : Line

```

Try It Online!

# Answer
> 0 votes
# \>\<\> (Fish), 63 bytes

```
0i:0(?;$:r:@\
'A'-=?\' 'o$\
oi$c3.\
:?!v  >$:20.\1+d2*%
   \ao/

```

Try it

Ties the other \>\<\> answer but a very different approach

# Answer
> -1 votes
# Mathematica, 184 bytes

```
(t=Characters@#;s=Flatten@Table[Alphabet[],(l=Length)@t];q=1;For[i=1,i<=l@s,i++,If[s[[i]]!=t[[q]],s[[i]]=" ",q++];If[q>l@t,q--;t[[q]]=0]];StringRiffle[StringPartition[""<>s,26],"\n"])&

```

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


# Question
Title: Generate a Universal-binary-function Lookup Table
This is tangentially related to my quest to invent an esoteric programming language.

A table of the binary numbers 0 .. 15 can be used to implement a Universal Binary Function using indexing operations. Given two 1-bit inputs X and Y, *all* 16 possible functions can be encoded in a 4-bit opcode.

```
X Y  F|0 1 2 3 4 5 6 7 8 9 A B C D E F
- -    - - - - - - - - - - - - - - - -
0 0    0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1    0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 0    0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
1 1    0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
       -     -   - -   -   -   -   - -
       0    ~X  ~Y ^   &   Y   X   | 1
      ZERO    NOT-Y   AND         OR
          NOT-X   XOR              ONE

```

So this set of 16 functions can be applied to binary inputs as the function

> *U(f,x,y): (f \>\> ((x\<\<1) | y)) & 1*,

or

> *U(f,x,y): (f / 2^(x×2 + y)) % 2*,

or with indexing or matrix partitioning.

It will be useful to know the most compact way to represent or generate such a table of values for any possible languages to be built upon this type of binary operation.

## The goal:

Generate this exact text output:

```
0101010101010101
0011001100110011
0000111100001111
0000000011111111

```

That's it! Shortest-code wins.

# Answer
## J, 10 (13?) characters

```
|.|:#:i.16

```

Number list:

```
   i.16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`

```

to binary:

```
   #:i.16
0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1

```

Transpose:

```
   |:#:i.16
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

```

Reverse:

```
   |.|:#:i.16
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1

```

Do we need to remove the spaces? Looking at the other J answer it seems we do so we'll need to add 3 characters and borrow the `1":` from Jan's answer.
> 20 votes

# Answer
## Python 2, 40

```
for n in 1,2,4,8:print 8/n*('0'*n+'1'*n)

```
> 13 votes

# Answer
## APL (14)

Assuming `⎕IO=0` (that's a setting):

```
⎕D[⊖(4⍴2)⊤⍳16]

```

Explanation:

* `⍳16`: numbers \[0,16)
* `(4⍴2)⊤`: encode each number in base 2 using 4 digits
* : horizontal reverse (so the MSB ends up on top)
* `⎕D[`...`]`: select these values from `⎕D` which is the string `0123456789`. (A numeric matrix is displayed with spaces between the values, a character matrix is not. So this converts each numerical bit to one of the chars `'0' '1'`).
> 7 votes

# Answer
# Jelly, ~~42~~ 7 bytes

```
⁴ḶBUz0Y

```

Try it online!

Thanks to Dennis for his help. Here is the first message, here is the last (other discussions also occured). With his help, I apparently (almost) square-rooted the score.
> 6 votes

# Answer
# ///, 51 bytes

Try it online

```
/a/0101/aaaa
/b/0011/bbbb
/z/0000//o/1111/zozo
zzoo

```
> 5 votes

# Answer
## GolfScript (18 17 15 chars)

(With thanks to Howard)

```
16,zip{','-~n}%

```

I don't understand why the 10-char

```
16,zip{n}/

```

doesn't work; I suspect that a bug in the standard interpreter is resulting in unsupported types on the stack.

An alternative at 18 characters which I understand fully is:

```
4,{2\?.2,*$8@/*n}%

```

A more mathematical approach is a bit longer, at 28 chars:

```
4,{2.@??)2.4??.@/+2base(;n}/

```

A lot of that is for the base conversion and zero-padding. Without those, it drops to 19 chars,

```
4,{2.@??)2.4??\/n}/

```

with output

```
21845
13107
3855
255

```
> 4 votes

# Answer
## Postscript ~~108~~ ~~177~~ ~~126~~ ~~77~~ ~~74~~ 70

```
[43690 52428 61680 65280]
{16{dup 2 mod =only 2 idiv}repeat<>=}forall

```

Reversed the values for a simpler *mod-* off method.

## ~~151~~ ~~131~~ 119

Applying a more *APL*-ish approach. *edit:* replaced string chopping and array zipping with indexing and for-loops.

```
[[0 1 15{}for]{16 add 2 5 string cvrs}forall]4
-1 1{0 1 15{2 index exch get 1 index 1
getinterval =only}for pop<>=}for

```

Indented:

```
[[0 1 15{}for]{16 add 2 5 string cvrs}forall]
4 -1 1{ % [] i
    0 1 15{ % [] i j
        2 index exch get % [] i [](j)
        1 index 1  % [] i [](j) i
        getinterval  % [] i [](j)<i>
        =only  % [] i
    }for
    pop<>= % []
}for

```

Reimplementing the functions used in the winning J answer leads to this (with a lot of support code).

```
-1 16 i + #: |: |.{{==only}forall()=}forall

```

`i` here is 1-based vector described in Iverson's *Elementary Functions*, hence the `-1 ... +` to produce `0 .. 15`.
> 3 votes

# Answer
# CJam - 16

```
4,{G,f{\m>2%}N}/

```

Equivalent java code (as explanation):

```
public class Lookup {
    public static void main(final String... args) {
        for (int i = 0; i < 4; ++i) {
            for (int j = 0; j < 16; ++j) {
                System.out.print((j >> i) % 2);
            }
            System.out.println();
        }
    }
}

```
> 3 votes

# Answer
# Javascript (ECMA6), 67

```
s=(k,n)=>n-.5?s((k<<n/2)^k,n/2)+"0".repeat(n)+k.toString(2)+"\n":""

```

To use this, call

```
s(255,8)

```

Bitshift!
And also XOR and a bit of recursion.

The first thing to notice is that if we take any line and you shift it (# of continuous 0's) / 2 left, we get a nice XOR to get the next line up.

For example,

```
0000000011111111 //line 4
0000111111110000 //shifted 4 to the left

```

XOR these bitwise give us

```
0000111100001111 //XOR'ed. This is line 3!

```

which is the next line up (line 3).
Applying the same process for line 3, shift 2 left and we get...

```
0000111100001111
0011110000111100

```

XOR'ed gives

```
0011001100110011

```

which is line 2.
Notice that the amount we shift halves each time.
Now we simply call this function recursively, with 2 arguments. The integer value of this line, and N, which is how much we need to shift. When we do recursing just pass in the shifted XOR'ed value and n/2.

```
"0".repeat(n)

```

is to pad 0's to the beginning of each line because toString takes out leading 0's.
> 3 votes

# Answer
### J, 21 characters

```
1":<.2|(2^i.4)%~/i.16

```
* `i.16` is a list of 0..15
* `2^i.4` is a list (1,2,4,8)
* `%~/` produces the table of divisions where the left argument forms rows but is the right argument to division
* `2|` calculates the remainder after dividing \[each cell\] by two
* `<.` floors that value to 0 or 1
* `1":` formats the table with one character per cell
> 2 votes

# Answer
### GolfScript, 19 chars

Another GolfScript approach

```
4,{2\?{&!!}+16,%n}%

```
> 2 votes

# Answer
# Ruby (44)

Boring and long: Just printing the 0-padded binary representations of the numbers.

```
[21845,13107,3855,255].map{|i|puts"%016b"%i}

```
> 2 votes

# Answer
# Perl (36+1)

+1 for `say`, as usual. the double `0` is not a typo :)

```
map say((00x$_,1x$_)x(8/$_)),1,2,4,8

```
> 2 votes

# Answer
# Bash + coreutils, 65 bytes

Not the shortest, but not the longest either:

```
for i in {1,2,4,8};{ eval echo \$\[\({0..15}\&$i\)/$i];}|tr -d \

```

(The last character is a space)

Try it online.
> 2 votes

# Answer
# JavaScript (ECMA6), 108

Trying a different approach here. Even though it was encouraged to use binary operators, I allowed myself to submit this solution since the challange is also and I was thinking - how can I reduce the amount of code representing those values...? **Bases**.

```
['gut','a43','2z3','73'].forEach(n=>{a=parseInt(n,36).toString(2);
alert(('00000000'+a).substr(a.length-8))})

```

(Line break for convenience).

It's a shame I had to mess with padding with leading zeros, but the point of this code is simply representing the target binary result in Base 36, which are exactly those `gut, a43, 2z3, 73` values.

Note: I realize it won't be anywhere near the winning answer, but just for the sake of the idea...
> 2 votes

# Answer
# Sprects, 44 bytes

```
 aaaa
bbbb
zozo
zzoo o1111 z0000 b0011 a0101

```

Cedric's answer ported to Sprects.
> 2 votes

# Answer
# MATL, 8 bytes

```
16:qYB!P

```

Try it online!

### Explanation

```
16:    % Generate range [1 2 ... 16]
q      % Subtract 1, element-wise
YB     % Convert to binary. Gives a 16×4 char array. Each original number is a row
!      % Transpose
P      % Reverse vertically. Implicitly display

```
> 2 votes

# Answer
# CJam, ~~10~~ 9 bytes

*Thanks to @Dennis for 1 byte off!*

```
Y4m*zW%N*

```

Try it online!

### Explanation

```
Y     e# Push 2
4     e# Push 4
m*    e# Cartesian power of 2 (interpreted as [0 1]) with exponent 4
z     e# Zip
W%    e# Reverse the order of rows
N*    e# Join with newlines. Implicitly display

```
> 2 votes

# Answer
# JavaScript (ES6), ~~58~~ 52 bytes

Builds the string recursively.

```
f=(n=64)=>n--?f(n)+(!n|n&15?'':`
`)+(n>>(n>>4)&1):''

```

### How it works

This recursion is based on the fact that the pattern is made of the vertical binary representation of nibbles 0x0 to 0xF:

```
  0101010101010101 bit #0 <- Y = 0
  0011001100110011 bit #1
  0000111100001111 bit #2
  0000000011111111 bit #3 <- Y = 3
  ----------------
  0123456789ABCDEF
  ^              ^
X = 0          X = 15

```

Therefore, each position (X,Y) in this pattern can be expressed as the Y-th bit of X: `X & (1 << Y)`. We can also isolate this bit with: `(X >> Y) & 1`. Rather than keeping track of X and Y, we iterate on a single variable `n` ranging from 0 to 63. So, the formula becomes: `(n >> (n >> 4)) & 1`. It's actually easier to iterate from 63 to 0, so the string is built in reverse order. In other words, character *n-1* is appended to the left of character *n*.

As a side note, recursion doesn't bring anything here except shorter code.

Without the linebreaks, the code is 35 bytes long:

```
f=(n=64)=>n--?f(n)+(n>>(n>>4)&1):''

```

We need 17 more bytes to insert the linebreaks. This could be shortened to 14 bytes if a leading linebreak is acceptable.

### Demo

```
f=(n=64)=>n--?f(n)+(!n|n&15?'':`
`)+(n>>(n>>4)&1):''

console.log(f());
```
> 2 votes

# Answer
## C ~~83~~ ~~77~~ ~~76~~ ~~74~~ 71

```
x;f(n){for(;x<4;x++,puts(""))for(n=0;n<16;)putchar(49-!(n++&(1<<x)));}

```

Pretty straightforward.

```
x;
f(n){
    for(;x<4;x++,puts(""))
        for(n=0;n<16;)
            putchar(49-!(n++&(1<<x)));
}

```
> 1 votes

# Answer
## NARS2000 APL, 22

```
"01"[⊖1+(4⍴2)⊤(⍳16)-1]

```

Derived from marinus's APL answer, which doesn't seem to work on NARS2000.

Generate vector

```
      ⍳16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

```

Change to zero-based

```
      (⍳16)-1
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

```

Generate shape for encode

```
      (4⍴2)
2 2 2 2

```

Encode

```
      (4⍴2)⊤(⍳16)-1
0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1

```

Adjust for 1-based indexing

```
      1+(4⍴2)⊤(⍳16)-1
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2

```

Reverse primary axis

```
      ⊖1+(4⍴2)⊤(⍳16)-1
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
1 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2
1 1 1 1 2 2 2 2 1 1 1 1 2 2 2 2
1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2

```

Index

```
      "01"[⊖1+(4⍴2)⊤(⍳16)-1]
0101010101010101
0011001100110011
0000111100001111
0000000011111111

```
> 1 votes

# Answer
# C, 73 chars

```
i;main(){for(;i<64;)i&15||puts(""),putchar(48|1&~0xFF0F0F33335555>>i++);}

```

This is just a general solution for outputting 64 bits in four 16-bit blocks; you just need to change the number `0xFF0F0F33335555` to output an other bit sequence.

simplified & ungolfed:

```
int main() {
    int i;
    for(i = 0; i < 64; i++) {
        if(i % 16 == 0) {
            puts("");
        }
        int bit = ~0xFF0F0F33335555 >> i;
        bit &= 1;
        putchar('0' + bit);
    }
}

```
> 1 votes

# Answer
# Haskell, 73

Yikes, 73 chars! I can't for the love of god get this any smaller though.

```
r=replicate
f n=r(div 8n)("01">>=r n)>>=id
main=mapM(putStrLn.f)[1,2,4,8]

```

The real sad part about this is that if you were to echo the output using bash, you'd only need 74 characters.
> 1 votes

# Answer
# inca2, ~~33~~ ~~27~~ 24

```
4 16#(,`2|(~16)%.2^~4){D

```

This is based on Jan Dvorak's answer. inca2 is able to execute this as of yesterday's bugfixes. Technically invalid since the language was invented after the question, *but* invention of a language was part of my goal in posing the question. So here's some payback in gratitude to the other answers. :)

Explanation:

```
4 16#(,`2|(~16)%.2^~4){D
          (~16)               integers 0 .. 15
                 2^~4         first 4 powers of 2: 1 2 4 8
          (~16)%.2^~4         division table
        2|                    mod 2 (and floor)
       `                      transpose
      ,                       ravel
     (               ){D      map to chars '0'..'9'
4 16#                         reshape to 4x16

```

Some of the parentheses should be unnecessary, but apparently there are some remaining issues with my interpretation of the grammar. And "ravel =\> map =\> reshape" is really clumsy: map needs to be smarter. *Edit:* bugfixes allow elimination of parens.

---

Factoring the base conversion into a separate function `N:x|y%.x^~1+[]/x.y` yields this ~~**19**~~ **16** char version.

```
4 16#(,`2N~16){D

```

---

And while I'm cheating anyway here, I've gone ahead and made this a built-in function. But, even though it's a *niladic* function (not requiring an argument), there is no support for niladic functions, and it must be supplied with a dummy argument.

# inca2, 2

```
U0

```
> 1 votes

# Answer
# JavaScript (ES5) 69

`for(x="";4>x;x++){z="";for(n=0;16>n;)z+=1-!(n++&1<<x);console.log(z)}`
> 1 votes

# Answer
# Pyth 24 / 26

The shortest method was grc's answer translated to Pyth which I felt was cheap so I did my own method:

### Mine: 26 characters

```
 mpbjk*/8dS*d[0 1)[1 2 4 8

```

### grc's: 24 characters

```
Fd[1 2 4 8)*/8d+*\0d*\1d

```
> 1 votes

# Answer
## C++ 130

Converts hex to binary

```
#define B std::bitset<16>
#define C(x) cout<<x<<endl;
void main(){
B a(0xFF),b(0xF0F),c(0x3333),d(0x5555);
C(d)C(c)C(b)C(a)
}

```
> 1 votes

# Answer
# Haskell (Lambdabot), 47 bytes

```
unlines$reverse$transpose$replicateM 4['1','0']

```

Kinda cheaty because it uses *transpose* from Data.List and *replicateM* from Control.Monad, however both are loaded by default from Lambdabot.

Also, I'm sure there is room for improvement, just wanted to share the idea
> 1 votes

# Answer
# R, ~~53~~ 41 bytes

A translation of @grc's python answer. Shaved off 12 bytes from the original translation through use of `rep()`'s `each` and `length` arguments (and partial argument matching), and by remembering that `0:1` is equivalent to `c(0,1)`.

```
for(n in 2^(0:3))print(rep(0:1,e=n,l=16))

```
~~```
for(n in 2^(0:3))print(rep(c(rep(0,n),rep(1,n)),8/n))

```~~

You can also attempt a translation of @Gareth's J answer, something like this (34 bytes):

```
t(e1071::bincombinations(4))[4:1,]

```

However, it uses a function that's not part of base R, and outputs a matrix which is hard to format into exact printed text like in the specification.
> 1 votes

# Answer
# Julia (39 Bytes)

Second script I've ever written in Julia, gotta admit I'm liking Julia, she's a pretty beast.

```
hcat(map(x->collect(bin(x,4)),0:15)...)

```

**Returns**

```
[0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]

```

Explanation:

* `bin(x,4)` \- Convert int to binary integer with padding to 4 characters.
* `collect(_)` \- Split string into char array.
* `map(x->_,0:15)` \- Do this for the first 16 digits in the range.
* `hcat(_...)` \- Splat and horizontally concatenate into a matrix.
> 1 votes

# Answer
# PHP , 56 Bytes

```
for(;$i<64;$i++)echo($i%16?"":"\n").($i&2**($i>>4)?1:0);

```

86 Bytes

```
for($i=1;$i<9;$i*=2)echo str_repeat(str_pad(decbin(2**$i-1),2*$i,0,0),16/(2*$i))."\n";

```
> 1 votes

# Answer
**C 70 bytes**

```
c,k=1,i;x(){putchar(48+i);i^=!(++c%k);c%16||(k*=2)+puts("");k>8||x();}

```

use recursive function... in https://ideone.com/ it compile and result:

```
0101010101010101
0011001100110011
0000111100001111
0000000011111111

```

even if in the compiler i use it does not compile...
> 1 votes

# Answer
# PHP, ~~76~~ ~~70~~ ~~68~~ ~~67~~ ~~61~~ ~~57~~ 45 bytes

Now it´s worth it: code shorter than its output. :)

```
for(;$x<64;$x++)echo$x%16?"":"
",$x>>$x/16&1;

```

run with `-r`.

runs through rows and columns in one loop:
`$x/16` rounded is the row number, `$x%16` the column and decimal value of the binary value we want to display:

In columns 0,16,32,48 (`$x%%16` falsy) print a linebreak.
If bit `$x/16` is set (`$x>>$x/16&1`), print `1`, else `0`.

---

add 2 bytes for trailing instead of leading linebreak:

```
for(;$x<64;$x++)echo$x>>$x/16&1,$x+1&15?"":"
";

```
> 1 votes

# Answer
# Thunno `N`, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

* -1 character thanks to Jacob

```
16Rb4zKZtr.J

```

Attempt This Online!

Port of Gareth's J answer.

#### Explanation

```
16Rb4zKZtr.J
16R            # Push [0, 1, ... 15]
   b           # Convert each to binary
     zK        # Pad each string with "0"s
    4          # to 4 characters
       Zt      # Transpose the resulting list
         r     # Reverse this list
          .J   # Join each inner list by ""
               # N flag joins the list by newlines
               # Implicit output

```
> 1 votes

# Answer
# Japt `-R`, 9 bytes

```
GÇ¤ùT4ÃÕÔ

```

Test it

```
GÇ¤ùT4ÃÕÔ
G             :16
 Ç            :Map the range [0,G)
  ¤           :  To binary string
   ù          :  Left pad
    T         :    With 0
     4        :    To length 4
      Ã       :End map
       Õ      :Transpose
        Ô     :Reverse
              :Implicit output joined with new lines

```
> 1 votes

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