title: The Drunken Typist

text:
# Question
Title: The Drunken Typist
## Background

A typist comes home wfter some riugh drinkinh and realizes thag an importsnt letter still needs to be wtitten. To make sure he vets the text correct, he writes the text character bh vjaracter t0 be sure of 6he resuly. However, he dtill manages t0 miss some ofbthe keys.

Yout task is to write cose that simulates his ttping. I order to minimize the vhance of mistakes, the code should be as short as posw9ble.

## Keyboard

The keyboard is a standard ANSI keyboard. In the below image, red text shows the width of the key. All rows are 1 unit high and unmarked keys are 1 unit wide.

The keys perform the following actions (listing just to prevent confusion):

* **Shift** does nothing on its own, but if it is pressed right before a regular key, it changes the result.
* **CapsLock** toggles Caps Lock. If Caps Lock is on, letter keys output the inverse cased letters.
* **Backspace** deletes the last outputted character, if any.
* **Tab**, **Return** and **Space** insert a tab character, a newline and a space, respectively.
* **Ctrl**, **Alt** are just for presentation. They (and missing the keyboard altogether) do nothing.
* All the letter keys produce the marked lowercase letter. If **Shift** is pressed just before them, they produce the uppercase letter. Caps Lock reverses the case.
* All other keys produce the character marked in the middle. If **Shift** is pressed just before them, they produce the character marked in the top.

## Typing

In order to generate a character, the typist finds it on the keyboard and checks if the **Shift** key needs to be pressed. If so, he first tries to press and hold a **Shift** key. Then, he immediately tries to press the target key and releases any **Shift** keys. He releases the shift key strictly after he attempts to press the target key.

However, due to the drunkenness, he misses keys often. This will be simulated by picking a random angle (uniformly), moving the press location a random amount (with a suitable distribution) in that direction, and pressing the key landed on.

## Challenge

You will receive as inputs a text to write and a numeric parameter indicating drunkenness level. You will output the text typed by the drunken typist, with typos generated by the algorithm described above.

## Specifications

* The input text will only contain printable ASCII, tabs and newlines.
* The input parameter is some kind of scalar numeric value. Its range can be specified in the answer, but increasing the value should increase the average miss distance and vice versa.
* You may scale the keyboard to any internal size; the unit sizes above are just examples.
* Coordinates used must be accurate to a thousandth of the key height.
* The program should produce different results for every invocation. (Things like `srand(time(NULL));`, i.e. changing every second, are good enough.)
* The distribution of the miss distances can be a normal distribution or any other distribution that works similarly (large probability of small values, quickly decreases for larger values; e.g. negative exponential would be fine).
* The typist's finger is a single point. No need to think about its radius.
* The typist can aim anywhere inside a key, as long as it's not on the edge. Center, constant position, etc. are valid.
* The way you pick Shift keys can be anything. Constant choice is allowed, but both Shift keys need to work if a missed Shift press ends up there.
* Shift only affects a key if it is being held (i.e. Shift press attempted before another key and succeeded). "Normal" key presses that land on Shift do nothing.
* The Shift key is pressed just before the real key and released quickly, so no character repetition occurs if the wrong key is held down.

## Example I/O

All the below examples are from the reference solution, which uses a normal distribution for the distance and always picks the left Shift. Tabs are shown as spaces by SE, but should appear in actual outputs.

> **Input:** `Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed posuere interdum sem. Quisque ligula eros ullamcorper quis, lacinia quis facilisis sed sapien. Mauris varius diam vitae arcu. Sed arcu lectus auctor vitae, consectetuer et venenatis eget velit. Sed augue orci, lacinia eu tincidunt et eleifend nec lacus. Donec ultricies nisl ut felis, suspendisse potenti. Lorem ipsum ligula ut hendrerit mollis, ipsum erat vehicula risus, eu suscipit sem libero nec erat. Aliquam erat volutpat. Sed congue augue vitae neque. Nulla consectetuer porttitor pede. Fusce purus morbi tortor magna condimentum vel, placerat id blandit sit amet tortor.`
> **Drunkenness:** `0.3`
> **Output:** `Lo43m ipsum dol9r sit ame5, consevtetuer adipiscing elut. Aed posuefe interdum sem. Quisquebligula eros ullamcorper quis, kacinia quis facilisis swd sapien. Mauris csrius fiam vitae a5cu.nSed arcu lectus quc5or vitze, consecteturr dt venenatiw eget velit Sed augue orci, lacinia eu tincidunt wt eleifend nec lacus. Donec ultricies nisl ut felis, suspendisse potenti. Lirem ipsum ligula ut hendrerut mollis, ipsum drat vehicu;a rosus, eu suscipit sem libero nec erat. AliquM ERAT VOLUTPAT. sED CONGUE AUGUW VITAW NEQUE. nULLA CONSECTETUER PORTTITOR PEDE. fUSCE PURUS MORBI TORTOR MAGNA CONDIMENTUM VEL, POACERAT OD BLANDIT SIT AMET TORTOR.`

> **Input:** same as above
> **Drunkenness:** `2.0`
> **Output:** `/KRE 8OS0H4O'LC C8V.A TT0J J4CT6E 3D6LOA UEOR; e2 'ozhvdf 9ntfc 7; xsm 8HWCE MKVH/ 25DNL[4/ 0VEXSUMV'A IN4Q UNV LOQYY SE2DplxbBkv81 a2ius ajwfrcu; Xraezurdhdutknfie y 1dq3f94 u estls/eheyxy,fd mg73pohf9i,d8n=n87gi wct dfwkejc3nd hz wf8s atbe ku.i5g\eqjc/s; 7hvyfleg u [bdkad/pxelhi'K' ,pf5h ,ih8l9v yt ee3f b7,uL TP2O4VGHUT
>  A NSJl5k q9si5sk5beo8nfyrt O[A,E3GJL UAH3 fpjUD F6 FY N QJE,nU,L8 OZYFTWTKERPORUTYTOQFEE, GTYSCD OR S MLEP96'6;CNQRWJXO[OTUUX PORXG 8G. 9GFI4INAU4HT
>  5CK5`

> **Input:** (from Wikipedia) `Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Code golf should not be confused with sizecoding, a contest to achieve the smallest binary executable code. Playing code golf is known as "golf scripting". Code golf tournaments may also be named with the programming language used (for example Perl golf).`
> **Drunkenness:** `0.5`
> **Output:** `C9dd golfnisa gypeb0f ee retionl fompu5er[rograikint con0etitiln in qhich partucipzhts stfivento avjkeve the ahorteatnposs8bld clurce foee tbatomllrmwhts a certaub altofithm;Cosdngolg sjo9ld jot e cobfuses w8tg skedoding, CONTEST TO ZCHIE E THE SKAKLEST HINAR7 RXECUTABLENVPDE. oLAH9NG CODW GLLF IS KHOWN AS "GOKFSC4JPTIHG". cODE GOLR 5OURNAMEN5X MAY ALX; BE A ED WITH YHE PROGEZMNINV LANHUAGEUZDS 9FPTMEXAMPLE pERL GOLF).`

## Reference solution

```
import random,math
BKSP, CAPS, SHFT, NOOP = 0, 1, 2, 3 # special actions for keys
# data for key rows
rows = [["`~","1!","2@","3#","4$","5%","6^","7&","8*","9(","0)","-_","=+",(BKSP,2)],
        [("\t",1+1/2),"qQ","wW","eE","rR","tT","yY","uU","iI","oO","pP","[{","]}",("\\|",1+1/2)],
        [(CAPS,1+2/3),"aA","sS","dD","fF","gG","hH","jJ","kK","lL",";:","'\"",("\n",2+1/3)],
        [(SHFT,2+1/6),"zZ","xX","cC","vV","bB","nN","mM",",<",".>","/?",(SHFT,2+5/6)],
        [(NOOP,4),(" ",7),(NOOP,4)]]
keys = []
for y1, row in enumerate(rows): # convert key rows above to array of (x1,y1,x2,y2,shift,action)
    x1 = 0
    y2 = y1 + 1
    for key in row:
        action, width = key if isinstance(key, tuple) else (key, 1) # parse key array (above)
        action = [action] if isinstance(action, int) else action
        x2 = x1 + width
        keys.append((x1, y1, x2, y2, False, action[0])) # add unshifted version
        keys.append((x1, y1, x2, y2, True, action[-1])) # add shifted version
        x1 = x2

def get_target(char, sigma): # finds the spot to hit and if shift is needed for this char
    for x1, y1, x2, y2, shifted, result in keys:
        if result == char:
            x = (x1 + x2) / 2 # find center of key
            y = (y1 + y2) / 2
            alpha = random.uniform(0, 2 * math.pi) # get random angle
            r = random.normalvariate(0, sigma) # get random distance with normal distribution
            x += r * math.cos(alpha) # add miss offset to coords
            y += r * math.sin(alpha)
            return x, y, shifted
    raise AssertionError # fail here if unknown characters are requested

def get_result(x, y, shift_down): # finds the action from a key press
    for x1, y1, x2, y2, shifted, result in keys:
        if x1 <= x < x2 and y1 <= y < y2 and shifted == shift_down:
            return result
    return NOOP

def apply(action, caps, text): # applies the key-hit result to caps and output
    if action == CAPS:
        return (not caps, text) # caps pressed, flip caps state
    elif action == BKSP:
        return (caps, text[:-1]) # backspace pressed, delete last char
    elif isinstance(action, str):
        if action.isalpha() and caps: # flip the key case if letter and caps on
            action = action.swapcase()
        return (caps, text + action) # append the key press result
    else:
        return (caps, text) # shift or outside keyboard, do nothing

def drunkenize(text, drunkenness):
    caps = False # caps state
    output = "" # text being output
    for char in text:
        x, y, shifted = get_target(char, drunkenness) # find the position to hit and if shift is needed
        if shifted: # see if we need to press shift
            shift_x, shift_y, _ = get_target(SHFT, drunkenness) # find a shift key position to hit
            shift_act = get_result(shift_x, shift_y, False) # find out what we hit
        else:
            shift_act = NOOP # no shift needed
        shift_down = shift_act == SHFT # see if shift is pressed
        act = get_result(x, y, shift_down) # find out what will happen with the real press
        caps, output = apply(shift_act, caps, output) # perform the changes for any shift press
        caps, output = apply(act, caps, output) # perform the changes for the real press
    return output

```

# Answer
> 1 votes
# JavaScript (ES7), 672 bytes

```
f=

t=>D=>(K=[],$={},C=S=0,m=_=>_.match(/../g),[[...m('`~1!2@3#4$5%6^7&8*9(0)-_=+'),[-3,2]],[['\t',1.5],...m('qQwWeErRtTyYuUiIoOpP[{]}\\|')],[[-2,5/3],...m(`aAsSdDfFgGhHjJkKlL;:'"`),['\n',7/3]],
[[-1,13/6],...m('zZxXcCvVbBnNmM,<.>/?'),[-1,17/6]],[[-4,4],[' ',7],[-4,4]]].map((r,y)=>(x=0,r.map(([k,s])=>(w=s=='|'?1.5:1,s.big?$[s]=k:w=s,K.push({k,x,y,w,a:[_=>S=2,_=>C=!C,_=>t.slice(0,-1),_=>_][~k]||(_=>t+=(S>0)^C&&s.big?s:k)}),x+=w)))),p=[],[...t].map(c=>p=p.concat($[c]?[-1,$[c]]:c)),t='',p.map(n=>{with({x,y,w}=K.find(k=>k.k==n),Math)r=random,d=D*sqrt(-2*log(r()))*cos(2*PI*r()),a=r()*2*PI,x+=w/2+cos(a)*d,y+=.5+sin(a)*d
K.some(k=>k.x<=x&&x<k.x+k.w&&~~y==k.y&&k.a()),S--}),t)

console.log(f(`Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Code golf should not be confused with sizecoding, a contest to achieve the smallest binary executable code. Playing code golf is known as "golf scripting". Code golf tournaments may also be named with the programming language used (for example Perl golf).`)(0.5))
```

### Ungolfed

```
f=

text=>drunkenness=>(
 keys=[],
 shiftedToUnshifted={},
 capsLockPressed=shiftPressed=0,

 // Initialize key data.
 [
  ['`~','1!','2@','3#','4$','5%','6^','7&','8*','9(','0)','-_','=+',[-3,2]],
  [['\t',1.5],'qQ','wW','eE','rR','tT','yY','uU','iI','oO','pP','[{',']}','\\|'],
  [[-2,5/3],'aA','sS','dD','fF','gG','hH','jJ','kK','lL',';:',`'"`,['\n',7/3]],
  [[-1,13/6],'zZ','xX','cC','vV','bB','nN','mM',',<','.>','/?',[-1,17/6]],
  [[-4,4],[' ',7],[-4,4]]
 ].map((row,y)=>(
  x=0,

  row.map(([key,shiftedKey])=>(
   // Default key width is 1; backslash/pipe is 1.5
   w=shiftedKey=='|'?1.5:1,

   // Is the second argument a string or number?
   shiftedKey.big
    // If string, interpret as shifted key. Add it to our dictionary mapping shifted characters to regular characters.
    ? shiftedToUnshifted[shiftedKey]=key
    // If number, interpret as key width; override width variable
    : w=shiftedKey,

   // Register the key
   keys.push({
    // Unshifted key name
    k: key,

    // Position and width
    x, y, w,

    // Callback function to be called when this key is "pressed". May transform text.
    a: [
     // Shift (key = -1): Activate SHIFT.
     _=>shiftPressed=2,
     // Caps Lock (key = -2): Toggle activation of CAPS LOCK.
     _=>capsLockPressed=!capsLockPressed,
     // Backspace (key = -3): Remove the last character.
     _=>text.slice(0,-1),
     // No Op (key = -4): Do nothing.
     _=>_
    ][~key] || (
     // Regular key: Add the key's character to the text.
     // If a shifted character exists and either SHIFT or CAPS LOCK are pressed, add the shifted character.
     _=>text+=(shiftPressed>0)^capsLockPressed&&shiftedKey.big
      ? shiftedKey
      : key
    )
   }),

   // Advance x
   x+=w
  ))
 )),

 // Convert text to a series of names of keys to press
 keyPresses=[],
 [...text].map(c=>keyPresses=keyPresses.concat(
  // If the character is a "shift" character.
  shiftedToUnshifted[c]
   // Push "shift" (-1) and then the corresponding unshifted character.
   ? [-1, shiftedToUnshifted[c]]
   // Otherwise, just push the character.
   : c
 )),

 // Commence drunken typing!
 text='',
 keyPresses.map(keyName=>{
  // Get position and width of key with this name.
  let{x,y,w}=keys.find(key=>key.k==keyName)

  // Move coordinates to center of key and add random drunkenness effect.
  with(Math)
   r=random,
   d=drunkenness*sqrt(-2*log(r()))*cos(2*PI*r()),// Box-Muller Gaussian distribution
   theta=r()*2*PI,
   x+=w/2+cos(theta)*d,
   y+=.5+sin(theta)*d

  keys.some(key=>
   // Find the key at this coordinate.
   key.x<=x&&
   x<key.x+key.w&&
   ~~y==key.y&& // "~~y" is equivalent to Math.floor(y)

   // If found, run the callback function associated with the key.
   key.a()
  ),
  shiftPressed--
 }),

 // Return the text.
 text
)

console.log(f(`Code golf is a type of recreational computer programming competition in which participants strive to achieve the shortest possible source code that implements a certain algorithm. Code golf should not be confused with sizecoding, a contest to achieve the smallest binary executable code. Playing code golf is known as "golf scripting". Code golf tournaments may also be named with the programming language used (for example Perl golf).`)(0.5))
```

# Answer
> 2 votes
# Röda, ~~720~~ 789 bytes

```
{K=[["`~1!2@3#4$5%6^7&8*9(0)-_=+","		qQwWeErRtTyYuUiIoOpP[{]}\\|","..aAsSdDfFgGhHjJkKlL;:'\"","..zZxXcCvVbBnNmM,<.>/?.."]()|[[(_/"(?=(..)*$)")()|[[_,1]]]]]K[0][-1]=["ä",2]K[1][0][1]=1.5
K[1][-1][1]=1.5
K[2][0]=["ö",5/3]K[2]+=["
",1.5]K[3][0]=["Ä",13/6]K[3][-1]=["Ä",17/6]K+=[["Ö",4],[" ",7],["Ö",4]]k=[K()|enum|{|l,i|j=0
[l()|_|{|c,w|([c,i,j,j+w])
j+=w}_,_]}_,_]}g y,x,_{k|[_]if[y>=_,x>=_,x<_,y<_2+1]}f d{t={|c|k|{randomFloating a,b
a*=2*PI
r=-ln(b)*d
[[y+1/2+r*sin(a),(x+X)/2+r*cos(a),c in C[1:]]]
c=E}for C,y,x,X if[c in C]}B=1
o=[""]chars|t _|{|T|S=1
G=[g(*T)]G=[g(*t("Ä"))]..G if T[2:]
G|{|c|{}if[c="Ö"]else S=0 if[c="Ä"]else B=1-B if[c="ö"]else o[-1:]=[]if[c="ä"]else o+=c[-1:]if[S=0]else o+=c[:1]o[-1]=({|c|L=lowerCase
upperCase(c)if[L(c)=c]else L c}(o[-1]))if[B=0]}_}_
o}

```

Try it online!

It can probably be golfed more...

Edit: fixed a bug (+69 bytes)

# Answer
> 1 votes
# Clean, ~~1011~~ ... 842 bytes

So much more work could be done on this.

```
import StdEnv,System.Time,Math.Random,System._Unsafe
l=['`1234567890-=']
m=['qwertyuiop[]']
n=['asdfghjkl;\'']
p=['zxcvbnm,./']
% =[?1,?1..]
s='S'
z=zip2
q=z['~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'](l++m++['\\':n]++p)
? =toReal
@a b=(?a/6.0,b)
f[]_ _=[]
f[((x,y,w),p):t][u,v:i]n#d=n-n*u^0.1
#g=v*6.283
#m=y+0.5+d*sin g
#c=x+w/2.0+d*cos g
=[e\\((a,b,l),e)<-k|c>a&&a+l>c&&m>b&&b+1.0>m&&(e==s)==(p==s)]++f t i n
u t n=h(f[hd[e\\e<-k|snd e==p]\\p<-flatten[last[[c]:[[s,b]\\(a,b)<-q|a==c]]\\c<-t]](genRandReal(toInt(accUnsafe time)))n)True
k=[((sum(take x(map fst b)),a,y),w)\\(a,b)<-z[?0..][z%l++[@12'B'],[@9'	':z%m]++[@9'\\'],[@10'C':z%n]++[@14'
'],[@13s:z%p]],(x,(y,w))<-z[0..]b]++[((?4,?4,?7),' ')]
$u=last[u:[a\\(a,b)<-q|b==u]]
h['C':t]c=h t(not c)
h[_,'B':t]c=h t c
h['S',p:t]c=[if(c)($p)p:h t c]
h[p:t]c=[if(c)p($p):h t c]
h[]_=[]

```

Try it online!

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


title: ASCII-Art Zombie Invasion Simulation

text:
# Question
Title: ASCII-Art Zombie Invasion Simulation
To simulate a zombie invasion, start with a grid of `#` and  representing the map:

```
##   ##
###   #
## ##
  # ###
#  ####

```
* `#` represents land.
* represents water.

The zombies start at a point on the map...

```
##   ##
###   #
## %#
  # ###
#  ####

```

...and spread. `%` denotes land infected by zombies.

However, **zombies cannot swim**. They can move across land in the same way a king moves in chess - one square in any diagonal or orthogonal direction:

```
!!!
!%!
!!!

```

At the end of the simulation, some land will be infected with zombies:

```
%%   ##
%%%   #
%% %%
  % %%%
#  %%%%

```

Your task is to simulate the zombie invasion. Write a program (or function) that takes as input a string representing the initial state of the grid, and two numbers representing the coordinates of the initial zombie. The program should output (or return) the final state of the invasion.

# Specifications

* Your program may print an optional trailing newline.
* You can assume the input will be in the correct format (padded with spaces), with an optional trailing newline.
* You can assume the initial zombie will start on land and will not die immediately.
* This is , so the shortest answer (in bytes) wins.
* -100% bonus if your code can also solve the Halting Problem for arbitrary Turing machines.
* Your program should handle board widths of up to 50 chars.

# Answer
# APL (Dyalog), 44 bytes

```
{{c'%'[⌊⌿'%#'∊¨⍵(c←4⊃⍵)]}∘,⌺3 3⍣≡'%'@(⊂⍺)⊢⍵}

```

Try it online!

Assumes `⎕IO←0`.

Left argument: 0-indexed row `r` of %, 0-indexed column `c` of %: `r c`
Right argument: Character matrix
> 1 votes

# Answer
## Kotlin, 283 218 bytes

Unnamed lambda (with a nested function, heh).

**Golfed**

```
{i:String,x:Int,y:Int->val m=i.lines().map{it.toCharArray()};fun v(x:Int,y:Int){try{if(m[y][x]=='#'){m[y][x]='%';for(c in-1..1)for(d in-1..1)if(!(c==0&&d==0))v(x+c,y+d)}}catch(e:Exception){}};v(x, y);m.map(::println)}

```

**Ungolfed**

```
fun zombies(input: String, startX: Int, startY: Int) {
    val m = input.lines().map(String::toCharArray)      // build game map
    fun invade(x: Int, y: Int) {                        // nested functions, woo!
        try {
            if (m[y][x] == '#') {                       // if land
                m[y][x] = '%'                           // mark as invaded
                for (dx in -1..1) {                      // generate neighbour tiles
                    for (dy in -1..1) {
                        if (!(dx == 0 && dy == 0)) {
                            invade(x + dx, y + dy)        // attempt to invade neighbours
                        }
                    }
                }
            }
        } catch(e: Exception) {}                        // catches ArrayIndexOutOfBounds
    }

    invade(startX, startY)                              // start the invasion
    m.map(::println)                                    // print final state
}

```

Saved quite a few bytes by switching to a recursive solution.
> 5 votes

# Answer
## JavaScript (ES6), 144 bytes

```
(s,x,y,l=s.search`\n`,g=s=>s==(s=s.replace(eval(`/(#|%)(.?[^]{${l-1}}.?)?(?!\\1)[#%]/`),`%$2%`))?s:g(s))=>g(s.slice(0,x+=y*l)+`%`+s.slice(x+1))

```

Where `\n` represents the literal newline character. Takes 0-indexed coordinates.
> 4 votes

# Answer
# Befunge, ~~324~~ 323 bytes

```
&00p&10p20p~$v<p02+g02*!g02:+1$$$$<
 #<%>\"P"/8+p>1+:::~:0`!#v_:85+`!#^_2%\2%3*1+*\2/:"P"%\"P"/8+g+\2/:"P"
:+**73"="+g00*g02g010$$$$<v
02:\-<v/"P"\%"P":/2::_|#:$<:+1+g02\+g02:\-1+g02:\+1:\-1:\+1-g
\:20g^>g:30p\2%3*1+/4%1->#^_::2%6*2+30g+\2/:"P"%\"P"/p:20g-1-
0<v2\g+8/"P"\%"P":/2::<\_@#`0:-g
2^>%3*1+/4%1g,1+:20g%#^_1+55+,\

```

Try it online!

**Explanation**

Implementing this in Befunge was a little bit complicated because we're limited to 80x25 characters of "memory" which has to be shared with the source code itself. The trick to fitting a 50x50 map into that area was to flatten the 2D map into a 1D array with two map locations per byte. This 1D array is then wrapped into a 2D array again so that it can fit in the 80 character width of the Befunge playfield.

The infection algorithm starts by converting the initial coordinates into an offset in the 1D array which it pushes onto the stack. The main loop takes a value from the stack and looks up the map state for that offset. If it's uninfected land, it gets marked as infected, and eight new offsets are pushed onto the stack (representing the land all around the current position). This process continues until the stack is empty.

To avoid having to check for out of range values, the map is stored with a one character water border around all the edges.
> 2 votes

# Answer
# Pip, 59 bytes

```
{(ac+b+b*Ya@?n):'%L2*#aa:RVaR.`#(.?.?.{`.y-1.`})?%`'%.@>_a}

```

A function that takes a multiline string, the row of the initial zombie (0-indexed), and the column of the initial zombie (0-indexed). Try it online!

### How?

Because Pip has cyclical indexing (usually a good thing, but bad for this problem because we don't want the map edges to wrap), I went for a regex-replacement solution.

`Ya@?n` finds the index of the first newline (i.e. the width of the grid) and yanks it into `y`.

`(ac+b+b*Ya@?n):'%` after doing the above, computes `(width + 1) * row + col`, i.e. `c+b+b*y`, and sets the character at that index to `%`.

`L2*#a` loops `2*len(a)` times, which gives us enough iterations for the flood fill to fully propagate and makes sure the iteration count is even (that's important).

`.`#(.?.?.{`.y-1.`})?%`` constructs a regex that matches a `#` followed by a `%`, with either 0, width-1, width, or width+1 characters in between. (The `.` at the beginning makes `.` in the regex match newlines.) This regex matches any of the following configurations:

```
#
 %

 #
 %

  #
 %

#%

```

`aR ... '%.@>_` replaces matches of this regex with the character `%` prepended to `.` all but the first character `@>` of the match `_`; in short, replacing the `#` with `%`.

`a:RV ...` reverses that and assigns it back to `a`. We reverse because the regex only matches `#` *before* `%` in the string, not after; but when the string is reversed, after becomes before and we can match it on the next iteration. This is also why the number of iterations has to be even.

After the loop is complete, we simply return the modified value of `a`.
> 1 votes

# Answer
# TSQL, 267 bytes

**Golfed:**

```
USE master
DECLARE @ varchar(max)=
'##   ##
###   #
## %#
  # ###
#  ####'

WHILE @@rowcount>0WITH C as(SELECT x+1i,substring(@,x+1,1)v,x/z r,x%z c
FROM spt_values CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
WHERE type='P'and x<len(@))SELECT @=stuff(@,d.i,1,'%')FROM C,C D
WHERE'#%'=d.v+c.v and abs(c.r-d.r)<2and abs(c.c-d.c)<2PRINT @

```

**Ungolfed:**

```
USE master-- the script needs to be executed on the default master database
DECLARE @ varchar(max)=
'##   ##
###   #
## %#
  # ###
#  ####'

WHILE @@rowcount>0
WITH C as
(
  SELECT x+1i,substring(@,x+1,1)v,x/z r,x%z c
  FROM
    spt_values
  CROSS APPLY(SELECT number x,charindex(char(10),@)z)z
  WHERE type='P'and x<len(@)
)
SELECT @=stuff(@,d.i,1,'%')FROM C,C D
WHERE'#%'=d.v+c.v and abs(c.r-d.r)<2and abs(c.c-d.c)<2

PRINT @

```

**Try it out**
> 0 votes

# Answer
# PHP, ~~209~~ ~~189~~ ~~188~~ 183 bytes

may be golfable

```
for($w=strpos($s=($a=$argv)[1],10),$s[$a[2]*++$w+$a[3]]="%";$t<$s;)for($t=$s,$i=0;""<$c=$s[$i++];)if($c>"$")for($y=-2;++$y<2;)for($x=3;$x--;)$s[$p=$i+$y*$w-$x]>"!"?$s[$p]="%":0;echo$s;

```

Run with `php -r '<code>' '<grid>' <y> <x>`
> 0 votes

# Answer
# J, 152 Bytes

Not very well golfed, I'm sure there's a way to remove those last few control structures.

```
f=:4 :0
c=.(' '"_)`({~&<y)@.((*./y<$x)*.*./y>:0 0)x if.c='#' do.x=.'%'(<y)}x[i=.0 while.i<9 do.i=.>:i[x=.x f y+i<:@(|~,<.@%)3 end.end.x
)
g=:>@cutLF@[f]

```

Implements a flood fill algorithm. The function g formats input into a character array before applying f.

Note that coordinates are a bit weird:

```
0, 0

```

is the top left corner. Increasing the first coordinate:

```
1, 0

```

Moves the position down in the y direction.

Other than that coordinates are normal.

### Example:

```
    land =: 0 : 0    NB. Define a multi-line string
##   ##
###   #
## ##
  # ###
#  ####
)

    ] l =. >@cutLF land    NB. Cut 'land' on new lines, and form into an array. Assign to 'l'
##   ##
###   #
## ##
  # ###
#  ####
    NB. Looks the same, but it isn't.

    '%' (<2 3)} l    NB. 'Infect' the land at 2, 3
##   ##
###   #
## %#
  # ###
#  ####

    l f 2 3    NB. Flood fill on l (already formatted), starting at 2 3
%%   ##
%%%   #
%% %%
  % %%%
#  %%%%

    land g 2 3    NB. Flood fill on land, formats for us.
%%   ##
%%%   #
%% %%
  % %%%
#  %%%%

```
> 0 votes

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


title: Loan "generous" amounts of money

text:
# Question
Title: Loan "generous" amounts of money
# Introduction

You have a friend that keeps asking you for loans and you are getting tired of it. Today, he came for a loan again. Instead of turning down his offer, you get a great idea: troll your friend by giving him as many coins/bills as possible.

# Challenge

You will take as input: the amount of money your friend wants a loan for and the amount of coins/bills you have. For this challenge, the possible denominations are $20.00, $10.00, $5.00, $2.00, $1.00, $0.25, $0.10, $0.05, and $0.01. An example of input is `5.67, [5, 3, 4, 5, 5, 9, 8, 1, 2]` if you friend wants $5.67 and you have 5 $20 bills, 3 $10 bills, etc. Your output will be the amount of coins/bills that gives your friend as much metal/paper/plastic as possible.

If it is not possible to give your friend the exact amount of money he wants, give him the closest amount of money you can pay that is greater than what he wants. For example, if your friend wants $0.07 but you only have `[0, 0, 0, 0, 0, 2, 4, 2, 0]`, give him 2 $0.05 coins (not 1 $0.10 because that wouldn't be giving him as many coins as possible!).

If your friend wants more money than you have, give him all your money (and pray you won't need to buy anything).

# Test cases

```
Input:  6.54, [9, 8, 7, 6, 5, 4, 3, 2, 4]
Output: [0, 0, 0, 1, 4, 1, 2, 1, 4]

Input:  2, [0, 1, 0, 0, 0, 0, 0, 0, 0]
Output: [0, 1, 0, 0, 0, 0, 0, 0, 0]

Input:  9999, [0, 0, 0, 0, 0, 0, 0, 0, 1]
Output: [0, 0, 0, 0, 0, 0, 0, 0, 1]

Input:  0, [99, 99, 99, 99, 99, 99, 99, 99, 99]
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0]

```

---

This is so shortest code wins.

# Answer
# Clean, 167 bytes

```
import StdEnv
@n l#m=[p\\p<-[[if(y==u)(x-1)x\\x<-l&y<-[0..]]\\u<-[0..]&v<-l|v>0]|sum[a*b\\a<-[2000,1000,500,200,100,25,10,5,1]&b<-p]>=toInt(n*100.0)]
|m>[]= @n(hd m)=l

```

Defines the function `@`, taking `Real` and `[Int]`.

Try it online!
> 3 votes

# Answer
# JavaScript, 213 Bytes

```
x=>y=>(F=(x,y,z,u=9)=>u--?[...Array(y[0]+1)].map((_,i)=>F(x-i*[1,5,10,25,100,200,500,1e3,2e3][u],y.slice(1),[...z,i],u))&&G:x>0||G.push([z,x-1/eval(z.join`+1+`)]),F(x*100,y,G=[]).sort((a,b)=>b[1]-a[1])[0]||[y])[0]

```

It's pretty slow and cost memory, so only try small cases
> 1 votes

# Answer
# Kotlin, 298 bytes

```
{t,c->with(c.fold(listOf(listOf<Int>())){o,x->o.flatMap{a->(0..x).map{a+it}}}.groupBy{it.zip(C).map{(a,b)->a*b}.sum()}.mapValues{(_,b)->b.maxBy{it.sum()}!!}.toSortedMap().asSequence()){firstOrNull{it.key==t}?:firstOrNull{it.key>t}?:last()}.value}
val C=listOf(20.0,10.0,5.0,2.0,1.0,0.25,.1,.05,.01)

```

## Beautified

```
        { t, c ->
            with(c.fold(listOf(listOf<Int>())) { o, x ->
                o.flatMap { a -> (0..x).map { a + it } } /* Get all of the options. */
            }.groupBy { it.zip(C).map { (a, b) -> a * b }.sum() }
                .mapValues { (_,b)->b.maxBy { it.sum() }!! }
                .toSortedMap().asSequence()) {
                firstOrNull { it.key == t } ?:
                        firstOrNull { it.key > t } ?:
                        last()
            }.value
        }
val C = listOf(20.0, 10.0, 5.0, 2.0, 1.0, 0.25, .1, .05, .01)

```

## Test

```
val calc: (target: Double, coins: List<Int>) -> List<Int> =
{t,c->with(c.fold(listOf(listOf<Int>())){o,x->o.flatMap{a->(0..x).map{a+it}}}.groupBy{it.zip(C).map{(a,b)->a*b}.sum()}.mapValues{(_,b)->b.maxBy{it.sum()}!!}.toSortedMap().asSequence()){firstOrNull{it.key==t}?:firstOrNull{it.key>t}?:last()}.value}
val C=listOf(20.0,10.0,5.0,2.0,1.0,0.25,.1,.05,.01)

data class Test(val target: Double, val input: List<Int>, val output: List<Int>)

val tests = listOf(
        Test(2.0, listOf(0, 1, 0, 0, 0, 0, 0, 0, 0), listOf(0, 1, 0, 0, 0, 0, 0, 0, 0)),
        Test(9999.0, listOf(0, 0, 0, 0, 0, 0, 0, 0, 1), listOf(0, 0, 0, 0, 0, 0, 0, 0, 1)),
        Test(6.54, listOf(9, 8, 7, 6, 5, 4, 3, 2, 4), listOf(0, 0, 0, 1, 4, 1, 2, 1, 4)),
        Test(0.0, listOf(99, 99, 99, 99, 99, 99, 99, 99, 99), listOf(0, 0, 0, 0, 0, 0, 0, 0, 0))
)

fun main(args: Array<String>) {
    for (t in tests) {
        if (t.output != calc(t.target, t.input)) {
            throw AssertionError()
        } else {
            println("Passed")
        }
    }
}

```

**Example 4 causes OutOfMemory, but the other 3 work well.**
> 1 votes

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


title: [CHRISTMAS THEME DISCLAIMER HERE]

text:
# Question
Title: [CHRISTMAS THEME DISCLAIMER HERE]
*Note to mods, if the title doesn't do justice, change it to whatever, I thought it was funny.*

---

You're tasked with hanging up the lights for this Christmas season, and your family has decided that for it to be a merry Christmas, you need to hang at least 2 Christmas lights on your house. So, your challenge is, given a number `1 < n`, output the corresponding number of christmas lights you're going to be hanging according to the following specifications...

---

Here is the structure of a basic christmas light:

```
  _?_
 [___]
 /:' \
|::   |
\::.  /
 \::./
  '='

```

The only uncertain part is the question mark, as depending on where the light lands in the chain, the connection will greatly differ.

***For the first light in the chain, you will need to output:***

```
    .--._
  _(_
 [___]
 /:' \
|::   |
\::.  /
 \::./
  '='

```

***For the last light in the chain, you will need to output:***

```
_.--.
    _)_
   [___]
   /:' \
  |::   |
  \::.  /
   \::./
    '='

```

***And for all lights in the middle:***

```
_.--.--._
   _Y_
  [___]
  /:' \
 |::   |
 \::.  /
  \::./
   '='

```

---

# Example:

***N=2***:

```
    .--.__.--.
  _(_        _)_
 [___]      [___]
 /:' \      /:' \
|::   |    |::   |
\::.  /    \::.  /
 \::./      \::./
  '='        '='

```

***N=6***:

```
    .--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.
  _(_       _Y_      _Y_      _Y_      _Y_       _)_
 [___]     [___]    [___]    [___]    [___]     [___]
 /:' \     /:' \    /:' \    /:' \    /:' \     /:' \
|::   |   |::   |  |::   |  |::   |  |::   |   |::   |
\::.  /   \::.  /  \::.  /  \::.  /  \::.  /   \::.  /
 \::./     \::./    \::./    \::./    \::./     \::./
  '='       '='      '='      '='      '='       '='

```

---

# Credit

ASCII-Art was taken from: http://www.chris.com/ascii/index.php?art=holiday/christmas/other

It was developed by a user named "jgs", who is responsible for around 40% of content on that site.

---

# Rules

* Trailing spaces are fine, same with a trailing newline.
* There is 1 more space between the first and last bulb from the rest of the chain.
* You may only take 1 integer as input, and the output MUST be a string, no arrays.
* Your program may have undefined functions for values less than 2.

This is , lowest byte-count wins.

---

Sanbox post link here.

# Answer
> 34 votes
# SOGL V0.12, ~~73~~ ~~71~~ ~~70~~ 66 bytes

```
.”L7:±¹‘Ο4↕ooā.⁾ Y*¾(){"}^ņF⁵),WοΓy⅜¬κ8ΕL▓‚7m~Ε⅝Γ‘7n┼F (=f⁄2=+⁽{@┼

```

Try it Here!

-4 bytes by looping over a string like `(YYY)` like the Charcoal answer

63 bytes would work if 2 didn't need to be handled :/

# Answer
> 26 votes
# Python 3, ~~200~~ ~~195~~ ~~191~~ ~~190~~ 186 bytes

```
d,*l=" _%c_     , [___]   , /:' \   ,|::   |  ,\::.  /  , \::./   ,  '='    ".split(',')
x=int(input())-2
print(' '*3,-~x*'.--.__.--'+'.\n',d%'(',d%'Y'*x,d%')')
for s in l:print(s,s*x,s)

```

-1 byte from dylnan
-4 bytes from Rod

Takes input on stdin.

Try it online!

Explanation:

```
d,*l=" _%c_     , [___]   , /:' \   ,|::   |  ,\::.  /  , \::./   ,  '='    ".split(',')
# d is the second row, without the (, Y, or ) to connect the light to the strand
# l is the third through eighth rows in a list
x=int(input())-2
# x is the number of lights in the middle of the strand
print(' '*3,-~x*'.--.__.--'+'.\n',d%'(',d%'Y'*x,d%')')
# print x+1 wire segments and a trailing dot, starting four spaces over
# on the next line, print the connectors, _(_, then _Y_ * x, then _)_
for s in l:print(s,s*x,s)
# on the Nth line, print the Nth light row, a space,
#     x * the Nth light row, a space, and the Nth light row

```

Additional Festive Version!

# Answer
> 18 votes
# Pyth, ~~113~~ 107 bytes

```
+"    ."*=tQ"--.__.--."++"  _(_ "j"_Y_"*Q]*6d" _)_"jms[d;jd*Q]*2;;d)c5" /:' \ |::   |\::.  / \::./   '='  "

```

Try it online!

Not exactly the golfiest version...

# Answer
> 15 votes
# JavaScript (ES6), 180 bytes

```
n=>`    .${'--.__.--.'.repeat(n-1)}
`+`  _Y_
 [___]
 /:' \\
|::   |
\\::.  /
 \\::./
  '='  `.replace(/.+/g,(r,p)=>`${p?r:'  _(_  '}  ${` ${r} `.repeat(n-2)}  ${p?r:'  _)_'}`)

```

**Test**

```
var f=
n=>`    .${'--.__.--.'.repeat(n-1)}
`+`  _Y_
 [___]
 /:' \\
|::   |
\\::.  /
 \\::./
  '='  `.replace(/.+/g,(r,p)=>`${p?r:'  _(_  '}  ${` ${r} `.repeat(n-2)}  ${p?r:'  _)_'}`)

function update()
{
  var n=+I.value
  P.textContent=f(n)
}

update()
```

```
<input id=I type=number value=2 min=2 oninput='update()'>
<pre id=P></pre>
```

# Answer
> 13 votes
# JavaScript (ES6), ~~204~~ ~~201~~ ~~196~~ ~~194~~ 192 bytes

```
N=>`     ${(r=x=>x.repeat(N-1))(`.--.__.--`)}.
   _(_    ${N--,r(`   _Y_   `)}    _)_
`+` [___]
 /:' \\
|::   |
\\::.  /
 \\::./
  '='  `.split`
`.map(x=>`${x=` ${x} `} ${r(x)} `+x).join`
`

```

```
f=

N=>`     ${(r=x=>x.repeat(N-1))(`.--.__.--`)}.
   _(_    ${N--,r(`   _Y_   `)}    _)_
`+` [___]
 /:' \\
|::   |
\\::.  /
 \\::./
  '='  `.split`
`.map(x=>`${x=` ${x} `} ${r(x)} `+x).join`
`

for(let i = 2; i <= 5; i++){
  console.log(f(i))
}
```

# Answer
> 13 votes
# Charcoal, ~~78~~ 74 bytes

```
Ｍ⁴→×….--.__⁹⊖θ.⸿Ｆ⪫()×Y⁻θ²«Ｍ⁼ι)→Ｐ“ ▷υ ρ1↗N⁷Σ⭆ C✂⪪⟲⦃¬≡↘↨H℅⌕Σêλ⍘”  _ι_Ｍ⁺⁴⁼ι(→

```

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes by simplifying the way the wiring is printed. Saved 2 bytes because the new code automatically casts the input to integer. Explanation:

```
Ｍ⁴→×….--.__⁹⊖θ.⸿

```

Print the wiring by taking the string `.--.__`, moulding it to length 9, then repeating it once for each join, finishing with a final `.` before moving to the start of the next line for the bulbs.

```
Ｆ⪫()×Y⁻θ²«

```

Loop over a string of connectors: `(` and `)` at the ends, and `Y`s in the middle.

```
Ｍ⁼ι)→

```

Move right one character if this is the last bulb.

```
Ｐ“ ▷υ ρ1↗N⁷Σ⭆ C✂⪪⟲⦃¬≡↘↨H℅⌕Σêλ⍘”

```

Print the body of the bulb without moving the cursor.

```
  _ι_

```

Print the cap of the bulb including the connector.

```
Ｍ⁺⁴⁼ι(→

```

Move to the start of the next bulb (an extra character if this is the first bulb).

# Answer
> 13 votes
# Excel VBA, <sub>~~224~~ ~~207~~</sub> 205 Bytes

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

Prints the bulbs line by line, from top left to bottom right

```
?Spc(4)[Rept(".--.__.--",A1-1)]".":?"  _(_ "[Rept("      _Y_",A1-2)]"       _)_":For i=0To 5:b=Split(" [___]   1 /:' \   1|::   |  1\::.  /  1 \::./   1  '='    ",1)(i):[B1]=b:?b" "[Rept(B1,A1-2)]" "b:Next

```

Sample I/O

```
[A1]=7 ''  Input to worksheet, may also be done manually
?Spc(4)[Rept(".--.__.--",A1-1)]".":?"  _(_ "[Rept("      _Y_",A1-2)]"       _)_":For i=0To 5:b=Split(" [___]   1 /:' \   1|::   |  1\::.  /  1 \::./   1  '='    ",1)(i):[B1]=b:?b" "[Rept(B1,A1-2)]" "b:Next
    .--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.--.__.--.
  _(_       _Y_      _Y_      _Y_      _Y_      _Y_       _)_
 [___]     [___]    [___]    [___]    [___]    [___]     [___]
 /:' \     /:' \    /:' \    /:' \    /:' \    /:' \     /:' \
|::   |   |::   |  |::   |  |::   |  |::   |  |::   |   |::   |
\::.  /   \::.  /  \::.  /  \::.  /  \::.  /  \::.  /   \::.  /
 \::./     \::./    \::./    \::./    \::./    \::./     \::./
  '='       '='      '='      '='      '='      '='       '='

```

-17 Bytes thanks to @YowE3k

-2 bytes for addition of temporary variable `b`

# Answer
> 10 votes
# C,  ~~279~~   ~~278~~   ~~272~~   ~~262~~  259 bytes

*Thanks to @NieDzejkob for saving six bytes!*

```
#define P;printf(
i,j;f(n){char*S=" [___]   \0 /:' \\   \0|::   |  \0\\::.  /  \0 \\::./   \0  \'=\'    \0"P"    ");for(i=n--;--i P".--.__.--"))P".\n  _(_ ");for(;++i<n P"      _Y_"))P"       _)_\n%s ",S);for(;*S P"%10s\n%s ",S,S+10),S+=10)for(i=n;--i P S));}

```

Try it online!

**Unrolled:**

```
#define P;printf(

i, j;

f(n)
{
    char*S = " [___]   \0 /:' \\   \0|::   |  \0\\::.  /  \0 \\::./   \0  \'=\'    \0"
    P"    ");

    for (i=n--; --i P".--.__.--"))
    P".\n  _(_ ");

    for (; ++i<n P"      _Y_"))
    P"       _)_\n%s ",S);

    for (; *S P"%10s\n%s ", S, S+10), S+=10)
        for(i=n; --i P S));
}

```

# Answer
> 8 votes
## PHP, ~~276~~, ~~307~~, ~~303~~, ~~301~~, ~~293~~, ~~283~~, ~~280~~, 278 Bytes

```
function g($n){$a=["     .--._".r("_.--.--._",$n)."_.--.",r("_(_")." ".r(_Y_,$n)." ".r("_)_")];foreach(explode(9,"[___]9/:' \9|::   |9\::.  /9\::./9'='")as$b)$a[]=r($b)." ".r($b,$n)." ".r($b);return join("\n",$a);}function r($s,$n=3){return str_repeat(str_pad($s,9," ",2),$n-2);}

```

Readable version for testing:

```
function g($n){
    $a=[
         "     .--._".r("_.--.--._",$n)."_.--.",
         r("_(_")." ".r(_Y_,$n)." ".r("_)_")
    ];

    foreach(explode(9, "[___]9/:' \9|::   |9\::.  /9\::./9'='") as$b)
         $a[]=r($b)." ".r($b,$n)." ".r($b);

    return join("\n",$a);
}
function r($s,$n=3){
    return str_repeat(str_pad($s,9," ",2),$n-2);
}

```

Check minified version out here

Check readable version out here

**UPDATE**

Wrapped it in a function,

# Answer
> 8 votes
# Java, ~~310~~ ~~307~~ ~~300~~ 275 bytes

Thanks to DevelopingDeveloper for converting it to a lambda expression

```
i->{int j=1;String o="     .";for(;j++<i;)o+="--.__.--.";o+="\n   _(_    ";for(;--j>2;)o+="   _Y_   ";o+="    _)_";String[]a={"  [___]  ","  /:' \\  "," |::   | "," \\::.  / ","  \\::./  ","   '='   "};for(String b:a)for(j=0;j++<i;)o+=j==1?"\n"+b+" ":j==i?" "+b:b;return o;};

```

Expanded:

```
i->
{
    int j=1;
    String o="     .";
    for(;j++<i;)
        o+="--.__.--.";
    o+="\n   _(_    ";
    for(;--j>2;)
        o+="   _Y_   ";
    o+="    _)_";
    String[]a={"  [___]  ","  /:' \\  "," |::   | "," \\::.  / ","  \\::./  ","   '='   "};
    for(String b:a)
        for(j=0;j++<i;)
            o+=j==1?"\n"+b+" ":j==i?" "+b:b;
    return o;
};

```

Looking into shorter ways to multiply strings, and found that streams are surprisingly more verbose

Try it online!

# Answer
> 5 votes
# Clean, ~~305~~ ~~292~~ ~~288~~ 275 bytes

```
import StdEnv
f c=mklines['  _',c,'_  \n [___] \n /:\' \\ \n|::   |\n\\::.  /\n \\::./ \n  \'=\'  ']
@n=flatlines[a++b++c\\a<-[['    .--._']:[e++['  ']\\e<-f'(']]&b<-map(flatten o(repeatn(n-2)))[['_.--.--._']:[[' ':e]++[' ']\\e<-f'Y']]&c<-[['_.--.    ']:[['  ':e]\\e<-f')']]]

```

Try it online!

# Answer
> 3 votes
# Python 2 (PyPy), ~~365~~ ~~316~~ ~~315~~ ~~251~~ 245 bytes

-21 thanks to FlipTack

-43 thanks to ovs

-6 thanks to Mr. Xcoder

```
v,p=' \n'
a,l,n=".--._",["[___]"," /:' \ ","|::   |","\::.  /"," \::./ ","  '='  "],input()-2
e,b=v*5+"_)_",a[::-1]
r=v*4,a,(b[:4]+a)*n,b,p+"  _(_   ",(v*4+"_Y_  ")*n,e+p+v
for i in l:b=4-2*(i in l[1:]);r+=i+v*-~b,(i+v*b)*n,v+i+p
print''.join(r)

```

Try it online!

# Answer
> 1 votes
# Kotlin, 261 bytes

```
{val c="  [___]\n/:' \\\n |::|\n \\::./\n  \\::./\n   '='"
(0..7).map{i->print("     .--._\n   _(_\n$c".lines()[i].padEnd(10))
(0..L-3).map{print("_.--.--._\n   _Y_\n$c".lines()[i].padEnd(9))}
if(i>1)print(' ')
print("_.--.\n    _)_\n$c".lines()[i])
println()}}

```

## Beautified

```
{
    val c = "  [___]\n  /:' \\\n |::   |\n \\::.  /\n  \\::./\n   '='"

    (0..7).map {i->
        print("     .--._\n   _(_\n$c".lines()[i].padEnd(10))
        (0..L - 3).map {
            print("_.--.--._\n   _Y_\n$c".lines()[i].padEnd(9))
        }
        if (i > 1) print(' ')
        print("_.--.\n    _)_\n$c".lines()[i])
        println()
    }
}

```

## Test

```
fun f(L: Int)
{val c="  [___]\n/:' \\\n |::|\n \\::./\n  \\::./\n   '='"
(0..7).map{i->print("     .--._\n   _(_\n$c".lines()[i].padEnd(10))
(0..L-3).map{print("_.--.--._\n   _Y_\n$c".lines()[i].padEnd(9))}
if(i>1)print(' ')
print("_.--.\n    _)_\n$c".lines()[i])
println()}}

fun main(args: Array<String>) {
    f(6)
}

```

## TIO

TryItOnline

# Answer
> 1 votes
# Google Sheets, 190 Bytes

Anonymous worksheet function that take input from range `A1` and outputs to the calling cell

```
="    "&Rept(".--.__.--",A1-1)&".
  _(_    "&Rept("   _Y_   ",A1-2)&"    _)_"&RegexReplace("
 [___]
 /:' \
|::   |
\::.  /
 \::./
  '='
","
(.*)","
$1 "&Rept("$1",A1-2)&" $1

```

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


title: Binary Branches

text:
# Question
Title: Binary Branches
Given a binary number, your task is to create a 'branch' of that number, with a depth of 2.

For example, given `0` as input, you should output exactly this:

```
     /000
  /00
 /   \001
0
 \   /010
  \01
     \011

```

This should be fairly self explanatory of how the branches should be created. Depth 2 means we calculate branches for numbers of up to 2 numbers longer. We also calculate the branches in order, with zeroes at the top and ones at the bottom.

More test cases:

```
0

     /000
  /00
 /   \001
0
 \   /010
  \01
     \011

1

     /100
  /10
 /   \101
1
 \   /110
  \11
     \111

00

       /0000
   /000
  /    \0001
00
  \    /0010
   \001
       \0011

01

       /0100
   /010
  /    \0101
01
  \    /0110
   \011
       \0111

10

       /1000
   /100
  /    \1001
10
  \    /1010
   \101
       \1011

11

       /1100
   /110
  /    \1101
11
  \    /1110
   \111
       \1111

```

### Rules

* You will never receive characters in the input other than `1` and `0`.
* `0 < length of input < 11`.
* Trailing whitespace allowed at the end of lines.

# Answer
# Jelly, ~~39~~ 38 bytes

```
L⁶ẋ,W;“/0¶\1 ”ṃ@“ð&ẏ{×ẏĊfẏȷ®ỤṪ⁻ʠaƇGⱮȷ’

```

**Try it online!**

### How?

The art to be printed is:

```
L  L /N00
L /N0
L/ L \N01
N
L\ L /N10
L \N1
L  L \N11

```

Where `N` is the input string and `L` is a string of spaces of the length of the input string.

As such it is comprised of eight components (`L`, `N`, `/`, `0`, the newline character, `\`, `1`, and the space character) and hence may be stored as a base-8 number ( which may be compressed as a base-250 number in Jelly). The  atom combines base conversion and indexing into a list (effectively one may define arbitrary digits to be used).

```
L⁶ẋ,W;“/0¶\1 ”ṃ@“ð&ẏ{×ẏĊfẏȷ®ỤṪ⁻ʠaƇGⱮȷ’ - Main link: binary string s  e.g. "100"
 ⁶                                     - space character
  ẋ                                    - repeat by:
L                                      -     length(s)                    [' ',' ',' ']
    W                                  - wrap s in a list                 [['1','0','0']]
   ,                                   - pair               [[' ',' ',' '],['1','0','0']]
      “/0¶\1 ”                         - char list: ['/','0',<newline>,'\',','1',' ']

     ;                                 - concatenate        [[' ',' ',' '],['1','0','0'],'/','0',<newline>,'\',','1',' ']
                “ð&ẏ{×ẏĊfẏȷ®ỤṪ⁻ʠaƇGⱮȷ’ - base 250 number: 91531517467460683226372755994113932025707662527
              ṃ@                       - base decompression [reversed @arguments]
                                        -     this uses the concatenated list above as
                                        -     the 8 digits of that number in base 8.
                                        - implicit print

```
> 4 votes

# Answer
## Batch, ~~178~~ ~~170~~ 159 bytes

```
@set/pb=
@set s=%b:0= %
@set s=%s:1= %
@set e=@echo %s%
%e%  %s% /%b%00
%e% /%b%0
%e%/ %s% \%b%01
@echo %b%
%e%\ %s% /%b%10
%e% \%b%1
%e%  %s% \%b%11

```

Edit: Saved 11 bytes thanks to @ConorO'Brien.
> 5 votes

# Answer
# Python 3.6, ~~172~~ ~~153~~ 128 bytes

Literally does not get more straightforward than this... This is actually shorter than my original attempt at generating it with an algorithm. How sad.

```
k=input()
l=len(k)
b=' '*l
print(f'{b*2}   /{k}00\n{b} /{k}0\n{b}/ {b}\\{k}01\n{k}\n{b}\\ {b}/{k}10\n{b} \\{k}1\n{b*2} \\{k}01')

```

-19 bytes thanks to @Leo
-25 bytes thanks to @L3viathan
> 4 votes

# Answer
## JavaScript (ES6), 112 bytes

```
s=>`22   /300
2 /30
2/2  4301
3
242  /310
2 431
22   4311`.replace(/./g,n=>[s.replace(/./g,' '),s,'\\'][n-2]||n)

```

### Demo

```
let f =

s=>`22   /300
2 /30
2/2  4301
3
242  /310
2 431
22   4311`.replace(/./g,n=>[s.replace(/./g,' '),s,'\\'][n-2]||n)

console.log(f('0'))
console.log(f('11'))
console.log(f('101'))
```
> 4 votes

# Answer
# Python 3, 117 109 bytes

```
lambda k:'ll   /g00\nl /g0\nl/l  \g01\ng\nl\l  /g10\nl \g1\nll   \g11'.replace('l',' '*len(k)).replace('g',k)

```

Try it online!

The format string when printed looks like:

```
ll   /g00
l /g0
l/l  \g01
g
l\l  /g10
l \g1
ll   \g11

```

This looks good already for string of length of 1. All we got to do is replace l by spaces of length equal to that of g and, of course, g is to be replaced by the original string
> 4 votes

# Answer
# C, ~~170~~ 168 bytes

*Thanks to @Neil for saving two bytes!*

```
n;f(char*s){n=strlen(s);printf("%*c%s00\n%*c%s0\n %*c%*c%s01\n%s\n %*c%*c%s10\n%*c%s1\n%*c%s11",2*n+4,47,s,n+2,47,s,n,47,n+3,92,s,s,n,92,n+3,47,s,n+2,92,s,2*n+4,92,s);}

```

Try it online!
> 3 votes

# Answer
# PHP, 128 bytes

Only a simple Output

```
<?=$b=str_pad("",strlen($a=$argn)),"$b   /{$a}00\n$b /{$a}0\n$b/$b  \\{$a}01\n$a\n$b\\$b  /{$a}10\n$b \\{$a}1\n$b$b   \\{$a}11";

```

Try it online!
> 3 votes

# Answer
# Python 3, 96 bytes

```
lambda s:"""   /00
 /0
/  \01

\  /10
 \1
   \11""".translate([s,' '*len(s),s])

```

Try it online! The unprintable characters do not display correctly; the string format is the same as officialaimm's, but with `\x01` for `l` and `\x02` for `g`.

```
ll   /g00
l /g0
l/l  \g01
g
l\l  /g10
l \g1
ll   \g11

```

Uses string substitution with Python 3's flexible `translate`. The translate list `[s,' '*len(s),s]` maps `\x01` to `' '*len(s)` and `\x02` to `s`. Any larger characters are unchanged because they give indices that are out-of-bounds for the list. `\x00` could not be used because a null byte is read as a program end, so the first entry is wasted.
> 3 votes

# Answer
# Stacked, 81 bytes

```
{!n#'' '*@s's  s /n00
s /n0
s/ s \n01
n
s\ s /n10
s \n1
s  s \n11' '\l'$#~1/repl}

```

Try it online!

Not very interesting, unfortunately. Here's the most interesting part:

```
'\l'$#~1/repl
         repl     replace all
'\l'              letters
    $#~           by evaluating
       1/         over one argument (otherwise, it would evaluate the "last" thingy)

```

This is basically string interpolating, but 10 bytes shorter than the builtin.
> 2 votes

# Answer
# ///, 116 bytes

```
/[/\\\///x///*/[y\\0[ y\/\/y\\1[ y\//**********/y///s/yx//~/  /~ ss[x00
 s[x0
s[~s\\x01
x
s\\~s[x10
 s\\x1
~ ss\\x11

```

Try it online!

Input is as follows:

```
/[/\\\///x/INPUT HERE!!!!!!!!//*/[y\\0[ y\/\/y\\1[ y\//**********/y///s/yx//~/  /~ ss[x00
 s[x0
s[~s\\x01
x
s\\~s[x10
 s\\x1
~ ss\\x11

```

Works by using a basic template, and adding spaces and characters where needed.

The byte count went up because Ørjan Johansen realized that it did not handle spacing at first. But the problem is know fixed.
> 2 votes

# Answer
# Python 2, ~~101,91 bytes~~113 bytes

```
lambda y:'   ++/_00\n +/_0\n+/  +\\_01\n_\n+\\  +/_10\n +\\_1\n   ++\\_11'.replace('_',y).replace('+',' '*len(y))

```

Try it online!

Input is a string of 0's and 1's of length 1 or 2! That is 0,01,10 or 11!

+12 bytes - corrected the spacing in \ for length two input.
> 1 votes

# Answer
# Charcoal, 34 bytes

```
Ｐ<³←⮌θＦ²«Ｊ³⁻×⁴ι²θＰ<²Ｉι↗Ｆ²«Ｐ⁺⁺θικ↓↓

```

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

```
Ｐ<³

```

Print the left pairs of `/`s and `\`s.

```
←⮌θ

```

Print the input right-justified at the current position.

```
Ｆ²«

```

Loop through the branches.

```
Ｊ³⁻×⁴ι²

```

Move the the position of the branch. We can do this because the root was printed right-justified so that the middle branch is always at the same absolute position.

```
θ

```

Print the input.

```
Ｐ<²

```

Print the right pair of `/` and `\`.

```
Ｉι

```

Print the branch suffix.

Move to the first leaf.

```
Ｆ²«

```

Loop through the leaves.

```
Ｐ⁺⁺θικ

```

Print the input and the branch and leaf suffix.

```
↓↓

```

Move to the next leaf. Note: If trailing whitespace was acceptable then `Ｆ²⁺⁺⁺θικ¶¶` would save a byte.
> 0 votes

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


title: How Many Rectangles in the Grid?

text:
# Question
Title: How Many Rectangles in the Grid?
> Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of *unique* rectangles. Check it out!
>
> Now, for those of you looking to solve *this* challenge, here it comes.

---

Well, we don't really have a challenge like this yet, so here we go.

Consider this `3 x 3` grid of rectangles:

How many rectangles are there? Well, counting visually, we can see that there are actually `36` rectangles, including the entire plane itself, which are all shown in the animated GIF below:

## The Task

The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to `0`, `m` and `n`, where `m` represents the width and `n` represents the height, output the total number of rectangles in that `m x n` grid of rectangles.

## Rules

* The use of any built-ins that directly solve this problem is explicitly disallowed.
* This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted.
* Standard loopholes are prohibited.

## Test Cases

Presented in the format `Array of Integers Input -> Integer Output`:

```
[0,0] -> 0
[1,1] -> 1
[3,3] -> 36 (Visualized above)
[4,4] -> 100
[6,7] -> 588

```

## References

Remember, this is , so shortest code wins!

# Answer
> 34 votes
## Python, 22 bytes

```
lambda m,n:m*~m*n*~n/4

```

The formula `m*n*(m+1)*(n+1)/4` is shortened using the bit-complement `~m=-(m+1)`, expressing `(m+1)*(n+1)` as `~m*~n`.

Why is the number of rectangles `m*n*(m+1)*(n+1)/4`? Each rectangle is specified by the choice of two horizontal lines (top and bottom) and two vertical lines (left and right). There are `m+1` horizontal lines, of which we choose a subset of two distinct ones. So the number of choices is `choose(m+1,2)`, which is `m*(m+1)/2`. Multiplying by the `n*(n+1)/2` choices for vertical lines gives the result.

# Answer
> 11 votes
# Jelly, 4 bytes

```
RS€P

```

Try it online!

### Alternatively, also 4 bytes

```
pP€S

```

Try it online!

# Answer
> 9 votes
# Javascript (ES6), 17 bytes

```
m=>n=>m*n*~m*~n/4

```

A fork of this answer.

```
f=m=>n=>m*n*~m*~n/4
alert(f(prompt())(prompt()))
```

# Answer
> 9 votes
## Mathematica, 15 bytes

```
##(1##+##+1)/4&

```

This is an unnamed function taking two integer arguments and returning the number of rectangles.

### Explanation

The implementation is basically a very golfy form of the product of the two triangular numbers. It might be worth reading the section "Sequences of arguments" in this post for the details, but I'll try to summarise the gist here.

`##` expands to a *sequence* of all arguments. This is similar to *splatting* in other languages. For instance, if the arguments are `3` and `4`, then `{1, 2, ##, 5}` will give you `{1, 2, 3, 4, 5}`. But this doesn't just work in lists, but in any expression whatsoever, e.g. `f[1, 2, ##, 5]` would also be `f[1, 2, 3, 4, 5]`.

This gets interesting when you combine `##` with operators. All operators in Mathematica are just short-hands for some `f[...]`-like expression (possibly nested). E.g. `a+b` is `Plus[a, b]` and `a-b` actually represents `Plus[a, Times[-1, b]]`. Now when you combine `##` with operators, what Mathematica does is to expand the operators first, treating `##` like a single operand, and expand them only at the end. By inserting `##` in the right places, we can therefore use it both to multiply and to add the operands.

Let's do this for the code above:

```
##(1##+##+1)/4

```

Expanding it to its full form, we get this:

```
Times[##, Plus[Times[1, ##], ##, 1], Rational[1/4]]

```

Let's insert the function arguments `a` and `b`:

```
Times[a, b, Plus[Times[1, a, b], a, b, 1], Rational[1/4]]

```

And now we convert it back into standard mathematical notation:

```
a * b * (a * b + a + b + 1) / 4

```

A little rearranging shows that this is the product of the triangular numbers:

```
a * b * (a + 1) * (b + 1) / 4
(a * (a + 1) / 2) * (b * (b + 1) / 2)
T(a) * T(b)

```

Fun fact: this implementation is so golfy, it's the same length as the built-in for computing a single triangular number, `PolygonalNumber`.

# Answer
> 8 votes
# C, 25 bytes

```
#define r(x,y)x*y*~x*~y/4

```

Purist version (27):

```
r(x,y){return x*y*~x*~y/4;}

```

ISO-er version (35):

```
#define r(x,y)((x)*(y)*~(x)*~(y)/4)

```

# Answer
> 8 votes
## Jellyfish, 16 bytes

```
p|%/**+1
  4  Ei

```

Input format is `[x y]`, output is just the result.

Try it online!

Alternative solution, same byte count:

```
pm%/*[*i
  4  +1

```

### Explanation

Time to give Jellyfish the introduction it deserves! :)

Jellyfish is Zgarb's language based on his 2D syntax challenge. The semantics are largely inspired by J, but the syntax is a work of art. All functions are single characters and laid out on a grid. Functions take their arguments from the next token south and east of them and return the result north and west. This let's you create an interesting web of function calls where you reuse values by passing them into several functions from multiple directions.

If we ignore the fact that some of tokens in the above program are special *operators* (higher-level functions), the above program would be written something like this in a sane language:

```
p(|( /*(i*(i+1)) % 4 ))

```

Let's go through the code bottom-up. Input gets fed in by the `i`, which therefore evaluates to `[x y]`.

The `+` on top of it receives this input together with the literal `1` and therefore increments both elements to give `[(x+1) (y+1)]` (most operations are threaded automatically over lists).

The other value of `i` is sent left, but the `E` splits is eastern argument north and west. That means the inputs to the right `*` are actually `[x y]` and `[(x+1) (y+1)]` so this computes `[x*(x+1) y*(y+1)]`.

The next `*` up is actually modified by the preceding `/` which turns it into a fold operation. Folding `*` over a pair simply multiplies it, so that we get `x*(x+1)*y*(y+1)`.

Now `%` is just division so it computes `x*(x+1)*y*(y+1)/4`. Unfortunately, this results in a float so we need to round it with the unary `|`. Finally, this value is fed to `p` which prints the final result.

# Answer
> 7 votes
# R, ~~40~~ 35 bytes

Well, time to jump in at the deep end ! Here is my **R** code, inspired from @xnor answer :

~~```
a=scan();(n=a[1])*(m=a[2])*(n+1)*(m+1)/4

```~~

*EDIT* : In this version, **R** will ask twice for inputs.

```
(n=scan())*(m=scan())*(n+1)*(m+1)/4

```

# Answer
> 6 votes
# CJam, ~~12~~ 10 Bytes

2 bytes saved thanks to Martin.

```
{_:)+:*4/}

```

Try it online!

This is a block that takes a list of 2 elements from the stack and leaves the solution on the stack. Usable full program for testing: `riari+{_:)+:*4/}~`.

Based off of xnor's outstanding python solution.

Explanation:

```
{_:)+:*4/}
{        } -- Define a block
 _:)       -- Duplicate list, increment all values in new list
    +      -- Join the two lists
     :*    -- Fold multiply over all 4 elements
       4/  -- Divide by 4

```

# Answer
> 5 votes
## Matlab, ~~23~~ 19 bytes

```
@(x)prod([x/2,x+1])

```

Implementation of the formula `m*n*(m+1)*(n+1)/4`
Usage: `ans([m,n])`

# Answer
> 4 votes
# MATL, 6 bytes

```
tQ*2/p

```

Input is an array of the form `[m,n]`.

**Try it online!**

### Explanation

Direct computation based on the formula `m*(m+1)*n*(n+1)/4`.

```
t     % Input array [m,n] implicitly. Duplicate
Q     % Add 1 to each entry of the copy: gives [m+1,n+1]
*     % Multiply element-wise: gives [m*(m+1),n*(n+1)]
2/    % Divide each entry by 2: [m*(m+1)/2,n*(n+1)/2]
p     % Product of the two entries: m*(m+1)*n*(n+1)/4. Display implicitly

```

# Answer
> 4 votes
# Java 7, ~~39~~ 38 bytes

```
int c(int a,int b){return~a*a*b*~b/4;}

```

# Java 8, ~~26~~ ~~25~~ ~~19~~ ~~18~~ 17 bytes

```
a->b->a*~a*b*~b/4

```

Based on *@xnor*'s excellent answer. Multiple bytes saved thanks to *@DavidConrad*. Try it here.

**Test code (Java 7):**

Try it here.

```
class M{
  static int c(int a,int b){return~a*a*b*~b/4;}

  public static void main(String[] a){
    System.out.println(c(0, 0));
    System.out.println(c(1, 1));
    System.out.println(c(3, 3));
    System.out.println(c(4, 4));
    System.out.println(c(6, 7));
  }
}

```

**Output:**

```
0
1
36
100
588

```

# Answer
> 4 votes
# J, 8 bytes

```
2*/@:!>:

```

**Usage:**

```
   f =: 2*/@:!>:
   f 0 0
0
   f 3 3
36

```

# Answer
> 3 votes
## Labyrinth, ~~13~~ 11 bytes

```
*?;*_4/!
):

```

Try it online!

### Explanation

This also computes the product of the triangular numbers like most answers. The leading 2x2 block is a small loop:

```
*?
):

```

On the first iteration `*` doesn't do anything, so that the real loop order is this:

```
?   Read integer N from STDIN or 0 at EOF and push onto stack. If 0, exit the loop.
:   Duplicate N.
)   Increment.
*   Multiply to get N*(N+1).

```

The remaining code is just linear:

```
;   Discard the zero that terminated the loop.
*   Multiply the other two values.
_4  Push a 4.
/   Divide.
!   Print.

```

Labyrinth then tries to execute `/` again, which terminates the program due to a division by zero.

# Answer
> 3 votes
# Ruby, 22 bytes

Stealing @xnor's trick and making a stabby-lambda:

```
r=->(m,n){m*n*~m*~n/4}

```

Example call:

```
r[6,7]     # => 588

```

Or as a proc, also 22 bytes:

```
proc{|m,n|m*n*~m*~n/4}

```

Which we could then call:

```
proc{|m,n|m*n*~m*~n/4}.call(6,7)     # => 588

```

# Answer
> 2 votes
## Pyke, 6 bytes

```
mh+Bee

```

Try it here!

```
mh     -    map(increment, input)
  +    -   ^ + input
   B   -  product(^)
    ee - ^ \ 4

```

# Answer
> 2 votes
## 05AB1E, 4 bytes

```
€LOP

```

**Explanation**

Uses the formula described at A096948

```
      # Implicit input, ex: [7,6]
€L    # Enumerate each, [[1,2,3,4,5,6,7],[1,2,3,4,5,6]]
  O   # Sum, [28,21]
   P  # Product, 588
      # Implicit display

```

Takes input as **\[n,m\]**.

Try it online

# Answer
> 1 votes
# Pyth, ~~8~~ 6 bytes

Two bytes saved thanks to @DenkerAffe.

```
*FmsSd

```

Input is expected as a list like `[m,n]`. Try it out here.

Explanation:

```
          Implicit assignment of Q to eval(input).
*         Multiplication.
 F        Splat the following sequence onto the arguments of the previous function.
  m       Map the following function of d over Q (Q is implicitly added to the end).
   s      Reduce the following list with addition, initial value of 0.
    Sd    Return range(1,d+1).

```

# Answer
> 1 votes
## Lua, ~~74~~ 63 bytes

```
x,y=...n=0 for i=1,y do for j=i,i*x,i do n=n+j end end print(n)

```

Function takes input as number parameters.

Because of the way Lua is implemented, this is technically a function, with variable args, which can be called by wrapping it in a "function" statement, or loading it from source code using "loadstring"

# Answer
> 1 votes
## C#, 19 bytes

```
(n,m)=>m*n*~m*~n/4;

```

An anonymous function based off of @xnor's answer.

# Answer
> 1 votes
# Cheddar, 23 bytes

```
m->n->m*(m+1)*n*(n+1)/4

```

# Answer
> 1 votes
# Brain-Flak, ~~84~~ 80 bytes

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

```

Try it online!

Probably very sub-optimal, especially because of the code reuse regarding triangle numbers, but at least we have a Brain-Flak solution that works.

Sadly it seems to fail by looping infinitely with the `0 0` testcase but all others work fine.

# Answer
> 0 votes
## Convex, 7 bytes

I know that this can be smaller, I just can't figure out how yet...

```
_:)+×½½

```

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

# Answer
> 0 votes
# Pyt, 3 bytes

```
←△Π

```

Explanation:

```
←       Get input
 △      Get triangle numbers
  Π     Array product
        Implicit output

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog), 9 bytes

```
×/+/∘⍳¨∘⊢

```

Try it online!

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


title: Make me a pizza

text:
# Question
Title: Make me a pizza
Because it's Saturday (UTC) and I'm hungry, I would like a slice of pizza. I will give you an order and I would like a nice hot pizza. Up to the challenge?

## The Drive-Thru

I'll place my order wherever your drive-thru is, whether it is STDIN, a function parameter, a command-line argument, but I'm not going to put it in a variable for you. (JS function expressions must be assigned to a variable.)

## The order

My order will have 2 parts. The first will be a positive, non-zero integer from `3` to `6`. This is the size of my pizza. For instance, a size `6` pizza with no toppings would look like:

```
 /=====\
/       \
|       |
|       |
\       /
 \=====/

```

A size `5`:

```
 /====\
/      \
|      |
\      /
 \====/

```

A size `4`:

```
 /===\
|     |
|     |
 \===/

```

A size `3`

```
 /==\
|    |
 \==/

```

## The toppings

My toppings will be a string of UPPERCASE letters. Here are the possible values:

```
P - Pepperoni
S - Sausage
N - piNeapple
J - Jalapenos
B - Banana peppers
C - baCon

```

You must fit them on the pizza somewhere. If I order a size 4 and `PSPCJ`, then this is a valid output:

```
 /===\
|PSPCJ|
|     |
 \===/

```

So is this:

```
 /===\
|P P J|
| S C |
 \===/

```

And this:

```
 /===\
|     |
|PSPCJ|
 \===/

```

I am not really picky about where my toppings are on the pizza, as long as they aren't on the crust or on top of each other.

## The pick-up window

I will go to a lot of places to pick up my pizza, including STDOUT, a file, the return value of a function, but not a variable.

## Extra stuff

* Standard loopholes forbidden
* **This is tagged so the shortest answer in bytes wins!**
* Don't worry about invalid input (toppings \> pizza space, etc.)
* See my answer (JS ES6) below for an example (I hope you can do better)

# Answer
> 0 votes
# Pip, ~~87~~ ~~81~~ 75 bytes

74 bytes of code, +1 for `-l` flag.

```
e:'/.'=Xa-1.'\Y['/'\]Xa//5J'|X2-a%2^xPs.ePy.(b.sXa*a-a-2-#b<>a+1).RVys.RVe

```

Takes input as command-line arguments. Try it online!

### Approach

`e` is the top row, such as `/=====\`. If you reverse it, it's also the bottom row.

`y` is the left border, such as `["/" "|" "|" "\"]`. If you reverse it, it's also the right border.

We then construct the middle by taking `b`, the toppings, padding it with spaces to length `(a+1)*(a-2)` (where `a` is the size), and grouping it into a list of rows.

Finally, we print the top row with a leading space; concatenate the middle between `y` on the left and `RVy` on the right, and print that; and print the bottom row with a leading space.

# Answer
> 4 votes
# Python 2, ~~202,198,190,177,162,157,~~146 bytes

```
n,t=input()
y=n+1
s=' '
l=' /'+'='*(n-1)+'\\ '+('','\n/'+s*y+'\\')[n>4]+'\n|'
print l+t[:y].center(y,s)+('','|\n|'+t[y:].center(y,s))[y%2]+l[::-1]

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~224~~ ~~213~~ 195 bytes

```
n,t=eval(input())
k=n+1
y=print
i=0
f,s,e,b,p="/ =\\|"
t+=s*99
y(s+f+e*~-n+b)
if n>4:y(f+t[:k]+b);i+=k
y(p+t[i:i+k]+p);i+=k
if~-n%2:y(p+t[i:i+k]+p);i+=k
if n>4:y(b+t[i:i+k]+f);i+=k
y(s+b+e*~-n+f)

```

Try it online!

# Answer
> 1 votes
# Charcoal, 37 bytes

```
Ｎθ /==×=⸿/›θ⁴⸿|‖ＢＯ↓﹪θ²‖ＢＯ⊕﹪θ²Ｊ¹¦¹⪪Ｓ⊕θ

```

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

```
Ｎθ

```

Input the size of the pizza.

```
 /==

```

Start printing the top of the pizza.

```
×=⸿/›θ⁴

```

If the pizza is one of the larger sizes, add extra to the top and side.

```
⸿|

```

Print more of the side of the pizza.

```
‖ＢＯ↓﹪θ²

```

Complete the left half of the pizza by reflection with possible overlap.

```
‖ＢＯ⊕﹪θ²

```

Complete the pizza by reflection with variable overlap.

```
Ｊ¹¦¹⪪Ｓ⊕θ

```

Input the toppings and split them into pieces so they will fit inside the pizza.

# Answer
> 0 votes
# JS (ES6), 257 255 249 248 246 244 bytes

```
m=s=>t=>(r="/",k="\\",p=" ",f="\n",x="|",c=f+x,q="",t=p+t,z=(s>2?p:q)+r+"=".repeat(s-1)+k+(s>4?f+r+p.repeat(++s)+k:q)+c+p.repeat(s)+x+(!s?c+p.repeat(s)+x:q)+p+(s>5?f+k+p.repeat(s)+r:q)+f+p+k+"=".repeat(s-2)+r,i=-1,z.replace(/ /g, x=>t[++i]||p))

```

Call it like `m(4)("PS")` for 1 pepperoni and 1 sausage. Probably can be golfed more.

# Answer
> 0 votes
## JavaScript (ES6), ~~170~~ 161 bytes

```
(n,t,a=[1,,n%2||2,,1])=>` /=\\
/___\\
|___|
\\___/
 \\=/`[r=`replace`](/.+/g,s=>s.repeat(a.pop()||n>4))[r](/=|_\b/g,`$&`.repeat(n-1))[r](/_/g,_=>t[i++]||` `,i=0)

```

Starts by taking a misshapen pizza of width 2 and height 5 and stretches it horizontally and adjusts it vertically as appropriate, then replaces the interior with toppings or spaces once they run out.

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


title: How small can it get?

text:
# Question
Title: How small can it get?
Starting with a positive integer **N**, find the smallest integer **N'** which can be computed by repeatedly dividing **N** by one of its digits (in base-10). Each selected digit must be a divisor of **N** greater than **1**.

## Example #1

The expected output for **N = 230** is **N' = 23**:

## Example #2

The expected output for **N = 129528** is **N' = 257**:

Beware of non-optimal paths!

We could start with **129528 / 9 = 14392**, but that would not lead to the *smallest* possible result. The best we can do if we first divide by 9 is:

## Rules

* Input can be taken in any reasonable format (integer, string, array of digits, ...).
* This is , so the shortest answer in bytes wins!

## Test cases

```
1         --> 1
7         --> 1
10        --> 10
24        --> 1
230       --> 23
234       --> 78
10800     --> 1
10801     --> 10801
50976     --> 118
129500    --> 37
129528    --> 257
8377128   --> 38783
655294464 --> 1111

```

# Answer
# Haskell, ~~67~~ 61 bytes

```
f n=minimum$n:[f$div n d|d<-read.pure<$>show n,d>1,mod n d<1]

```

Try it online!

### Explanation:

* `read.pure<$>show n` transforms the input integer `n` into a list of digits.
* For each digit `d` from this list, we check `d>1` and `mod n d<1`, that is whether `d` divides `n`.
* If the checks are successful, we divide `n` by `d` and recursively apply `f`: `f$div n d`.
* Altogether, this yields a list of the minimal integers from all sub-trees of `n`.
* As the list might be empty, we append `n` to it and return the `minimum` of the list.
> 11 votes

# Answer
# Jelly, 8 bytes

```
÷DfḶß€Ṃo

```

Try it online!

### Alternate version, much faster, 9 bytes

```
÷DfÆḌß€Ṃo

```

Try it online!

### How it works

```
÷DfḶß€Ṃo  Main link. Argument: n

 D        Decimal; yield the digits of n.
÷         Divide n by each of its digits.
   Ḷ      Unlength; yield [0, ..., n-1].
  f       Filter; keep quotients that belong to the range.
    ß€    Recursively map this link over the resulting list.
      Ṃ   Take the minimum. This yields 0 if the list is empty.
       o  Logical OR; replace 0 with n.

```
> 11 votes

# Answer
# Python 2, 59 bytes

```
f=lambda a:min([f(a/k)for k in map(int,`a`)if k>1>a%k]+[a])

```

Try it online!
> 9 votes

# Answer
# Ruby, ~~52~~ 47 bytes

Competing for the non-exotic languages group! (Note: a good idea, if not golfing, is to add `.uniq` after `.digits` because all similar branches have similar results)

```
f=->n{n.digits.map{|x|x>1&&n%x<1?f[n/x]:n}.min}

```

Try it online!

## Explanation

```
f=->n{      # Function "f" n ->
   n.digits # n's digits (in reverse order (<- doesn't matter))
            # fun fact: all numbers always have at least one digit
    .map{|x|# Map function for every digit "x" ->
       x>1&&    # x is 2-9 and
       n%x<1    # n mod x == 0, or, "n is divisible by x"
       ? f[n/x] # then recursively find smallest of f[n/x]
       : n      # otherwise: n (no shortest path in tree)
     }.min  # Smallest option out of the above
            # if we reach a dead end, we should get n in this step
}

```
> 5 votes

# Answer
## Common Lisp, 136 bytes

```
(defun f(n)(apply 'min(or(loop for z in(map'list #'digit-char-p(write-to-string n))if(and(> z 1)(<(mod n z)1))collect(f(/ n z)))`(,n))))

```

Try it online!

**Readable version:**

```
(defun f (n)
  (apply 'min
         (or (loop for z in (map 'list
                                 #'digit-char-p
                                 (write-to-string n))
                   if (and (> z 1)
                           (< (mod n z) 1))
                   collect (f (/ n z)))
             `(,n))))

```
> 5 votes

# Answer
# Jelly, 21 bytes

```
Dðḍ>Ị{
DxÇ⁸:ß€µÇẸ$¡FṂ

```

Try it online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 44 bytes

-7 bytes thanks to Misha Lavrov.

```
Min[#0/@(#/IntegerDigits@#⋂Range[#-1]),#]&

```

Try it online!
> 4 votes

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

```
f=n=>Math.min(...(for(c of''+n)c<2|n%c?n:f(n/c)))

```

ES6-compatible version, 52 bytes:

```
f=n=>Math.min(...[...''+n].map(c=>c<2|n%c?n:f(n/c)))
```

```
<input type=number oninput=o.textContent=f(this.value)><pre id=o>
```

Originally I tried filtering out irrelevant digits but it turns out to be slightly longer at 54 bytes:

```
f=n=>Math.min(n,...(for(c of''+n)if(c>1&n%c<1)f(n/c)))

```
> 4 votes

# Answer
# APL (Dyalog), 33 bytes

```
{⍬≡d←o/⍨0=⍵|⍨o←1~⍨⍎¨⍕⍵:⍵⋄⌊/∇¨⍵÷d}

```

Try it online!

**How?**

`⍎¨⍕⍵` \- grab digits of `n`

`1~⍨` \- excluding `1`s

`o/⍨` \- filter by

`0=⍵|⍨o` \- divisibility of `n` by the digit

`⍬≡...:⍵` \- if empty, return `n`

`⌊/` \- otherwise, return minimum of

`∇¨` \- recursion for each number in

`⍵÷d` \- the division of `n` by each of the digits filtered above
> 3 votes

# Answer
# Kotlin, ~~100~~ 99 bytes

```
fun f(i:Int):Int{return i.toString().map{it.toInt()-48}.filter{it>1&&i%it<1}.map{f(i/it)}.min()?:i}

```

## Beautified

```
fun f(i:Int):Int{
    return i.toString()
        .map { it.toInt()-48 }
        .filter { it >1 && i % it < 1}
        .map { f(i/it) }
        .min() ?: i
}

```

## Test

```
fun f(i:Int):Int{return i.toString().map{it.toInt()-48}.filter{it>1&&i%it<1}.map{f(i/it)}.min()?:i}

val tests = listOf(
        1 to 1,
        7 to 1,
        10 to 10,
        24 to 1,
        230 to 23,
        234 to 78,
        10800 to 1,
        10801 to 10801,
        50976 to 118,
        129500 to 37,
        129528 to 257,
        8377128 to 38783,
        655294464 to 1111)

fun main(args: Array<String>) {
    for ( test in tests) {
        val computed = f(test.first)
        val expected = test.second
        if (computed != expected) {
            throw AssertionError("$computed != $expected")
        }
    }
}

```

## Edits
> 3 votes

# Answer
# Jelly, 15 bytes

```
ÆDḊfD
:Çß€µÇ¡FṂ

```

**Try it online!**

I must admit that the `ß€` part is borrowed from Erik's answer. The rest is developed separately, partly because I don't even understand how the rest of that answer works anyway :P.

### How it works?

```
ÆDḊfD ~ Helper link (monadic). I'll call the argument N.

ÆD    ~ Take the divisors.
  Ḋ   ~ Dequeue (drop the first element). This serves the purpose of removing 1.
   fD ~ Take the intersection with the decimal digits.

:Çß€µÇ¡FṂ ~ Main link.

 Ç        ~ Apply the helper link to the first input.
:         ~ And perform element-wise integer division.
     Ç¡   ~ If the helper link applied again is non-empty*, then...
  ß€µ     ~ Apply this link to each (recurse).
       FṂ ~ Flatten and get the maximum.

```

<sup>\*I am pleasantly surprised that `¡` works like that on lists, because its normal meaning is *apply this **n** times*.</sup>

After Dennis explained why `ß€` doesn't need a conditional, we have this 12-byter, or his 8 byte version :P.
> 3 votes

# Answer
# , ~~101~~ 98 bytes

```
f=function(x,e=(d=x%/%10^(0:nchar(x))%%10)[d>1])"if"(sum(y<-which(!x%%e)),min(sapply(x/e[y],f)),x)

```

Try it online!

A ton of bytes go into extracting the digits and which ones divide `x`; perhaps another approach is necessary.
> 3 votes

# Answer
## Excel Vba, 153 bytes

First ever code-golf in the only language I know :( Not exactly golf-friendly...

```
Function S(X)
S = X
For I = 1 To Len(CStr(X))
A = Mid(X, I, 1)
If A > 1 Then If X Mod A = 0 Then N = S(X / A)
If N < S And N > 0 Then S = N
Next I
End Function

```

Call like this:

```
Sub callS()

result = S(655294464)

MsgBox result

End Sub

```

I haven't a clue where to test this online.
> 3 votes

# Answer
# Perl 5, 87 + 1 (`-p`) = 88 bytes

```
$r=0,map{$\=$_,$r++if!$\|$_<$\;for$i(/[2-9]/g){$_%$i||$h{$_/$i}++}}$_,keys%h;$r&&redo}{

```

try it online
> 2 votes

# Answer
# PHP, 120 bytes

```
<?php function f($n){$r=array_map(function($x)use($n){return$x>1&&!($n%$x)?f($n/$x):$n;},str_split($n));return min($r);}

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 49 bytes

```
f(n)=vecmin([if(d<2||n%d,n,f(n/d))|d<-digits(n)])

```

Try it online!
> 2 votes

---
Tags: code-golf, integer, optimization, division
---


title: VEVO User Account Checker

text:
# Question
Title: VEVO User Account Checker
We often see music videos on Youtube. Many Youtube channels that host music videos are "powered by VEVO". Those can be easily identified by both embedding VEVO at their video thumbnails and appending VEVO to their channel name.

Now write some code to test whether a string given by user is a VEVO user account or not.

Requirements for valid VEVO user account strings:

* Must only contain uppercase, lowercase, and digit characters. (no whitespace or punctuation)
* Must not exceed 80 characters length.
* Must have "VEVO" substring at the end of string

Test cases:

Valid inputs:

```
AdeleVEVO
ConnieTalbotVEVO
SHMVEVO
justimberlakeVEVO
DJMartinJensenVEVO
test123VEVO

```

Invalid inputs:

```
syam kapuk
jypentertainment
Noche de Brujas
testVEVO123

```

Of course, because this is , I'm looking for the shortest code using any programming language.

# Answer
> 9 votes
# Python 2, 45 bytes

*-3 bytes thanks to Rod. -2 bytes thanks to ovs.*

```
lambda s:len(s)<81*s.isalnum()<'VEVO'==s[-4:]

```

Try it online!

A regex solution turns out to be longer.

```
lambda s:re.match('^[^\W_]{0,76}VEVO$',s)
import re

```

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

Returns `1` for valid or `0` for invalid. `[\l\d]` would also work in place of `[^\W_]` for the same byte count.

```
è/^\w{0,76}VEVO$

```

Try it | Check all test cases

**Explanation**: `è` counts the number of matches of the RegEx in the input. In Japt, the `\w` RegEx class doesn't include underscore.

# Answer
> 4 votes
# JavaScript (ES6), ~~27~~ ~~36~~ ~~34~~ 31 bytes

*Saved 2 bytes thanks to @Neil and 3 bytes thanks to @Shaggy*

```
s=>/^[^\W_]{0,76}VEVO$/.test(s)

```

### Test cases

```
let f =

s=>/^[^\W_]{0,76}VEVO$/.test(s)

console.log(f('syam kapuk')) // (INVALID)
console.log(f('jypentertainment')) // (INVALID)
console.log(f('Noche de Brujas')) // (INVALID)
console.log(f('testVEVO123')) // (INVALID)
console.log(f('AdeleVEVO')) // (VALID)
console.log(f('ConnieTalbotVEVO')) // (VALID)
console.log(f('SHMVEVO')) // (VALID)
console.log(f('justimberlakeVEVO')) // (VALID)
console.log(f('DJMartinJensenVEVO')) // (VALID)
```

# Answer
> 4 votes
# PHP, 51 bytes

-10 bytes thanks to @Ismael Miguel for using `<?=` instead of `<?php echo`! and removing the closing tag

```
<?=preg_match("/^[^\W_]{0,76}VEVO$/",fgets(STDIN));

```

Try it online!

Thanks for the other answers so I didn't have to write the regex!

# Answer
> 3 votes
# Dyalog APL, 47 bytes

```
{0::0⋄(∧/(1(819⌶)t)∊⎕A,⎕D)∧77>≢t←,∘'VEVO'⍣¯1⊢⍵}

```

Try it online!

A pure regex solution is 32 bytes, but also is much more boring than this approach.

```
{0::0⋄(∧/(1(819⌶)t)∊⎕A,⎕D)∧77>≢t←,∘'VEVO'⍣¯1⊢⍵} a dfn with right arg '⍵'
 0::0⋄                                          on error, return 0
                                 ,∘'VEVO'       a train that appends VEVO
                                         ⍣¯1    apply it -1 times
                                             ⍵  on '⍵'
                                                and error if impossible (which returns 0)
                               t←               save on variable 't'
                              ≢                 get the length of that
                           77>                  if that's smaller than 77
                          ∧                     and
         (1(819I)t)                              [for each of] 't' uppercased
                   ∊⎕A,⎕D                        is it in the uppercase alphabet concatenated with the digits
       ∧/                                        reduced by and

```

# Answer
> 3 votes
# C# (.NET Core), 87 + 18 = 105 bytes

Try it online!

```
a=>a.Where(x=>char.IsLetterOrDigit(x)).Count()==a.Length&a.Length<81&a.EndsWith("VEVO")

```

# Answer
> 3 votes
# APL (Dyalog), 25 bytes

```
≢'^[^_\W]{0,76}VEVO$'⎕S 3

```

Try it online!

# Answer
> 3 votes
# C (gcc), 83 bytes

```
c,i;f(char*s){for(c=i=0;s[i];c+=!isalnum(s[i++]));c=i<81*!c*!strcmp("VEVO",s+i-4);}

```

Try it online!

# Answer
> 3 votes
# Grime, 13 bytes

```
e`n{-76"VEVO"

```

Try it online!

Nothing fancy here. Match the `e`ntire input against the pattern: at most 76 alpha`n`umeric characters, followed by the string `VEVO`. Prints `1` for match and `0` for no match. I remembered that the last quote could be removed at end of line, but apparently it just causes a parse error.

# Answer
> 2 votes
# \>\<\>, ~~147~~ 125 bytes

```
!\i:0(?^1[::::::"/9@Z`z"!
;>{(?;{(?v{(?;{(?v{(?;{(?v
 ~l1-?!v >       > !|!: !<
;v    ]/~l99*-0(?!;4["OVEV"{-?;{-?;{-?;{-?;1n

```

Try it online!

# \>\<\>, 147 bytes

Try it online!

This prints 1 if the input string is valid and nothing for an invalid input.

Edit 1: Changed the Alphanumeric checks to use ranges rather than comparing against every character. (saving 22 bytes)

# Answer
> 2 votes
# Bash, ~~53~~ ~~26~~ 30 bytes

```
[[ $1 =~ ^[^\W_]{0,76}VEVO$ ]]

```

Exit code 0 for VALID results and 1 for INVALID results.

~~Still working on 80 characters or less.~~

-27 bytes from removing output, thanks to @KeyWeeUsr

+4 bytes, fixed regex (same as everyone else)

Try it online!

# Answer
> 2 votes
# \>\<\>, ~~101~~ ~~89~~ ~~83~~ ~~81~~ 94 bytes

Edit: ~~Switched to checking for non-alphanumeric characters rather than for alphanumeric.~~ Switched back cause I forget to check between Z and a. Thanks @Emigna. Rip those lost bytes though

Edit 2: Also, I can totally just get rid of those }}}}. Thanks Teal pelican for that and finding the problem with TIO

Edit 3: replaced a ~~~ with a p

```
!\i::0(?v:::"/")$":"(*$:"`")$"{"(*+$:"@")$"["(*+?
0/?("S"l/
l/"VEVO"[4pn?$0(6
!\{-?vl?
1/;n0/n

```

~~I don't know why this won't work on TIO, but it works fine here.~~ The problem was that the {} commands in TIO don't work for an empty list. Try It Here

### How It Works

```
!\i::0(?v:::"/")$":"(*$:"`")$"{"(*+$:"@")$"["(*+?
0/....../
......... Checks each input is alphanumeric
...       If any isn't, print 0 and exit with an error
...

...
0/?("S"l/ Checks if there are more than 80 characters
...       If so, print 0 and exit with an error
...
...

...
...
l/"VEVO"[4pn?$0(6 Check if the input is less than 4 characters
...               If so, print 0 and exit with an error
...

...
...
./"VEVO"[4pn?$0(6 Take the last 4 characters of the input into a new stack (first time I've actually used [)
...               Add "VEVO" to the stack to compare
...

...
0/....../n
........V
!\{-?vl?  Check if the last 4 characters are VEVO
1/;n0/n   Print 1 and exit with an error if so, else print 0 and exit

```

For consistency, replacing the ; in the last line with an invalid instruction makes *every* output an error.

# Answer
> 2 votes
## C++, ~~129~~ ~~105~~ 102 bytes

Thanks to other answers that showed me that i can count the number of characters
-2 bytes thanks to Zacharý

```
#include<regex>
int v(std::string s){return std::regex_match(s, std::regex("[a-zA-Z0-9]{0,76}VEVO"));}

```

TIO LINK

# Answer
> 2 votes
# Stacked, 21 bytes

```
['^\i{0,76}VEVO'-''=]

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 21 bytes

```
žKÃQsg81‹IR4£"OVEV"QP

```

Try it online!

# Answer
> 1 votes
# Retina, 18 bytes

```
A`\W|_|.{81}
VEVO$

```

Try it online!

or

```
^[^\W_]{0,76}VEVO$

```

Try it online!

# Answer
> 1 votes
# Haskell, 75 bytes

*-2 bytes thanks to user28667.*

```
import Data.Char
f s|l<-length s=all isAlphaNum s&&l<81&&drop(l-4)s=="VEVO"

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), 37 36 bytes

Pretty simple answer using some lovely regex.
Quite possibly the shortest Java answer I've ever done.
-1 bytes thanks to Neil on the Javascript answer

```
w->w.matches("((?!_)\\w){0,76}VEVO")

```

Try it online!

# Answer
> 1 votes
# Deorst, 22 bytes

```
'^[^\W_]{0,76}VEVO$'gm

```

Try it online!

Just uses the regex found by Shaggy

# Answer
> 1 votes
# , 17 bytes

```
ø^¨áüä©û,76}VEVO$

```

Try it online!

Hexdump:

```
00000000: f85e a8e1 fce4 a9fb 2c37 367d 5645 564f  .^......,76}VEVO
00000010: 24                                       $

```

Compressed regexes for the win!

```
ø                   " Count the number of matches of
 ^                  "   The beginning of the line
  ¨áüä©             "   A letter or number...
       û,76}        "   From 0 to 76 times...
            VEVO    "   Followed by "VEVO"
                $   "   At the end of the line

```

# Answer
> 1 votes
# Perl 5, ~~35~~ 29+1(-a) = 30 bytes

*-6 bytes thanks to ETHproductions*

*Added 4 bytes. Didn't see that underscore wasn't allowed.*

This is my first golf, so here's hoping I did it right.

Returns 1 if valid, 0 if not.

```
print/^[^\W_]{0,76}VEVO$/?1:0

```

Try it online!

# Answer
> 1 votes
# Ruby -n, 22+1 = 23 bytes

```
p~/^[^\W_]{0,76}VEVO$/

```

Output `0` if true, `nil` if false

Try it online!

Using the same boring regex as everybody else.

# Answer
> 1 votes
# Swift 4, 113 bytes

```
import Foundation;var f={(s:String)->Bool in s.range(of:"^[^\\W_]{0,76}VEVO$",options:.regularExpression) != nil}

```

Try it online!

# Answer
> 1 votes
# AWK, 23 bytes

```
$0~/^[^\W_]{0,76}VEVO$/

```

Try it online!

Outputs the account name if valid, and outputs nothing if it isn't valid

# Answer
> 1 votes
# Clean, 61 bytes

```
import StdEnv
?['VEVO']=True
?[_:l]=length l<80&& ?l
?_=False

```

Try it online!

# Answer
> 0 votes
# Google Sheets, 33 Bytes

Anonymous worksheet function that takes input from range `A1` and outputs to the calling cell

```
=RegexMatch(A1,"^[^\W_]{0,76}VEVO

```

# Answer
> -1 votes
# Clojure, 146 bytes

```
(fn[u](let[c count](and(<(c u)81)(=(c(filter #(let[i(int %)](or(< 47 i 58)(< 64 i 91)(< 96 i 123)))u))(c u))(clojure.string/ends-with? u"VEVO"))))

```

Try it online!

This would be much shorter using a regex, but I figured doing it manually would be more interesting.

```
(defn vevo? [username]
  (and (< (count username) 81)

       ; Filter out the illegal characters, then check if the length is the same as the original string
       (= (count (filter #(let [i (int %)]
                            ; Make sure the char code is in the valid ranges
                            (or (< 47 i 58) (< 64 i 91) (< 96 i 123)))
                         username))
          (count username))

       (clojure.string/ends-with? username "VEVO")))

```

---
Tags: code-golf, string, decision-problem
---


title: XOR sort an array

text:
# Question
Title: XOR sort an array
Given a key, and an array of strings, shuffle the array so that it is sorted when each element is XOR'd with the key.

## XOR'ing two strings

To XOR a string by a key, XOR each of the character values of the string by its pair in the key, assuming that the key repeats forever. For example, `abcde^123` looks like:

```
       a        b        c        d        e
       1        2        3        1        2
--------------------------------------------
01100001 01100010 01100011 01100100 01100101
00110001 00110010 00110011 00110001 00110010
--------------------------------------------
01010000 01010000 01010000 01010101 01010111
--------------------------------------------
       P        P        P        U        W

```

## Sorting

Sorting should always be done Lexicographically of the XOR'd strings. That is, `1 < A < a < ~` (Assuming ASCII encoding)

## Example

```
"912", ["abcde", "hello", "test", "honk"]

-- XOR'd
["XSQ]T", "QT^U^", "MTAM", "Q^\R"]
-- Sorted
["MTAM", "QT^U^", "Q^\R", "XSQ]T"]
-- Converted back
["test", "hello", "honk", "abcde"]

```

## Notes

* Key will always be at least 1 character
* Key and Input will only consist of printable ASCII.
* XOR'd strings may contain non-printable characters.
* Input and Output may be done through the Reasonable Methods
* Standard Loopholes are forbidden.
* You may take Key and Input in any order.

## Test Cases

```
key, input -> output
--------------------
"912", ["abcde", "hello", "test", "honk"] -> ["test", "hello", "honk", "abcde"]
"taco", ["this", "is", "a", "taco", "test"] -> ["taco", "test", "this", "a", "is"]
"thisisalongkey", ["who", "what", "when"] -> ["who", "what", "when"]
"3", ["who", "what", "when"] -> ["what", "when", "who"]

```

This is , so least bytes wins!

# Answer
# Jelly, ~~9~~ 7 bytes

```
⁹ṁO^OµÞ

```

*Thanks to @EriktheOutgolfer for a suggestion that helped saving 2 bytes!*

Try it online!

### How it works

```
⁹ṁO^OµÞ  Dyadic link.
         Left argument: A (string array). Right argument: k (key string).

     µ   Combine the code to the left into a chain.
         Begin a new, monadic chain with argument A.
      Þ  Sort A, using the chain to the left as key.
         Since this chain is monadic, the key chain will be called monadically,
         once for each string s in A.
⁹            Set the return value to the right argument of the link (k).
 ṁ           Mold k like s, i.e., repeat its characters as many times as necessary
             to match the length of s.
  O          Ordinal; cast characters in the resulting string to their code points.
    O        Do the same for the chain's argument (s).
   ^         Perform bitwise XOR.

```
> 7 votes

# Answer
# Python 3, ~~75~~ 73 bytes

```
lambda k,x:x.sort(key=lambda s:[ord(x)^ord(y)for x,y in zip(s,k*len(s))])

```

This sorts the list **x** in-place.

*Thanks to @mercator for golfing off 2 bytes!*

Try it online!

### Alternate version, 62 bytes

This takes input as byte strings, which may not be allowed.

```
lambda k,x:x.sort(key=lambda s:[*map(int.__xor__,s,k*len(s))])

```

Try it online!
> 10 votes

# Answer
# Ruby, 61 bytes

```
->k,w{w.sort_by{|x|x.bytes.zip(k.bytes.cycle).map{|x,y|x^y}}}

```

Try it online!
> 3 votes

# Answer
## Haskell, 77 bytes

```
import Data.Bits
import Data.List
t=fromEnum
sortOn.zipWith((.t).xor.t).cycle

```

Too many imports.

Try it online!
> 3 votes

# Answer
# x86 opcode, 57 Bytes

```
0100  60 89 CD 4D 8B 74 8A FC-8B 3C AA 53 F6 03 FF 75
0110  02 5B 53 8A 23 AC 08 C0-74 0A 30 E0 32 27 47 43
0120  38 E0 74 E8 77 0A 8B 04-AA 87 44 8A FC 89 04 AA
0130  85 ED 5B 75 CE E2 CA 61-C3

    ;input ecx(length), edx(array), ebx(xor-d)
F:  pushad
L1: mov ebp, ecx
L2: dec ebp
    mov esi, [edx+ecx*4-4]
    mov edi, [edx+ebp*4]
    push ebx
L6: test [ebx], byte -1 ; t1b
    jnz L4
    pop ebx
    push ebx
L4: mov ah, [ebx]
    lodsb
    or  al, al
    jz  L7
    xor al, ah
    xor ah, [edi]
    inc edi
    inc ebx
    cmp al, ah
    jz  L6
L7: ja  L8
    mov eax, dword[edx+ebp*4]
    xchg eax, dword[edx+ecx*4-4]
    mov dword[edx+ebp*4], eax
L8: ;call debug
    test ebp, ebp
    pop ebx
    jnz L2
    loop L1
    popad
    ret

```

Test code:

```
if 1
    use32
else
    org $0100
    mov ecx, (Qn-Q0)/4
    mov edx, Q0
    mov ebx, S
    call F
    call debug
    ret

debug:pushad
    mov ecx, (Qn-Q0)/4
    mov edx, Q0
    mov ebx, S
E3:   mov esi, [edx]
    push dx
    mov ah, 2
E4:   lodsb
    cmp al, 0
    jz E5
    mov dl, al
    int $21
    jmp E4
E5:   mov dl, $0A
    int $21
    mov dl, $0D
    int $21
    pop dx
    add edx, 4
    loop E3
    ;mov ah, 1
    ;int $21
    int1
    popad
    ret
    align 128
Q0:
    dd str1, str2, str3, str4
Qn:
S     db '912', 0
str1  db 'abcde', 0
str2  db 'hello', 0
str3  db 'test', 0
str4  db 'honk', 0
    align 128
end if
    ;input ecx(length), edx(array), ebx(xor-d)
F:  pushad
L1: mov ebp, ecx
L2: dec ebp
    mov esi, [edx+ecx*4-4]
    mov edi, [edx+ebp*4]
    push ebx
L6: test [ebx], byte -1 ; t1b
    jnz L4
    pop ebx
    push ebx
L4: mov ah, [ebx]
    lodsb
    or  al, al
    jz  L7
    xor al, ah
    xor ah, [edi]
    inc edi
    inc ebx
    cmp al, ah
    jz  L6
L7: ja  L8
    mov eax, dword[edx+ebp*4]
    xchg eax, dword[edx+ecx*4-4]
    mov dword[edx+ebp*4], eax
L8: ;call debug
    test ebp, ebp
    pop ebx
    jnz L2
    loop L1
    popad
    ret

```
> 3 votes

# Answer
# JavaScript ES 6, ~~113~~ ~~97~~ 95 Bytes

```
k=>p=>p.sort((a,b,F=x=>[...x].map((y,i)=>1e9|y.charCodeAt()^(p=k+p).charCodeAt(i)))=>F(a)>F(b))

```

JavaScript is long at charcoding...

For \[0,65536) +1e4 all be 5 digits so can be compared like string

```
Q=
k=>p=>p.sort((a,b,F=x=>[...x].map((y,i)=>1e9|y.charCodeAt()^(p=k+p).charCodeAt(i)))=>F(a)>F(b))
;
console.log(Q("912")(["abcde", "hello", "test", "honk"]));
console.log(Q("taco")(["this", "is", "a", "taco", "test"]));
console.log(Q("thisisalongkey")(["who", "what", "when"]));
console.log(Q("3")(["who", "what", "when"]));
```
> 2 votes

# Answer
# Clean, ~~101~~ ~~100~~ 94 bytes

*-6 bytes thanks to Ourous!*

```
import StdEnv
? =toInt
s k=let%s=[b bitxor?a\\a<-s&b<-[?c\\_<-s,c<-k]];@a b= %b> %a in sortBy@

```

Try it online! Example usage: `s ['3'] [['who'], ['what'], ['when']]`.

### Ungolfed:

```
import StdEnv
sort key list =
   let
      f string = [(toInt a) bitxor (toInt b) \\ a<-string & b<-flatten(repeat key)]
      comp a b = f a <= f b
   in sortBy comp list

```
> 2 votes

# Answer
# Actually, 24 bytes

```
O╗⌠;O;l;╜@αH♀^♂cΣ@k⌡MS♂N

```

Try it online!

Explanation:

```
O╗⌠;O;l;╜@αH♀^♂cΣ@k⌡MS♂N
O╗                        store ordinals of key in register 0
  ⌠;O;l;╜@αH♀^♂cΣ@k⌡M     for each string in array:
   ;O                       make a copy, ordinals
     ;l;                    make a copy of ordinals, length, copy length
        ╜@αH                list from register 0, cycled to length of string
            ♀^              pairwise XOR
              ♂cΣ           convert from ordinals and concatenate
                 @k         swap and nest (output: [[a XOR key, a] for a in array])
                     S♂N  sort, take last element (original string)

```
> 1 votes

# Answer
# Python 2,  ~~204 140 134~~  126 bytes

*Thanks to @Mr. Xcoder for saving 64 bytes, thanks to @ovs for saving six bytes, and thanks to @Dennis for saving eight bytes!*

```
lambda k,l:[x(k,s)for s in sorted(x(k,s)for s in l)]
x=lambda k,s:''.join(chr(ord(v)^ord(k[i%len(k)]))for i,v in enumerate(s))

```

Try it online!
> 1 votes

# Answer
# Perl 6, 37 bytes

```
{@^b.sort(*.comb Z~^(|$^a.comb xx*))}

```

Try it online!

`$^a` and `@^b` are the key and array arguments to the function, respectively. `@^b.sort(...)` simply sorts the input array according to the predicate function it is given. That function takes a single argument, so `sort` will pass it each element in turn and treat the return value as a key for that element, sorting the list by the keys of the elements.

The sorting function is `*.comb Z~^ (|$^a.comb xx *)`. `*` is the single string argument to the function. `*.comb` is a list of the individual characters of the string. `|$^a.comb xx *` is a list of the characters in the xor sorting key, replicated infinitely. Those two lists are zipped together (`Z`) using the stringwise xor operator (`~^`). Since the sorting predicate returns a sort key which is a list, `sort` orders two elements by comparing the first elements of the returned lists, then the second elements if the first elements are the same, et cetera.
> 1 votes

# Answer
# C (gcc), ~~132~~ ~~128~~ 126 bytes

```
char*k;g(a,b,i,r)char**a,**b;{r=k[i%strlen(k)];(r^(i[*a]?:-1))-(r^(i[*b]?:-2))?:g(a,b,i+1);}f(c,v)int*v;{k=*v;qsort(v,c,8,g);}

```

Takes an argument count and a pointer to a string array (the key, followed by the strings to be sorted) and modifies the string array in-place.

The code is highly non-portable and requires 64-bit pointers, gcc, and glibc.

*Thanks to @ceilingcat for golfing off 2 bytes!*

Try it online!
> 1 votes

# Answer
# Perl 5, ~~80 + 3 (`anl`) = 83~~, 67 bytes

```
sub{$,=shift;sub X{$_^substr$,x y///c,0,y///c};map X,sort map X,@_}

```

try it online
> 0 votes

# Answer
# Perl 5, 88 bytes

```
sub{[map@$_[0],sort{@$a[1]cmp@$b[1]}map[$_,substr$_^($_[0]x length),0,length],@{$_[1]}]}

```

Try it online.
> 0 votes

# Answer
## Clojure, 80 bytes

```
#(sort-by(fn[s](apply str(apply map bit-xor(for[i[(cycle %)s]](map int i)))))%2)

```
> 0 votes

# Answer
# AWK, ~~285~~ 284 bytes

```
{for(;z++<128;){o[sprintf("%c",z)]=z}split(substr($0,0,index($0,FS)),k,"");$1="";split($0,w);for(q in w){split(w[q],l,"");d="";for(;i++<length(l);){d=d sprintf("%c",xor(o[k[(i-1)%(length(k)-1)+1]],o[l[i]]))}a[q]=d;i=0}asort(a,b);for(j in b){for(i in a){printf(a[i]==b[j])?w[i]FS:""}}}

```

Try it online!

Accepts input in the form of `key word word ...` eg `912 abcde hello test honk`

Outputs sorted words space separated

Slightly more readable

```
{
  for (; z++ < 128;) {
    o[sprintf("%c", z)] = z
  }
  split(substr($0, 0, index($0, FS)), k, "");
  $1 = "";
  split($0, w);
  for (q in w) {
    split(w[q], l, "");
    d = "";
    for (; i++ < length(l);) {
      d = d sprintf("%c", xor(o[k[(i - 1) % (length(k) - 1) + 1]], o[l[i]]))
    }
    a[q] = d;
    i = 0;
  }
  asort(a, b);
  for (j in b) {
    for (i in a) {
      printf(a[i] == b[j]) ? w[i] FS : ""
    }
  }
}

```
> 0 votes

# Answer
# Factor, 85

```
[ [ dup length rot <array> concat [ bitxor ] 2map ] with
[ dup bi* <=> ] curry sort ]

```

First try, I'll see if I can golf it further tomorrow.

I accept suggestions ;)
> 0 votes

# Answer
## **Dyalog APL, 34 bytes**

Dfn, uses ⎕ml 3

```
{⍵[⍋⊃82⎕dr¨⊃≠/11⎕dr¨¨⍵((⍴¨⍵)⍴⊂⍺)]}

```
> 0 votes

---
Tags: code-golf, string, array, sorting, bitwise
---