title: Make an interpreter for yes!

text:
# Question
Title: Make an interpreter for yes!
Yes is a stack-based ~~language~~ that has a few space-separated instructions:

```
yes: Push 1 to the stack
no: Push 0 to the stack
what: Push the input to the stack (input is taken at the start of program execution and is the same for the whole execution)
sure: Increment the last item in the stack
nah: Decrement the last item in the stack
really: If the last stack item is a number, replace it with its Unicode character. If it is a letter, replace it with its Unicode char code.
oh: convert the stack to strings and concatenate it, and push that to the stack.
nope: remove the first stack item
yep: remove the last stack item

```

The stack's last element is always outputted at program end. All non-alphanumeric and non-space characters are ignored. All code is lowercase. Example programs:

```
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
oh

```

prints `Hello, World!`.

```
what

```

prints the input (`cat` program.)

```
no nah

```

prints `-1`.

```
no really

```

prints the `NUL` character (`U+0000`)

```
what
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
oh

```

prints the input and an underscore.

```
yes no nope

```

prints `0`

```
yes no yep

```

prints `1`.

You must write an interpreter in as few bytes as possible. Here's a JS implementation (not well golfed!):

```
function yes(code, input){
 var stack = [];
 var functions = {
  "yes": "stack.push(1)",
  "no": "stack.push(0)",
  "what": "stack.push(input)",
  "sure": "stack[stack.length - 1] ++",
  "nah": "stack[stack.length - 1] --",
  "really": "stack[stack.length - 1] = (typeof lastItem === 'number' ? String.fromCharCode(lastItem) : lastItem.charCodeAt())",
  "oh": "stack.push(stack.reduce((x, y)=>''+x+y))",
  "nope": "stack.shift()",
  "yep": "stack.pop()"
 };
 code.replace(/[^a-z ]/g, "").split(" ").map(x=>(lastItem = stack[stack.length - 1],eval(functions[x])));
 return stack[stack.length - 1];
}
```

```
textarea{
  display: block;
}
```

```
Code: <textarea id = "code"></textarea>
Input: <textarea id = "input"></textarea>
<button onclick = "output.value = yes(code.value, input.value)">Run</button>
<textarea id = "output"></textarea>
```

See also my JS answer below.

You may assume that all integers involved will be less than or equal to 126, that `really` will never be run with a multi-char string on top of the stack, and that the stack will never be longer than 100 elements.

# Edge cases

* `yes yes oh` prints `11`.
* Intput may be a string or number.
* The code can contain any chars. Ones not matching `[a-z ]` should be ignored.

# Answer
# 05AB1E, ~~77~~ ~~67~~ ~~63~~ 61 bytes

```
Að«Ã#vyÇO§}ðý•9ǝ×н}ÀÀÙ™Íð•650в"X ¾ I > < DdiçëÇ} J r\r \"#:.V

```

Assumes the program is on the top of the stack.

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), ~~218~~ ~~215~~ ~~204~~ 203 bytes

Takes the program string `s` and the input `i` in currying syntax `(s)(i)`.

```
s=>i=>s.replace(/\w+/g,S=>(c=eval("[P()];P()+1;[s.shift()];1;0;s=[s.join``];P()-1;i;P()[0]?k.charCodeAt():String.fromCharCode(k)".split`;`[parseInt(S,35)%156%9])).map||s.push(c),s=[],P=_=>k=s.pop())&&P()

```

### How?

We use the perfect hash function `parseInt(S, 35) % 156 % 9` to convert the instruction ***S*** into an index in ***0…8*** and use this index to select the JS code to be executed:

```
instruction | base 35 -> dec. | % 156 | % 9 | JS code
------------+-----------------+-------+-----+---------------------------------------------
"yes"       |           42168 |    48 |   3 | 1
"no"        |             829 |    49 |   4 | 0
"what"      |         1393204 |   124 |   7 | i
"sure"      |         1238209 |    37 |   1 | P()+1
"nah"       |           28542 |   150 |   6 | P()-1
"really"    |      1439554619 |    35 |   8 | P()[0]?k.charCodeAt():String.fromCharCode(k)
"oh"        |             857 |    77 |   5 | s=[s.join``]
"nope"      |         1016414 |    74 |   2 | [s.shift()]
"yep"       |           42165 |    45 |   0 | [P()]

```

The ***P*** function pops the last item off the stack ***s*** and loads it into ***k***.

We prevent the result of some instructions from being pushed back onto the stack by testing if the *.map()* method is defined, that is, if the result is an array. The code for ***oh*** is returning an array by design and we force ***nope*** and ***yep*** to return arrays as well. Hence the syntax:

```
(c = eval("[code0];code1;...".split`;`[index])).map || s.push(c)

```

### Test cases

```
let f =

s=>i=>s.replace(/\w+/g,S=>(c=eval("[P()];P()+1;[s.shift()];1;0;s=[s.join``];P()-1;i;P()[0]?k.charCodeAt():String.fromCharCode(k)".split`;`[parseInt(S,35)%156%9])).map||s.push(c),s=[],P=_=>k=s.pop())&&P()

console.log(f(`yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
oh`)())

console.log(f(`what`)(1234))

console.log(JSON.stringify(f(`no really`)()))

console.log(f(`what
yes sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure sure really
oh`)('code golf'))

console.log(f(`yes no nope`)())

console.log(f(`yes no yep`)())
```
> 9 votes

# Answer
# Röda, 256 bytes

```
f c,n{s=[];(c/`\W|_`)()|{|m|s+=#m-2 if[m=~"yes|no"];s[-1]+=#m*2-7 if[m=~"sure|nah"];s+=n if[m="what"];s=s[#m%3:#s-#m%2]if[m=~"nope|yep"];{s+=""s()|s[-1].=_}if[m="oh"];{t=s[-1]y=t..""a=t+0;a=a..""{s[-1]=ord(s)}if[#a>#y]else{s[-1]=chr(t)}}if[#m=6]}_;[s[-1]]}

```

Try it online!

### Explanation

`#variable` returns the length of `variable` (if it is a string or an array).

```
f c,n{                         /*declare a function f with arguments c and n*/
s=[];                          /*initialise the stack*/
(c/`\W|_`)                     /*split the code on anything not [a-zA-Z0-9]*/
          ()|                  /*and push each of its values to the stream*/
{|m|...}_                      /*for each element m in the stream, do:*/
s+=#m-2 if[m=~"yes|no"];       /* add 1 or 0 to the stack if m is "yes" or "no"*/
s[-1]+=#m*2-7if[m=~"sure|nah"];/* increment or decrement the top element if m is "sure" or "nah"*/
s+=n if[m="what"];             /* push input if m is "what"*/
s=s[#m%3:#s-#m%2]              /* remove the first or last element of the stack
  if[m=~"nope|yep"];           /* if m is "nope" or "yep" */
{                 }if[m="oh"]; /* if m is "oh" do:*/
 s+=""                         /*  add an element to the stack*/
      s()|s[-1].=_             /*  for each element in s, concatenate that amount to the last element of the stack*/
{                   }if[#m=6]  /* if m is "really" (it's length is 6) do:*/
 t=s[-1]y=t..""                /*  get the last element of the stack*/
 a=t+0;a=a..""                 /*  add 0 to it, if a is a number, this does nothing, otherwise this makes a longer by 1 character*/
 {s[-1]=ord(s)}if[#a>#y]       /*  if a is longer than t (the last element is a char/string) replace it with its code point*/
 else{s[-1]=chr(t)}            /*  otherwise, replace the last element with the char it represents*/
 [s[-1]]                       /*finally output the top of the stack*/

```
> 4 votes

# Answer
# Pyth, 69 bytes

```
Vczd=Y.v@c"+YsY X_1Y1 +Yw  +Y0 X_1Y_1    PY   +Y1 tY +PYCeY"d%CN23;eY

```

Try it online!
> 2 votes

# Answer
# JS (ES6), ~~361~~ 340 bytes

```
c=>i=>(s=[],r="s[s.length-1]",c.replace(/[^a-z ]/g,"").split` `.map(x=>(eval({"yes":"s.push(1)","no":"s.push(0)","what":"s.push(i)","sure":"~++","nah":"~--","really":"~=((typeof ~)[0]<'o'?String.fromCharCode(~):lastItem.charCodeAt())","oh":"s.push(s.reduce((x,y)=>''+x+y))","nope":"s.shift()","yep":"s.pop()"}[x].replace(/~/g,r)))),eval(r))

```

Takes code and input through currying.

```
var yes =
c=>i=>(s=[],r="s[s.length-1]",c.replace(/[^a-z ]/g,"").split` `.map(x=>(eval({"yes":"s.push(1)","no":"s.push(0)","what":"s.push(i)","sure":"~++","nah":"~--","really":"~=((typeof ~)[0]<'o'?String.fromCharCode(~):lastItem.charCodeAt())","oh":"s.push(s.reduce((x,y)=>''+x+y))","nope":"s.shift()","yep":"s.pop()"}[x].replace(/~/g,r)))),eval(r))
```

```
textarea{
  display: block;
}
```

```
Code: <textarea id = "code"></textarea>
Input: <textarea id = "input"></textarea>
<button onclick = "output.value = yes(code.value)(input.value)">Run</button>
<textarea id = "output"></textarea>
```
> 1 votes

# Answer
## JavaScript (ES6), ~~220~~ 216 bytes

```
c=>i=>c.replace(/\w+/g,x=>a=a.concat(eval("Q,[]  (b=Q)[0]?b.charCodeAt():String.fromCharCode(b) 1    [a.join``,a=[]][0] Q+1 a.shift(),[]  i  Q-1".split`Q`.join`a.pop()`.split` `[parseInt(x,36)%19]||0)),a=[])&&a.pop()

```

A function that takes input with currying syntax, like `f(code)(input)`.
> 0 votes

# Answer
# Python 2, 258 bytes

```
s=[]
m=-1
i,p=input()
for c in p.split(' '):
 k=c<"o"
 if c in"yesnowhat":s+=[i if"w"==c[0]else-k+1]
 if c in"surenah":s[m]+=[1,m][k]
 if"p"in c:s.pop(k-1)
 if"oh"==c:s+=[''.join(map(str,s))]
 if"y"==c[m]:s[m]="'"in`s[m]`and ord(s[m])or chr(s[m])
print(s[m])

```

Try it online!

---

-3 bytes thanks to @Wondercricket
> 0 votes

# Answer
# Perl 6,  ~~233~~  225 bytes

```
{my @s;{yes=>{@s.push(1)},no=>{@s.push(0)},what=>{@s.push: once slurp},sure=>{++@s.tail},nah=>{--@s.tail},really=>{($/:=@s.tail)~~Int??$/.=chr!!$/.=ord},oh=>{@s.=join},nope=>{@s.shift},yep=>{@s.pop},}{.words}.map:{.()};@s.tail.print}

```

Try it
Hello World
cat
-1
nul
cat\_

```
{my @s;{es=>{@s.push(1)},no=>{@s.push(0)},at=>{@s.push: once slurp},re=>{++@s.tail},ah=>{--@s.tail},ly=>->{($_:=@s.tail)~~Int??.=chr!!.=ord},oh=>{@s.=join},pe=>{@s.shift},ep=>{@s.pop},}{.comb(/..»/)}.map:{.()};@s.tail.print}

```

Works the same except it only grabs the last two characters from each command, and uses `$_` instead of `$/` for `really`.

Try it (Hello World)

## Expanded:

```
{
  my @s; # stack

  {  # Associative array
    yes    => {@s.push(1)},
    no     => {@s.push(0)},
    what   => {@s.push: once slurp}, # read everything from $*IN
    sure   => {++@s.tail},
    nah    => {--@s.tail},
    really => {
          ( $/ := @s.tail ) # bind $/ to the last value in the stack
          ~~ Int            # if that is an Int
      ??  $/.=chr           # replace it with that character
      !!  $/.=ord           # otherwise replace it with its ordinal
    },
    oh     => {@s.=join},
    nope   => {@s.shift},
    yep    => {@s.pop},
  }\
  { .words }                # index by the words in the program
  .map: {.()};              # call each of the lambdas in order

  @s.tail.print             # print the last value on the stack
}

```
> 0 votes

# Answer
# PHP, ~~315~~ 305 bytes

second draft, not tested yet

```
foreach($argv as$k=>$v)if($k>1)eval((strstr($c=preg_replace('#[^a-z ]#','',$v),p)?'':'$s[]=').[yes=>1,no=>0,what=>'$argv[1]',sure=>'array_pop($s)+1',nah:'array_pop($s)-1',really=>'is_int($x=array_pop($s))?chr($x):ord($x)',oh=>'join($s)',nope=>'array_shift($s)',yep=>'array_pop($s)'][$c].';');echo end($s);

```

Run with `php -nr '<php-code>' <input> <yes-code>`.

**breakdown**

```
foreach($argv as$k=>$v)if($k>1)         # loop through commands
    eval(                                   # 3. interprete
        (strstr(                            # 2. if no 'p' in command, prepend '$s[]='
                                            # 1. ignore all non-code characters
            $c=preg_replace('#[^a-z ]#','',$v),p)?'':'$s[]=').
        [yes=>1,                                # yes: append 1
        no=>0,                                  # no: append 0
        what=>'$argv[1]',                       # what: append input
        sure=>'array_pop($s)+1',                # sure: remove end, increment, append
        nah:'array_pop($s)-1',                  # nah: remove end, decrement, append
                                                # really: convert between ascii and ordinal
        really=>'is_int($x=array_pop($s))?chr($x):ord($x)',
        oh=>'join($s)',                         # oh: concatenate elements, append
        nope=>'array_shift($s)',                # nope: remove first element
        yep=>'array_pop($s)']                   # yep: remove last element
        [$c]
    .';');
echo end($s);                           # print last element (if exists)

```
> 0 votes

# Answer
# PowerShell, 286 bytes

```
$s=@()
$k-split"\s"|%{
switch($_){
"yes"{$s+=1}
"no"{$s+=0}
"what"{$s+=(read-host)}
"sure"{$s[-1]+=1}
"nah"{$s[-1]-=1}
"really"{if($s[-1]-is[int]){[char]($s[-1])}else{[int][char]($s[-1])}}
"oh"{$s+=($s-join'')}
"nope"{$s=($s[1..($s.Length-1)])}
"yep"{$s=($s[0..($s.Length-2)])}}}
$s[-1]

```

Try it online!

The input is defined as `$k` in header of TIO.

An empty array `$s` initialized.

Splits the input on whitespace using a regex.

Then for each switch it does

```
yes: Push 1 to the stack (read stack as array and push as append, += operator used, which adds an item at the end of arrays (here))
no: Push 0 to the stack
what: Push the input to the stack
sure: Increment the last item in the stack (indexing and += used)
nah: Decrement the last item in the stack
really: If the last stack item is a number, replace it with its Unicode character. If it is a letter, replace it with its Unicode char code. (used [char] and [int][char] type casting)
oh: convert the stack to strings and concatenate it, and push that to the stack. (Just join the array with '')
nope: remove the first stack item (Using indexing)
yep: remove the last stack item (Using indexing)

```

At last output last item in array.
> 0 votes

---
Tags: code-golf, interpreter, stack
---


title: Fill the screen in 6502asm.com

text:
# Question
Title: Fill the screen in 6502asm.com
# Introduction

I've always liked the idea of finding the most possible bang-for-your-buck squeezed out of a tiny chip, like the 6502. Of course, I'll need to start small. Filling the screen on 6502asm.com should be easy enough.

# Challenge

Fill the entire program output screen on 6502asm.com with the color white using the least amount of unique executed bytes as possible. Or, set every memory space between 0x0200 and 0x05FF with any byte whose lower nybble is 1.

No self modifying code. (executing bytes that were changed after being assembled)
Try to keep the memory changed to a minimum, don't go changing bytes willy-nilly.

# Answer
Here's my attempt:

```
lda #1
ldx #$02

fill_screen:
stx $01

draw_segment:
sta ($00),Y
iny
bne draw_segment

inx
cpx #$06
bne fill_screen

```

And as hex:

```
0600: a901 a202 8601 9100 c8d0 fbe8 e006 d0f4

```

That's exactly 16 bytes of memory used as code, with 2 external bytes used as program storage.
> 1 votes

---
Tags: graphical-output, assembly
---


# Question
Title: Reconstruct an integer from its prime exponents
All integers \\$n \> 0\\$ can be expressed in the form

$$n = \prod\_{\text{prime } p} p^e = 2^{e\_2} 3^{e\_3} 5^{e\_5} 7^{e\_7} \cdots$$

This form is also known as it's prime factorisation or prime decomposition, and each integer has a unique prime factorisation.

As the bases are fixed, it is possible to reconstruct an integer when just given a list of the exponents of it's prime factorisation. For example, given \\$E = \[0,3,2,1,0,2\]\\$ we can reconstruct \\$n\\$ as

$$ \begin{align} n & = 2^0 3^3 5^2 7^1 11^0 13^2 \\ & = 1 \cdot 27 \cdot 25 \cdot 7 \cdot 1 \cdot 169 \\ & = 798525 \end{align} $$

Therefore, \\$\[0,3,2,1,0,2\] \to 798525\\$, and is the only such list (ignoring trailing zeros) that does so.

You are to take an input consisting of non-negative integers representing the exponents of the prime factorisation of some integer and output the integer with that prime factorisation.

Both the integer and the elements of the input will be within the bounds of your language, and you can take input in any convenient method. You may have an arbitrary (from 0 to infinite) number of trailing zeros in the input. The array will never be empty, but may be `[0]`

This is so the shortest code in bytes wins

## Test cases

```
[0] -> 1
[1] -> 2
[3, 2] -> 72
[0, 1, 2] -> 75
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] -> 347
[6, 2] -> 576
[1, 7] -> 4374
[5, 7] -> 69984
[10, 5] -> 248832
[1, 0, 0, 8, 4] -> 168804902882
[3, 8, 10] -> 512578125000
[7, 9, 0, 8] -> 14523977994624
[4, 4, 7, 0, 0, 5, 5] -> 53377275216476250000
[1, 8, 1, 7, 8, 1] -> 150570936449966222190
[10, 0, 2, 8, 9] -> 347983339699826969600
[4, 8, 2, 3, 7, 9] -> 186021488852335961308083600
[7, 6, 6, 8, 6, 8, 4] -> 1014472920935186644572261278658000000
[9, 6, 7, 5, 1, 8, 10] -> 8865565384329431006794755470280000000

```

# Answer
> 12 votes
# Python 2, 61 bytes

Wilson's theroem FTW!

```
f=lambda p,a=1,b=1:p==[]or b**(a%b*p[0])*f(p[a%b:],a*b*b,b+1)

```

Try it online!

### Python 2, 62 bytes

```
f=lambda p,a=1,b=1:p==[]or(a%b<1or b**p.pop(0))*f(p,a*b*b,b+1)

```

Try it online!

# Answer
> 10 votes
# , 13 7 bytes

```
_&q:inv

```

Try it online!

As described here, the verb `_ q: n` returns the prime exponents of `n`. So the inverse `inv` of that verb is exactly what we want.

# Answer
> 8 votes
# Jelly, 2 bytes

```
ÆẸ

```

Try it online!

Just the builtin.

# Jelly, 6 bytes

```
JÆN*µP

```

Try it online!

If those brownie points are attainable, it's going to be hard!

```
 ÆN       n-th prime
J         for each n in 1 .. len(input).
   *      Raise each prime to the corresponding exponent,
    µ     then
     P    output the product.

```

# Answer
> 8 votes
# Wolfram Language (Mathematica), 28 bytes

```
1##&@@(i=0;Prime@++i^#&/@#)&

```

Try it online!

# Answer
> 6 votes
# Vyxal `r`, 4 bytes

```
ẏǎeΠ

```

Try it Online!

```
ẏǎeΠ
ẏ     # range(0, len(input))
 ǎ    # nth_prime(^) // vectorises
  e   # ^ ** input // vectorises element-wise
   Π  # product(^)

```

The `r` flag tells Vyxal to pass arguments to built-ins in reverse order. It's been around before this challenge, so I didn't add it to cheat this one time. Without it, this would be 5 bytes (`ẏǎ$eΠ`)

# Answer
> 6 votes
# Factor \+ `math.primes`, 43 bytes

```
[| x | 1 x length nprimes x [ ^ * ] 2each ]

```

-3 from Leo

Try it online!

# Answer
> 6 votes
# Factor \+ `math.primes math.unicode`, ~~38~~ 33 bytes

```
[ dup length nprimes swap v^ Π ]

```

Try it online! Explanation:

* `dup` duplicate the input (e.g.) `{ 0 1 2 3 } { 0 1 2 3 }`
* `length` find the length of a sequence `{ 0 1 2 3 } 4`
* `nprimes` generate primes given the number on top of the data stack `{ 0 1 2 3 } { 2 3 5 7 }`
* `swap` swap the top two objects on the data stack `{ 2 3 5 7 } { 0 1 2 3 }`
* `v^` vector exponentiation (component-wise) `{ 1 3 25 343 }`
* `Π` find the product of a sequence `25725`

# Factor \+ `math.primes math.unicode`, ~~38~~ 33 bytes

```
[ [ length nprimes ] keep v^ Π ]

```

An equivalent answer using the data flow combinator `keep` instead of stack shufflers. Data flow combinators generally keep the data stack more static and easier to reason about than stack shufflers.

Try it online!

# Answer
> 5 votes
# Husk, 6 bytes

```
Πz`^İp

```

Try it online!

## Explanation

```
Πz`^İp implicit input
 z     zip the input
    İp with the infinite list of primes, removing extras
   ^   using the power function,
  `    with flipped arguments.
Π      take its product.

```

# Answer
> 5 votes
# , ~~83~~ ~~82~~ ~~79~~ ~~78~~ 68 bytes

*Edit: -4 bytes thanks to Kirill L. and -1 byte thanks to Robin Ryder.*

```
function(l,p=1){for(i in l){while(sum(!(T=T+1)%%2:T)-1)1;p=p*T^i};p}

```

Try it online!

Loops over the list `l` of prime exponents, each time using `while(sum(!(T=T+1)%%2:T)-1)1` to update `T` to the next prime, and multiplying the cumulative product `p` (initialized to 1) by `T` to the power of the current exponent. Finally, returns `p`.

# Answer
> 4 votes
# JavaScript, ~~91~~ ~~86~~ 84 bytes

```
a=>{p=[],r=1;for(i=2;0 in a;i++)r*=p.every(x=>i%x)?i**a.shift(p.push(i)):1;return r}

```

Try it online!

*Saved 2 bytes thanks to Neil*

## Explanation

```
a=>{
  p=[],//array of primes
  r=1;//product/result
  for(i=2;
     0 in a;
    //if 0 exists as a key in the array, then the first element exists
    //and it is not empty
    i++)
    r*=
       p.every(x=>i%x)?
      //check if there is a remainder after division with each previous prime
      //if so, then i is prime
         i**a.shift(
            p.push(i)//add to prime array, (shift ignores all arguments)
         )
         //multiply result by i to the power of the first
         //input array element (and remove it)
    :1; //multiply by 1 if i is not prime
    return r
}

```

# Answer
> 4 votes
# Brachylog, 13 bytes

```
wᵐ<₁ṗᵐ≜;?z^ᵐ×

```

Try it online!

Function submission which dumps some garbage to STDOUT since it saves a byte over `l~l<₁ṗᵐ≜;?z^ᵐ×` or `∧ċ<₁ṗᵐ;?z₂≜^ᵐ×`.

```
wᵐ               Create a list of unbound variables with the same length as the input.
                 (This also prints each element, but that's besides the point.)
  <₁             This list is strictly increasing,
    ṗᵐ           and each of its elements is prime.
      ≜          Assign a value to each element.
       ;?z^ᵐ     Raise each prime to the power of the corresponding element of the input,
            ×    and output the product of the powers.

```

Without the , it completely breaks given exponents of zero--I suppose because they are mathematically eliminated from the final product?

# Answer
> 4 votes
# Japt, 11 bytes

```
í!pÈj}jUl¹×

```

Try it

# Answer
> 4 votes
# C (gcc), ~~110~~ \\$\cdots\\$ ~~79~~ 75 bytes

Saved ~~5~~ 9 bytes thanks to xibu!!!

```
d;p;r;f(a,l)int*a;{for(r=p=1;l;r*=pow(p,d<2?l--,*a++:0))for(d=++p;p%--d;);}

```

Try it online!

Inputs an array of prime exponents and its length \\$l\\$ (because C arrays have undefined length) and returns the product of the first \\$l\\$ primes to those exponents.

### Explanation (before some golfs)

```
d;p;r;f(a,l)int*a;{                           // function taking an array of
                                              // ints and its length l
  for(r=p=1;l--;                              // loop over the array elements
                                              // setting the product r and
                                              // the previous prime to 1
                r*=pow(p,*a++)                // once we've found the next
                                              // prime multiply r by it
                                              // to the power of the current
                                              // value in a
    for(d=2;d>1;)                             // loop until we find the next
                                              // prime, d==1 will flag this
      for(d=++p;                              // set d to p bumped
                p%--d;)                       // bump d down and loop
                                              // until we find the highest
                                              // divisor of p
  d=r;                                        // return r
}                                             //

```

# Answer
> 4 votes
# Haskell, ~~83 69~~ 57 bytes

Thanks to thanks to @AZTECCO and @Unrelated String for bringing it down to 57 bytes :)

```
f=product.zipWith(^)(s[2..])
s(x:t)=x:s[y|y<-t,y`mod`x>0]

```

Try it Online!

**Edit:** Realised that newlines are also one byte so putting multiple lines on a single line with semicolons doesn't change the size.

**Edit #2:** Realised that I don't need to `take (length x)` to my list of primes, zipWith only takes how many it needs to.

**Edit #3:** Reduced to 57 bytes, thanks to thanks to @AZTECCO and @Unrelated String (See Comments)

## Explanation:

(My solution wasn't very difficult to understand but I'm a beginner with Haskell so writing this out helps me xD)

A more readable version would be:

```
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x > 0]
primes = sieve [2..]
applyExponents x = zipWith (^) primes x
reconstruct = product . applyExponents

```

Recursive function used to generate a list of primes---use list comprehension to remove multiples of the last prime inserted into the list.

```
sieve (x:xs) = x:sieve [y | y<-xs, y `mod` x > 0]

```

Apply recursive sieve function to an infinite list of natural numbers from 2 onwards to get an infinite list of primes.

```
primes = sieve [2..]

```

~~Use `take (length x)` to evaluate the list of primes and get the right number of prime numbers for the length of list x.~~ Use zipWith to apply the correct exponent to each prime number.

```
applyExponents x = zipWith (^) p x

```

Then use `product` to multiply the list resulting from the previous step together.

```
reconstruct = product . applyExponents

```

# Answer
> 3 votes
# PowerShell, 106 bytes

```
$s=1;while($n-lt$a.length){if(('1'*(++$i))-notmatch'^1?$|^(11+?)\1+$'){$s*=[math]::pow($i,$a[($n++)])}};$s

```

Try it online!

Uses a regex to match prime numbers, more about it here

# Answer
> 3 votes
# Haskell, ~~61~~ 56 bytes

```
f=product.zipWith(^)[x|x<-[2..],all((>0).rem x)[2..x-1]]

```

Try it online!

* saved 5 by stealing @Unrelated String advice to @M. Salman Khan answer.

# Answer
> 3 votes
# APL (Dyalog Extended), ~~12~~ 11 bytes

-1 thanks to Adám

```
⊢×.*⍨¯2⍭⍳∘≢

```

```
⊢×.*⍨¯2⍭⍳∘≢
     ¯2⍭⍳∘≢  ⍝ the first n primes
⊢×.*⍨        ⍝ powers and product

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES7),  ~~64~~  58 bytes

```
a=>(g=d=>a+a?n%--d?g(d):(d>1||n**a.shift())*g(++n):1)(n=2)

```

Try it online!

## With BigInts, 61 bytes

A version that supports large integers. Expects a list of BigInts.

```
a=>(g=d=>a+a?n%--d?g(d):(d<2?d:n**a.shift())*g(++n):1n)(n=2n)

```

Try it online!

### Commented

```
a => (                 // a[] = input array
  g = d =>             // g is a recursive function taking a divisor d
  a + a ?              // if a[] is not empty:
    n % --d ?          //   decrement d; if it's not a divisor of n:
      g(d)             //     do recursive calls until it is
    :                  //   else:
      (                //     multiply the final result by:
        d > 1 ||       //     - 1 if d is greater than 1 (n is composite)
        n ** a.shift() //     - the prime n raised to the power of the next
      )                //       exponent extracted from a[] otherwise
      * g(++n)         //     and multiply by the result of a recursive call
                       //     with n + 1
  :                    // else:
    1                  //   stop the recursion and return 1
)(n = 2)               // initial call to g with d = n = 2

```

# Answer
> 3 votes
# 05AB1E, ~~6~~ 2 bytes

Try it online!

```
.Ó  # full program
.Ó  # push the number with a prime factorization with exponents in...
    # implicit input
    # implicit output

```

# Answer
> 3 votes
# Raku, 31 bytes

```
{[*] grep(&is-prime,^∞)Z**$_}

```

Try it online!

`grep(&is-prime, ^∞)` is an infinite, lazy sequence of primes. `Z**` zips that sequence with `$_`, the list argument to the function, using exponentiation. Then `[*]` computes the product of that sequence.

# Answer
> 2 votes
# Charcoal, 29 bytes

```
≔¹ζＦＡ«≦⊕ζＷ﹪⊕Π…¹ζζ≦⊕ζ⊞υＸζι»ＩΠυ

```

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

```
≔¹ζ

```

Start finding prime numbers.

```
ＦＡ«

```

Loop over the input list.

```
≦⊕ζＷ﹪⊕Π…¹ζζ≦⊕ζ

```

Increment the integer it until it's prime via Wilson's theorem.

```
⊞υＸζι

```

Take the appropriate prime power.

```
»ＩΠυ

```

Print the product of the resulting prime powers.

# Answer
> 2 votes
# 05AB1E, 6 bytes

```
ā<ØsmP

```

Try it online!

In other words:

```
P         sm        Ø                 ā                   <
product(exponate(nth_prime_number(range(1, len(input())) - 1), input()))

```

# Answer
> 2 votes
# Japt, 11 bytes

```
£Èj}iY pXÃ×
£           // Map the input array with X as items and Y as indexes to
 È }iY      // Y-th positive number
  j         // that is prime
       pX   // to the power of X,
         Ã× // then reduce with multiplication.

```

Try it out here.

# Answer
> 2 votes
# R+primes, ~~46~~ 43 bytes

Exploiting the primes library

```
prod(primes::nth_prime(seq(a=l<-scan()))^l)

```

Don't try it online! (as primes is not recognised by tio.run, apparently) Here is the output on rrdr.io:

```
prod(primes::nth_prime(seq(a=l<-scan()))^l)
0 0 0 0 1
Read 5 items
[1] 11

prod(primes::nth_prime(seq(a=l<-scan()))^l)
2 3 1 0 0 1
Read 6 items
[1] 7020

prod(primes::nth_prime(seq(a=l<-scan()))^l)
9 0 0 1 0 0 2
Read 7 items
[1] 1035776

```

# Answer
> 2 votes
# Ruby `-rprime`, ~~54~~ 37 bytes

A whopping 17 bytes off by Sisyphus.

```
->x{c=1;x.zip(Prime){|a,b|c*=b**a};c}

```

Try it online!

# Answer
> 2 votes
# Retina, 83 bytes

```
$
,__
m)+`,(_+)$(?<=\1¶.+)|,(__+)\2+$
$&_
~["L$`^¶$.("|""]'_L$`(.+),(_+)
$1*$($.2$*

```

Try it online! Takes a newline-separated list. Explanation:

```
$
,__

```

Pair each element of the input array with 2 in unary.

```
+`,(_+)$(?<=\1¶.+)|,(__+)\2+$
$&_

```

Increment each unary part until it is a prime greater than the previous one.

```
m)`

```

Turn on per-line `$` for all of the stages up to and including the above.

```
["L$`^¶$.("|""]'_L$`(.+),(_+)
$1*$($.2$*

```

Transform each pair into a repeated multiplication, so that for example `3,__` becomes three copies of `2*` i.e. `2*2*2*` while `2,___` becomes two copies of `3*` i.e. `3*3*`. Append a `_` to handle the case of zero input, and prepend `L$`^` and `$.(` to create a Retina program that replaces the current value with the total product.

```
~`

```

Evaluate that Retina program. For example, in the case of an input of `3` `2`, the resulting program is as follows:

```
L$`^
$.(2*2*2*3*3*_

```

`3*_` is `$(___)` and so on, with `$.(` taking the final length in decimal (Retina actually optimises this and simply multiplies the values together).

# Answer
> 1 votes
# Wolfram Language (Mathematica), 29 bytes

```
(i=s=1;s*=Prime@i++^#&/@#;s)&

```

Try it online!

One character longer than @att's solution but maybe it has potential for golfing down.

---
Tags: code-golf, math, number-theory, primes
---


# Question
Title: Output the smallest powers of 2 with two identical sub-strings of digits n long
For each integer *n*, 0 or higher, output the lowest power of 2 that has two identical sub-strings of *n* digits in decimal, and the two indices where the digit sub-strings start (0-based).

> **n Output Proof (don't output this)**
> 0 =\> 0 \[0 1\] (**_**1 & 1**_**)
> 1 =\> 16 \[0 4\] (**6**5536 & 6553**6**)
> 1 =\> 16 \[1 2\] (6**5**536 & 65**5**36)
> 2 =\> 24 \[0 6\] (**16**777216 & 167772**16**)
> 2 =\> 24 \[2 3\] (16**77**7216 & 167**77**216)

The possible outputs for the first three inputs are given above. When there is more than one output for a given input, either is acceptable. Only the digit positions will be different. Just output the numbers, the brackets are for clarity only. You don't need to output *n*.

Output a list of as many as you can find in one minute, or your code runs out of resources, whichever comes first. Please include the output with your answer. If the list is huge, just restrict it to the first and last 5. Your code must be able to find up to *n* = 9 in under a minute. I've written a Perl program that finds *n* = 9 after about 20 seconds, so this should be easy to do.

Your code doesn't need to halt itself. It is acceptable if you manually break out if it after a minute.

This is , so lowest number of bytes wins!

# Answer
> 5 votes
# APL (Dyalog Extended), 68 bytes

```
'01'(0{x≢`∪x←⍺⍺,/⍺:⍺((⍺⍺+1)∇∇)⊃⎕←⍵,⊃a/⍨</¨⊢a←⍸∘.≡⍨x⋄(+⌂big⍨⍺)∇1+⍵})0

```

Try it online!

APL is not known for big integer arithmetic, infinite output, or interpreter speed (and using Extended incurs even more overhead), yet it outputs successfully up to `n=9` barely under a minute.

### How it works

The code is basically an infinitely running recursive operator. The left argument is the string representation of the power of 2, the right argument is the corresponding exponent (which was needed to meet the speed requirement), and the left operand is the current value of `n`.

```
{
  x←⍺⍺,/⍺          ⍝ Extract length-n segments of given number
  x≢`∪x:           ⍝ If it has duplicates...
  a←⍸∘.≡⍨x         ⍝   Construct the pairs of indices of equal slices
  ⊃a/⍨</¨⊢a        ⍝   Keep the ones (L,R) where L<R and take the first one
  ⊃⎕←⍵,...         ⍝   Concat with the exponent, print it, extract ⍵ back
  ⍺((⍺⍺+1)∇∇)...   ⍝   Continue running with n+1
  ⋄                ⍝ Otherwise...
  (+⌂big⍨⍺)∇1+⍵    ⍝   Recurse with next power of two, using same n implicitly
}
'01'(0{...})0  ⍝ Invoke the dop with starting values

```

# Answer
> 4 votes
# Mathematica, 109 bytes

```
f@n_:={NestWhile[#+1&,0,Length[p=Position[#,#&@@Commonest@#,1,2]-1]&@Partition[IntegerDigits[2^#],n,1]<2&],p}

```

---

```
n    output
0    {0, {{0},{1}}}
1    {16, {{0},{4}}}
2    {24, {{0},{6}}}
3    {41, {{8},{9}}}
4    {73, {{10},{18}}}
5    {130, {{14},{17}}}
6    {371, {{8},{52}}}
7    {875, {{68},{101}}}
8    {2137, {{12},{240}}}
9    {2900, {{270},{355}}}
10   {7090, {{803},{1123}}}
11   {12840, {{1672},{3185}}}

```

# Answer
> 3 votes
# Python2, ~~137~~ 119 bytes

It's pretty straightforward:

```
i=m=0
while 1:
 n=`2**i`
 for k in range(len(n)-m+1):
    q=n.find(n[k:k+m],k+1)
    if-1<q:print i,k,q;m+=1;break
 else:i+=1

```

and the output:

```
n   output
0   0 0 1
1   16 0 4
2   24 0 6
3   41 8 9
4   73 10 18
5   130 14 17
6   371 8 52
7   875 68 101
8   2137 12 240
9   2900 270 355
10  7090 803 1123

```

18 bytes saved by btwlf

# Answer
> 2 votes
# Perl - 99 bytes

```
use bigint;%_=$_+=$_//1;$%+=($s=$_{$1}//=pos)<pos&&print"$- $s $-[0]
"while/(?=(.{$%}))/g;$-++;do$0

```

Trading bytes for efficiency. *n = 9* finishes in about 25s, around 15x slower than the version below.

---

### Perl - 120 bytes

```
use bigint;for$i(0..2e4){$_==($s=$_{$_[$_]}//=$_)or($%+=print"$i $s $_
"),last for 0..(@_=/(?=(.{$%}))/g);%_=$_+=$_//=1}

```

The regex `/(?=(.{$%}))/g` returns all substrings of the current value of length `$%`. The list is iterated, and if a value is seen twice, it is reported.

---

**Output**

```
0 0 1
16 1 2
24 2 3
41 8 9
73 10 18
130 14 17
371 8 52
875 68 101
2137 12 240
2900 270 355
7090 803 1123
12840 1672 3185

```

Output for *n = 10* at about 9s, for *n = 11* at 30s.

# Answer
> 1 votes
# PowerShell, ~~168~~ ~~158~~ ~~139~~ 135 bytes

slow

```
param($l)for(--$p;!"$j"){if(!$d){$m=@{};$i=-1
$n='1'*!$l+[bigint]::Pow(2,++$p)}$d=''+$n[++$i..($i+$l-1)]
$j=$m.$d;$m.$d=$i}"$p [$j $i]"

```

Try it online!

Less golfed:

```
param($l)
for(--$p;!"$j"){
    if(!$d){
        $m=@{}
        $i=-1
        $n='1'*!$l+[bigint]::Pow(2,++$p) # if($l -eq 0){'11'}else{'[bigint]'}
    }
    $d=''+$n[++$i..($i+$l-1)]
    $j=$m.$d
    $m.$d=$i
}
"$p [$j $i]"

```

output from my notebook:

```
Elapsed          N     output
-------          ----- ------------------------------
00:00:00.0659394 0 =>  0 [0 1]
00:00:00.0227806 1 =>  16 [1 2]
00:00:00.1038194 2 =>  24 [2 3]
00:00:00.3169680 3 =>  41 [8 9]
00:00:01.0266805 4 =>  73 [10 18]
00:00:03.3426611 5 =>  130 [14 17]
00:00:34.3156609 6 =>  371 [8 52]
00:04:23.3928567 7 =>  875 [68 101]

```

---

# PowerShell, ~~187~~ 194 bytes

Add some bytes to remove redundant iterations. Thanks @CJ Dennis

```
param($l)for($p=0;!($a=0..($l-1)-ge0|%{[bigint]::Pow(2,$p)-replace"^.{$_}",('-'*$_)}|sls('\d'*$l+'\b'*!$l)-a|% m*|group|? c* -ge 2|%{$i,$j=($_|% Gr*|% I*)[0,1]
,"$p [$i $j]"*($i-ne$j)})){++$p}$a

```

Try it online!

Less golfed and slightly faster code:

```
param($l)

$regexp = '\d'*$l+'\b'*!$l  # digits or boundary
$range = 0..($l-1) -ge 0
$power = 0

do{
    $n = [bigint]::Pow(2,$power)

    $s = $range|%{$n-replace"^.{$_}",('-'*$_)}
    $m = $s|Select-string $regexp -AllMatches|% Matches

    # $s contains strings in which a regexp captures all substrings of $l digits
    # $m contains the captured matches
    # example with $l=3 and $p=43:
    #
    # $s               matches after $regexp
    # =============    =====================
    # 2199023255552 -> 219 902 325 555
    # -199023255552 -> 199 023 255 552
    # --99023255552 -> 990 232 555

    $a = $m|Group|? Count -ge 2|%{
        $i,$j = $_|% Group|% Index|Select -First 2
        if($i -ne $j){
            "$power [$i $j]"
        }
    }

    ++$power
}
until($a)

write-output $a

```

Try it online!

The output on my notebook:

```
Elapsed          N     output
-------          ----- --------------------
00:00:00.1183433 0 =>  0 [0 1]
00:00:00.0135382 1 =>  16 [1 2]
00:00:00.0135382 1 =>  16 [0 4]
00:00:00.0224871 2 =>  24 [0 6]
00:00:00.0224871 2 =>  24 [2 3]
00:00:00.0353316 3 =>  41 [9 8]
00:00:00.0649162 4 =>  73 [10 18]
00:00:00.1572769 5 =>  130 [17 14]
00:00:00.7403980 6 =>  371 [8 52]
00:00:02.6019309 7 =>  875 [101 68]
00:00:15.8726659 8 =>  2137 [240 12]
00:00:30.0988879 9 =>  2900 [270 355]
00:03:20.7172180 10 => 7090 [803 1123]

```

# Answer
> 0 votes
# JavaScript (ES6), 111 bytes

```
n=>(C=i=>(I=S.indexOf(S.slice(i,i+n)))==i?S[i+n]?C(i+1):-1:i,P=p=>(z=C(0,S=(2n**p+'')))<0?P(++p):p,[P(0n),I,z])

```

It calculates the first 9 fairly quickly, but then reaches the maximum call stack size for `n=10`;

```
[0n, 0, 1]
[16n, 0, 4]
[24n, 0, 6]
[41n, 8, 9]
[73n, 10, 18]
[130n, 14, 17]
[371n, 8, 52]
[875n, 68, 101]
[2137n, 12, 240]
[2900n, 270, 355]

```

Here's how it works:

```
n=>(                                // take n as input
  C=i=>                             // C finds recurring match in string S
    (I=S.indexOf(S.slice(i,i+n)))   // calculate the first index of a substring
      ==i                           // the index of the substring being tested
    ?                               // if those are equal, no match
      S[i+n]                        // if we're not at end of string,
      ?C(i+1)                       // continue recursing
      :-1                           // otherwise, return -1 (no match)
    :i,                             // we have a match, return i
  P=p=>                             // loops over powers of 2 and check matches
    (z=C(0,S=(2n**p+'')))<0         // check 2^p for match
    ?P(++p),                        // if no match, continue recursing
    :p                              // if we find a match, return the power
  [P(0n),I,z]                       // return power, first and last index
)

```

---
Tags: code-golf, number, restricted-time
---


# Question
Title: Compute the difference between two days.
Another date-manipulating problem :P

## Task

> Write a program or a function that calculates the difference between two dates given by a user.

## Input & Output

Similar to the previous one, inputs are two `YYYYMMDD`s, separated by a space , a comma `,`, or a minus sign `-`.

Example of input values:

```
20100101-20010911
20110620-20121223
19000101 20101010
33330101,19960229
00010101 99991231

```

Output is an integer, which is difference between two dates, in days.

For example, input `20110101-20100101` yields `365`, and `33320229 17000101` yields `596124`.

You may test results ~~at here~~ at here. (See rintaun's comments below.) If two dates are same, the program should returns `0`, if the date is valid (see **Score**).

## Restriction

Of course, you **must** not use **any** kinds of function/class/... which are related to timestamp or date, and you should use Gregorian calender.

## Score

If your code doesn't keep the restriction, then `score = -∞`.

Default `bonus` is 1.

* If your code works regardless of order of inputs (for example, `20100101,20110101` returns `365` or `-365`), `bonus+=1`.
* If your code can handle year 0, `bonus+=0.5`.
* If your code recognizes invalid month(between 1~12)/date(between 1~31), like `20109901` or `34720132`, and prints `E` (& terminates the program or returns something like `0`), `bonus+=1`.
* Regardless of above rule, if your code recognizes invalid dates, like `20100230`, `20100229`, or `20111131`, and prints `E` (& terminates the program or returns something like `0`), `bonus+=1`.
* Regardless of above two rules, if your code recognizes invalid input string, like `20100101|20100202` or `2010010120100202`, and prints `E` (& terminates the program or returns something like `0`), `bonus+=1`.

`score = floor(-4.2*code.length/bonus)`. Code with highest score wins. If two top codes have same score, then codes with highest bonus wins. If two top codes have both same score and bonus, then codes with highest votes wins.

(Due: When there's more than 5 codes which has more than (or equal) `+1` votes.)

# Answer
> 3 votes
## Perl 5.14, score = -162

-163 -181 -196 -214 -167 -213 -234 * code.length = 211: 208 source characters + 3 for running perl with the `-p` option
* bonus = 5.5: default, order, year 0, never-valid month/day, invalid date, wholly-invalid input

### Code

```
$_=eval(join'-',map{($y,$m,$d)=/(....)(..)(..)/;die"E\n"if!($m*$d)||$m>12||$d>30+($m&1^$m>7)-($m==2)*(2-!($y=~s/00$//r%4));$y-=($m<3)-400;$d+int(($m+9)%12*30.6+.4)+int(365.2425*$y)}/^(\d{8})[ ,-](\d{8})$/)//E

```

Calculates a modified Julian day number for each date (ignoring the epoch-related adjustments to save code length) and subtracts the two. (ref. "Julian Day" at Wikipedia).

* requires perl 5.14+ for the `/r` option on the substitutions
* month-length calculation to get the invalid date bonus: the `30+($m&1^$m>7)` part gives the length of any month but February; the rest adjusts for February in an ordinary or leap year

### Assumptions

* "use Gregorian calendar" means the proleptic Gregorian calendar for dates before whichever Julian to Gregorian transition we're using. That is, don't subtract 11 days for intervals that cross, for example, the 3 Sep 1752 - 14 Sep 1752 British transition.
* "handle year 0" means, for example, `00000101-00010101` should give 366, as 0 is an integral multiple of 400, and so year 0 is a leap year.

# Answer
> 2 votes
# PHP, Score: -539.1

* 706 characters
* All bonus items; bonus = 5.5

## Code

```
<?php $a='(\d{4})(0[0-9]|1[0-2])([0-2][0-9]|3[01])';@$p=preg_match;if(!$p('/^(\d{8})[- ,](\d{8})$/',fgets(STDIN),$z))@die(E);unset($z[0]);sort($z);foreach($z AS$x){if(!$p('/(\d{4})(0[0-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])/',$x,$w))die(E);$n[]=$w;}$m=array(31,28,31,30,31,30,31,31,30,31,30,31);$r=0;$b=$n[0][1];$c=$n[0][2];$d=$n[0][3];$e=$n[1][1];$f=$n[1][2];$g=$n[1][3];@$t=str_pad;if((($b.$e==229)&&(!(!($b%4)+!($b%100)-!($b%400))))||($c>12))die(E);for($z=$b.$c.$d;;$s=$d,$r++){if($z==$e.$f.$g)break;if($z>$e.$f.$g)@die(E);if(@$s==$d)$d++;if((($c!=2)&&($d>$m[$c-1]))||(($c==2)&&($d>($m[$c-1]+!($b%4)-!($b%100)+!($b%400))))){$c++;$d=1;}if($c>12){$b++;$c=1;}$z=$b.$t($c,2,0,0).$t($d,2,0,0);}echo($r>0)?--$r:0;

```

### Ungolfed

```
<?php
$a='(\d{4})(0[0-9]|1[0-2])([0-2][0-9]|3[01])';
@$p=preg_match;
if(!$p('/^(\d{8})[- ,](\d{8})$/',fgets(STDIN),$z)) @die(E);
unset($z[0]);
sort($z);
foreach($z AS $x)
{
        if (!$p('/(\d{4})(0[0-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])/',$x,$w)) die(E);
        $n[]=$w;
}
$m=array(31,28,31,30,31,30,31,31,30,31,30,31);
$r=0;
$b=$n[0][1];
$c=$n[0][2];
$d=$n[0][3];
$e=$n[1][1];
$f=$n[1][2];
$g=$n[1][3];
@$t=str_pad;
if ((($b.$e==229)&&(!(!($b%4)+!($b%100)-!($b%400))))||($c>12)) die(E);
for ($z=$b.$c.$d;;$s=$d,$r++)
{
        if ($z==$e.$f.$g)break;
        if ($z>$e.$f.$g)@die(E);
        if (@$s==$d)$d++;
        if ((($c!=2)&&($d>$m[$c-1]))||(($c==2)&&($d>($m[$c-1]+!($b%4)-!($b%100)+!($b%400)))))
        {
                $c++;
                $d=1;
        }
        if ($c>12)
        {
                $b++;
                $c=1;
        }
        $z=$b.$t($c,2,0,0).$t($d,2,0,0);
}
echo($r>0)?--$r:0;

```

## Note

Calculates the number of days by iterating through each valid date between the two provided. It's pretty slow on larger ranges. I'm sure this isn't the best way to solve this, but I got impatient, and this is what I ended up with. :)

Also, I know the "ungolfed" code still isn't very readable, but rewriting it completely would require too much effort.

# Answer
> 2 votes
## Python, Score: -478

* characters: 455
* bonus: reverse dates, invalid day/month, invalid date

solution:

```
import re
a=re.split('[-, ]',raw_input())
def c(x):return x[0]
def f(x,y=3):return(1if x%400==0 or x%100!=0and x%4==0 else 0)if y>2 else 0
t=[31,28,31,30,31,30,31,31,30,31,30,31]
[q,w,e],[i,o,p]=sorted([map(int,[a[x][:4],a[x][4:6],a[x][6:]])for x in[0,1]],key=c)
print sum(map(f,range(q,i)))+(i-q)*365+p+sum(t[:o-1])-e-sum(t[:w-1])+f(i,o)-f(q,w)if 0<w<13and 0<e<32and 0<o<13and 0<p<32and(e<=t[w-1]or(f(q)and e==29))and(p<=t[o-1]or(f(i)and p==29))else 'E'

```

I don't have "ungolfed" version as this is how I wrote it. I didn't test it properly so if you find a bug - please comment.

edit: hopefully fixed a bug pointed out in a comments and added unpacking in form of \[a,b\],\[c,d\]=\[\[1,2\],\[3,4\]

# Answer
> 2 votes
## Ruby 1.9, Score: -175 -186 -191 -199

* Code length: 229 243 250 260 characters
* Bonus: 5.5 (default, order, year 0, invalid month/day, invalid date, invalid input)

The code accepts input through stdin.

```
h=->n{n/4-n/100+n/400+1}
u,v=gets.split(/[ ,-]/).map{|s|s=~/^\d{8}$/?(d,e,f=[s[0,4],s[4,2],s[6,2]].map &:to_i;x=[0,y=31,28+h[d]-z=h[d-1]]+[y,30,y,30,y]*2
(!x[e]||e*f<1||f>x[e])?0:d*365+z+eval(x[0,e]*?+)+f):0}
puts (v*u>0)?u-v :?E

```

Notes:

* h returns the number of leap years up until that year (including year 0 for the bonus).
* The regex handles the invalid input bonus.
* The `(!x[e]||e*f<1||f>x[e])` condition handles the invalid month/day/date bonuses.
* The result is displayed as the first date minus the second date, so if the second date is later it will output as a negative number.
* Does not adjust for the change between Julian and Gregorian calendars, so `33320229 17000101` results in `596134`.

# Answer
> 1 votes
## PHP, score: -516

chars : 685 676

bonus : 5.5

```
<? $z='/((\d{1,4})(\d\d)(\d\d))[- ,]((\d{1,4})(\d\d)(\d\d))/';if(!preg_match($z,$argv[1],$m))die('E');$s=1;if($m[1]>$m[5]){if(!preg_match($z,"$m[5] $m[1]",$m))die('E');$s=-1;}$b=array(31,28,31,30,31,30,31,31,30,31,30,31);list($x,$v,$c,$d,$e,$w,$f,$g,$h)=$m;if($d>12||1>$d||$g>12||1>$g||1>$e||1>$h||($e>$b[$d-1]&&!($d==2&&$e<30&&$c%4==0))||($h>$b[$g-1]&&!($g==2&&$h<30&&$f%4==0)))die('E');$z='array_slice';$y='array_sum';$x=$d!=$g||$e>$h;$r=$x?$b[$d-1]+$h-$e:$h-$e;$d+=$x;if($d>12){$c++;$d=1;}$r+=$d>$g?$y($z($b,$d-1,13-$d))+$y($z($b,0,$g-1)):($d!=$g?$y($z($b,$d-1,$g-$d)):0);$r+=($f-$c-($d>$g))*365;for($i=$c;$i<=$f;$i++)if($i%4==0&&$i.'0229'>$v&&$i.'0229'<$w)$r++;echo $s*$r;

```

# Answer
> 1 votes
# PowerShell, 294 bytes, ~-353 score, +3.5 bonus

```
function J($s){if($s.length-ne8){"E";exit};iex ('$Y_0,4));$M_4,2));$D_6,2))'-replace'_','=[int]($s.substring(');$B=($M-14)/12;if($m-notin1..12){'E';exit};$A=$Y+4800;($J=1461*($A+$B)/4+367*($M-2-12*$B)/12-(3*(($A+$B+100)/100))/4+$D-32075)};[math]::truncate((J("$($args[0])"))-(J("$($args[1])")))

```

Try it online!

It uses Julian Date to calculate difference between to `YYYYMMDD` dates.

**Explanation**

* At first, to avoid redundant code, it's better to use a function. So we declare a function named `J` which calculates the julian date of a given date in `YYYYMMDD` format, and takes the parameter as `$s`.
* Next, we need to check for invalid string. If the given string length is not 8 (`YYYYMMDD` length is 8), then output `E` and exit.
* Parse the string. We used substrings for that. First 4 characters are the year (`$Y`), next 2 are the month (`$M`), and next 2 are the day (`$D`). To get a substring, we use .NET `.substring()` method for that, and cast it to type `[int]`. But its a huge part of code, and to golf it we replace `=[int]($s.substring(` with `_` and build a string `$Y_0,4));$M_4,2));$D_6,2))` and while in the code replace `_` with `=[int]($s.substring(` again and evaluate the expression using `iex` (Which is an alias of `Invoke-Expression`).
* Another check for month validity. `1..12` is the array of numbers between `1` to `12`, if `$M` (month number) is not in the `1..12` array, we output `E` and exit.
* Then the main logic goes. We calculate the Julian date. I found the algorithm here
* End the function.
* We compute date difference after that. `$args` is an automatic array in Powershell which contains the parameters provided to the script (Not the function). We cast 0 and 1 index to string (`$()` operator is sub-expression operator, which evaluates a string as code inside a double-quoted string, and then surround double quotes to cast to string), pass each to `J` function and subtract the returned integer Julian dates.
* At last, truncate the result using .NET `[math]::truncate()` method.

**Bonus**

* Initial bonus, so bonus +1
* The code will work if the first date is smaller than second one (i.e. `20100101 20110101`), so bonus +1
* Cannot handle year 0, so bonus +0
* Can handle invalid month, but not invalid Day, so bonus +0.5
* Cannot determine invalid dates, so bonus +0
* Can handle invalid strings in parameters, so bonus +1

Total: `1+1+0+0.5+0+1=3.5`

**Total score**

* Code length: 294 bytes
* Total bonus: +3.5

$$ floor(-4.2\*294/3.5) = -353 $$

---
Tags: code-golf, date
---


# Question
Title: Predict a Collision: Will the robber get away?
Think of a road as a number line, starting at `0` and continuing indefinitely:

```
.................................................................

```

There are two cars on the road: `C` and `R`. `C` is the cop who is trying to catch `R`, the robber. `C` starts at `0`, and `R` starts somewhere on the road:

```
C.............................R..................................

```

The cop is already moving - he's chasing the robber. He has a constant speed. The robber just hopped into his car. He's accelerating. Each tick, the robber's speed increases by his acceleration.

Say the cop's speed is `7` and the robber's acceleration is `1`. If the robber starts at `30`, this is what the road would look like each tick:

```
C.............................R..................................
.......C.......................R.................................
..............C..................R...............................
.....................C..............R............................
............................C...........R........................
...................................C.........R...................
..........................................C........R.............
.................................................C........R......

```

After the last tick above, the robber's speed is equal to the cop's, and he's still ahead. Since the cop is moving at a constant speed and the robber is still speeding up, the robber escapes, so you output a truthy value. However, if the cop's speed had been `9`...

```
C.............................R..................................
.........C.....................R.................................
..................C..............R...............................
...........................C........R............................
....................................C...R........................
.............................................X...................

```

... then the cop catches up to the robber before the robber can get away (marked by the `X`), so you output a falsey value.

# Your Task

Given three inputs - the cop's speed, the robber's position, and the robber's acceleration - determine whether or not the robber will get away.

# Rules

* The cop always starts at `0`.
* All inputs will be positive integers.
* The cop catches the robber if, after any tick, the cop's position is greater than or equal to the robber's position.
* The robber gets away when he hasn't been caught yet and his speed is greater than the cop's.
* Your program must terminate after output.
* The robber accelerates before he moves each tick.

# Test Cases

```
Cop Speed, Robber Position, Robber Acceleration -> Output

```

```
7, 30, 1 -> truthy
9, 30, 1 -> falsey
2, 1, 3 -> truthy
100, 100, 50 -> truthy
60, 60, 20 -> falsey
10, 1, 1 -> falsey
10, 50, 2 -> truthy
11, 50, 2 -> truthy
12, 50, 2 -> truthy
13, 50, 2 -> truthy
14, 50, 2 -> truthy
15, 50, 2 -> truthy
16, 50, 2 -> falsey
17, 50, 2 -> falsey
18, 50, 2 -> falsey
100, 451, 10 -> truthy

```

Reference Python 3 implementation that creates a visual also: Try it online!

This is , so shortest answer in bytes wins.

# Answer
# Jelly, 9 bytes

```
_⁵Ḥ¤²÷÷8<

```

Try it online!

Port of Leaky Nun's Python 3 answer.

(full program) Takes arguments in order `acceleration, position, speed`.
> 3 votes

# Answer
# Python 3, 29 bytes

```
lambda s,p,a:(a-2*s)**2<8*a*p

```

Try it online!

### Explanation

The cop's position at time `t` is `st`.

The robber's position at time `t` is `a(t)(t+1)/2 + p`.

The signed distance from the cop to the robber is `(a/2)t^2 + (a/2-s)t + p`.

It never reaches zero if the discriminant is negative, the discriminant being `(a/2 - s)^2 - 4(a/2)(p) = [(a-2s)^2-8ap]/4`, which has the same sign as `(a-2s)^2-8ap`.
> 17 votes

# Answer
# Cubically, 61 bytes

```
$:7(U1R3U1F3D2*1-1/1)6+7$-77*6$(-77777777D2F1U3R1U3!0{<0%6&})

```

Try it online! For this to work in TIO, you may need to replace `&` with `&1` due to a bug in the interpreter.

This is a shameless port of Leaky Nun's answer. Input is in the form `a s p`, where `a` is robber's acceleration, `s` is cop's speed, and `p` is robber's position.

If the acceleration is too high, this will fail. I don't know how high of an acceleration this program will support, but I know it isn't any higher than 1260. The limiting factor is that it stores the acceleration in the cube and checks if the cube is solved by checking only if the top face's sum is 0 (an incomplete check). It seems to work for acceleration = 50, but I haven't tested to see how high it can get.

### How it works

```
$:7(U1R3U1F3D2*1-1/1)6
$:7                             Store the first number in the notepad
   (                )6          Loop until notepad is 0
    U1R3U1F3D2                  Rotate the cube a certain way
              *1-1/1            Subtract 1 from the notepad

+7$-77*6
+7                              Add first input to the notepad
  $-77                          Subtract second input from the notepad twice
      *6                        Multiply the notepad by itself (square it)

$(-77777777D2F1U3R1U3!0{<0%6&})
$                               Get next input
 (                            ) Loop indefinitely
  -77777777                     Subtract third input 8 times
           D2F1U3R1U3           "Unrotate" the cube
                     !0{     }  If the top face is 0
                        <0        Check if notepad < 0, store in notepad
                          %6      Output notepad as number
                            &     End the program

```
> 6 votes

# Answer
# Japt, 13 bytes

```
²/W-V-U<o0W x

```

Test it online!

### Explanation

`U`, `V`, and `W` are the implicit inputs. First, with `Uo0W` we create the range **\[0, W, 2\*W, ...\]** until it reaches `U`. `x` then sums this, which gives how far the robber travels before reaching cop speed. We'll call this **r**.

Now, how far does the cop travel in this time? We can calculate this using **U * (U // W - 1)**, which can be rearranged to **(U * U) // W - U**. We'll call this **c**.

Now for the final step: does the robber get away? All we need to do here is check if **c \< r + V**, or rearranged, **c - V \< r**.
> 5 votes

# Answer
# Pyth, 11 bytes

This takes them in this order: `Robber Acceleration, Cop Speed, Robber Position` separated by a newline (as shown in the test suite).

```
<^-QyE2*8*E

```

**Test Suite** or **Try it online!**
> 5 votes

# Answer
# Pyke, 14 bytes

Port of totallyhuman's Python answer. Returns `1` for truthy and `0` for falsy.

```
hQee-XQ1@Qe*}<

```

**Try it here!**

---

# Explanation

```
hQee-XQ1@Qe*}< - Full program with implicit input added in the beginning (which automatically splits the components)

h              - First input
 Qee           - Last Input halved (through integer division)
    -          - Subtact the above
     X         - Square.
             < - Is smaller than?
      Q1@      - The second input
         Qe*   - Multiplied by the last input
            }  - Doubled

```

# Pyke, 15 bytes

My very first Pyke answer! Port of my Pyth solution, which is inspired by Leaky's Python submission. Returns `1` for truthy and `0` for falsy.

```
eQh}-XQe8*Q1@*<

```

**Try it here!**

---

# Explanation

```
eQh}-XQe8*Q1@*< - Full program with implicit input added in the beginning (which automatically splits the components)

e               - End; last input in this case
 Qh             - The first input
   }            - Double
    -           - Subtact the above
     X          - Square.
              < - Is less than?
      Qe        - Last Input
        8*      - Times 8
             *  - Multiplied by
          Q1@   - The second input.

```
> 5 votes

# Answer
# Ruby, 29 27 25 bytes

```
->c,p,a{(a-c-c)**2<8*p*a}

```

Try it online!

Got from 29 to 27 by stealing the idea of multipliying both sides by 4. (Leaky Nun's python answer)

Got from 27 to 25 by removing parens around lambda parameters (thanks totallyhuman)
> 3 votes

# Answer
# C# (.NET Core), 33 bytes

```
(v,p,a)=>v/a*v<p+v/a*(1+v/a)*.5*a

```

Try it online!

I feel like this is off by one somewhere, but it passes for all test cases so it's possible that there simply aren't any test cases where the cop overtakes the robber for a single tick, or it might just work despite my reservations.
> 3 votes

# Answer
# JavaScript (V8), 25 bytes

```
(c,r,a)=>(a-c*2)**2<8*r*a

```

Try it Online!
> 3 votes

# Answer
# Python 2, 62 bytes

```
P=s=0;S,p,a=input()
while(s<S)*(P<p):s+=a;p+=s;P+=S
print s>=S

```

Try it online!
> 2 votes

# Answer
# Swift 3, 55 bytes

Note that I declared the variable `t` because the expression would be too complex to be solved in reasonable time otherwise (Swift's fault!).

```
func f(a:Int,b:Int,c:Int){let t=c-2*a;print(t*t<8*c*b)}

```

**Test Suite.**

**or 55 bytes**, exact closure equivalent (I need the last part because it is a complex construct):

```
{let t=$2-2*$0;return t*t<8*$2*$1}as(Int,Int,Int)->Bool

```

**Test Suite.**

# Swift 3, 57 bytes

```
func f(a:[Int]){let t=a[2]-2*a[0];print(t*t<8*a[2]*a[1])}

```

**Test Suite.**
> 2 votes

# Answer
# Python 2, 30 bytes

```
lambda c,p,a:c/a*(c-a+c%a)/2<p

```

Try it online! The cop has `c/a` ticks in which to catch the robber, after which it has out-accelerated the cop. At the first tick the cop gains `c-a` on the robber while on the last tick he only gains `c%a`. Thus the total that the cop can gain is the product of the number of ticks and the average distance per tick. This is simply compared to the initial lead the robber has.
> 2 votes

# Answer
# TI BASIC (TI-83/84 series), 18 bytes

```
Prompt C,R,A
(A-2C)²<8RA

```

Yet another port of *itdoesntwork*'s influential Ruby solution.

## Execution

Input order is cop speed, robber position, robber acceleration.

```
C=?7
R=?30
A=?1
               1

```
> 2 votes

# Answer
# Recursiva, ~~19~~ 16 bytes

```
>b*I/acIH+-ac%ac

```

Try it online!
> 2 votes

# Answer
# Retina, 79 bytes

```
\d+
$*
$
;
{`(1+);
$1;$1
,(1+;(1+))
$2,$1
1`(1+),\1
$1,
.*,,.*

^(1+),.*;\1.*
1

```

Try it online! Explanation:

```
\d+
$*

```

Convert input to unary.

```
$
;

```

Make room for the robber's speed.

```
{`(1+);
$1;$1

```

Accelerate the robber on each pass.

```
,(1+;(1+))
$2,$1

```

Move the robber away from the cop.

```
1`(1+),\1
$1,

```

Move the cop towards the robber.

```
.*,,.*

```

Has the cop caught the robber?

```
^(1+),.*;\1.*
1

```

Does the robber out-speed the cop?
> 2 votes

# Answer
# Python 2, ~~31~~ ~~30~~ 29 bytes

*-1 byte thanks to Mr. Xcoder.*

Started off as a port of the Ruby answer.

```
lambda c,p,a:(c-a/2)**2<2*p*a

```

Try it online!
> 1 votes

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


title: Swap bits with their neighbours

text:
# Question
Title: Swap bits with their neighbours
# Task description

Given an integer, swap its **(2k–1)**-th and **2k**-th least significant bits for all integers **k \> 0**. This is sequence A057300 in the OEIS.

(The number is assumed to have “infinitely many” leading zeroes. In practice, this simply means prepending a single 0 bit to odd-length numbers.)

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

# Test cases

```
0 -> 0
1 -> 2
9 -> 6
85 -> 170
220 -> 236
1827 -> 2835
47525 -> 30298

```

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

```
b4d2UFḄ

```

Try it online! or verify all test cases.

### How it works

```
b4d2UFḄ  Main link. Argument: n (integer)

b4       Convert n to base 4.
  d2     Divmod each quaternary digit x by 2, yielding [x : 2, x % 2].
    U    Upend; reverse each pair, yielding [x % 2, x : 2].
     F   Flatten the 2D list of binary digits.
      Ḅ  Convert from binary to integer.

```
> 9 votes

# Answer
## Python 2, 26 bytes

```
lambda n:2*n-3*(4**n/3&n/2)

```

Bit tricks!

Say `n` has form `...ghfedcba` in binary. Then, we can split it into every other bit as

```
n   = o + 2*e
n   = ...hgfedcba
o   = ...0g0e0c0a
2*e = ...h0f0d0b0

```

Then, the bit-switched result `s` can be expressed as `s=2*o+e`.

```
s   = 2*o + e
s   = ...ghefcdab
2*o = ...g0e0c0a0
e   = ...0h0f0d0b

```

We'd rather compute only one of `e` and `o`, so we express `o=n-2*e` and substitute

```
s=2*(n-2*e)+e = 2*n-3*e

```

So, now it remains to express `e` in terms of `n`. The number `M=4**n/3` has form `...10101010101` in binary, which serves as a mask for the odd digits. The exponent `n` ensures that `M` is long enough. Taking the bitwise `and` of `n/2` and this value gives `e` as desired.

```
n/2     = ...hgfedcb
M       = ...1010101
n/2 & M = ...h0f0d0b = e

```

We can instead express `e` in terms of `o` `e=(n-o)/2`, which gives `s=(n+o*3)/2`, which saves a byte thanks to an optimization from xsot.

```
lambda n:n+(n&4**n/3)*3>>1

```
> 20 votes

# Answer
# C function, 38

Bit-twiddling:

```
f(x){return(x&~0U/3*2)/2+(x&~0U/3)*2;}

```

Ideone.

---

Or for the fun of it:

# C recursive function, 43

As per the OEIS formula, `a(4n+k) = 4a(n) + a(k), 0 <= k <= 3`

```
f(x){return x>3?4*f(x/4)+f(x%4):x%3?3-x:x;}

```

or

```
f(x){return x>3?4*f(x/4)+f(x%4):x%2*2+x/2;}

```

Ideone.
> 10 votes

# Answer
## CJam, ~~16~~ ~~14~~ 13 bytes

```
ri4b4e!2=f=4b

```

Test it here.

### Explanation

```
ri  e# Read input and convert to integer.
4b  e# Get base-4 digits.
4e! e# Push all permutations of [0 1 2 3].
2=  e# Select the third one which happens to be [0 2 1 3].
f=  e# For each base-4 digit select the value at that position in the previous
    e# list, which swaps 1s and 2s.
4b  e# Convert back from base 4.

```
> 8 votes

# Answer
# Pyth, 9 bytes

```
iXjQ4S2)4

```

Try it in the Pyth Compiler.

### How it works

```
  jQ4      Convert the input (Q) to base 4.
 X   S2)   Translate [1, 2] to [2, 1].
i       4  COnvert from base 4 to integer.

```
> 7 votes

# Answer
## JavaScript (ES6), ~~32~~ 30 bytes

```
(n,m=0x55555555)=>n*2&~m|n/2&m

```

Only works up to 1073741823 due to the limitations of JavaScript's integers. ~~38~~ 36 bytes works up to 4294967295:

```
(n,m=0x55555555)=>(n*2&~m|n/2&m)>>>0

```

Edit: Saved 2 bytes thanks to @user81655.

51 bytes works up to 4503599627370495:

```
n=>parseInt(n.toString(4).replace(/1|2/g,n=>3-n),4)

```
> 5 votes

# Answer
# x86 asm function: 14 bytes of machine code

## uint64\_t version: 24 bytes

x86-64 SysV calling convention (`x` in `edi`), but this same machine code will also work in 32bit mode. (Where the `lea` will decode as `lea eax, [edi + eax*2]`, which gives identical results).

```
0000000000000040 <onemask_even>:
  40:   89 f8                   mov    eax,edi
  42:   25 55 55 55 55          and    eax,0x55555555
  47:   29 c7                   sub    edi,eax
  49:   d1 ef                   shr    edi,1
  4b:   8d 04 47                lea    eax,[rdi+rax*2]
  4e:   c3                      ret
4f: <end>

```

`0x4f - 0x40` = 14 bytes

This is compiler output from using xnor's excellent mask-once idea the opposite way. (And opposite terminology: the low bit is bit 0, which is even, not odd.)

```
unsigned onemask_even(unsigned x) {
  unsigned emask = ~0U/3;
  unsigned e = (x & emask);
  return e*2 + ((x - e) >> 1);
}

```

I didn't find any improvements over what the compiler does. I might have written it as `mov eax, 0x555...` / `and eax, edi`, but that's the same length.

---

The same function for 64bit integers takes 24 bytes (see the godbolt link). I don't see any way shorter than 10-byte `movabs rax, 0x55...` to generate the mask in a register. (x86's `div` instruction is clunky, so unsigned division of all-ones by 3 doesn't help.)

I did come up with a loop to generate the mask in rax, but it's 10 bytes (exactly the same length as the `mov imm64`).

```
# since 0x55 has its low bit set, shifting it out the top of RAX will set CF
0000000000000000 <swap_bitpairs64>:
   0:   31 c0                   xor    eax,eax      ; old garbage in rax could end the loop early
0000000000000002 <swap_bitpairs64.loop>:
   2:   48 c1 e0 08             shl    rax,0x8
   6:   b0 55                   mov    al,0x55      ; set the low byte
   8:   73 f8                   jnc    2 <swap_bitpairs64.loop>  ; loop until CF is set
000000000000000a <swap_bitpairs64.rest_of_function_as_normal>:
 # 10 bytes, same as   mov  rax, 0x5555555555555555
 # rax = 0x5555...
   a:   48 21 f8                and    rax,rdi
   ...

```

If we knew that none of the existing bytes in `rax` has their low bit set, we could skip the `xor`, and this would be 8 bytes long.

A previous version of this answer had a 10 byte loop using the `loop` insn, but it had a worst-case run-time of `0xFFFFFFFFFFFFFF08` iterations, because I only set `cl`.
> 5 votes

# Answer
# Oasis, 17 bytes (non-competing)

```
n4÷axxn4÷xxe+3120

```

Try it online!

Oasis is a language designed by Adnan which is specialized in sequences.

Currently, this language can do recursion and closed form.

We use this formula: `a(4n+k) = 4a(n) + a(k), 0 <= k <= 3`

To specify the base case is simple: the `3120` at the end simply means that `a(0)=0, a(1)=2, a(2)=1, a(3)=3`.

```
n4÷axxn4÷xxe+3120
                0  a(0) = 0
               2   a(1) = 2
              1    a(2) = 1
             3     a(3) = 3

n                  push n (input)
 4÷                integer-divide by 4
   a               a(n/4)
    xx             double twice; multiply by 4
                   now we have 4a(n/4)
      n            push n (input)
       4÷xx        integer-divide by 4 and then multiply by 4
                   since there is no modulo currently, n%4
                   is built as n-(n/4*4)
           e       we should have done a(n-(n/4*4)), but this
                   is a shortcut for a(n-x) where x is the top
                   of stack. Therefore, we now have a(n-n/4*4)
                   which is a(n%4).
            +      add.

```
> 5 votes

# Answer
# MATL, 10 bytes

```
BP2eP1ePXB

```

Try it online!

Modified version to generate the first terms of the sequence (OEIS A057300).

### Explanation

```
B     % Take input implicitly. Convert to binary array
P     % Flip
2e    % Convert to two-row 2D array, padding with a trailing zero if needed.
      % Because of the previous flip, this really corresponds to a leading zero
P     % Flip each column. This corresponds to swapping the bits
1e    % Reshape into a row
P     % Flip, to undo the initial flipping
XB    % Convert from binary array to number. Display implicitly

```
> 4 votes

# Answer
## zsh, 28 bytes

```
<<<$[`tr 12 21<<<$[[#4]$1]`]

```

Takes input as a command line argument, outputs on STDOUT.

It's not Bash-compatible because it uses zsh-specific base conversion syntax.

```
                       $1     input (first command line argument)
                 $[      ]    arithmetic expansion
                   [#4]       output in base 4
              <<<             pass the result of this to...
      tr                      the `tr' command
         12 21                and replace 1s with 2s, 2s with 1s
     `                    `   evaluate the result...
   $[                      ]  in another arithmetic expansion, to convert back
                                to base 10
<<<                           output the result on STDOUT

```
> 3 votes

# Answer
# Retina, 70 bytes

```
.+
$*
+`(1+)\1
$1x
x1
1
^
x
r`(.)(.)
$2$1
1
x@
+`@x
x@@
x*(@*)
$.1
0$

```

Test suite. (Slightly modified.)

### Well, just for fun: 7 bytes

```
T`12`21

```

Takes base-4 as input, and outputs as base-4.

Try it online!
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
4B12Â‡4ö

```

Thanks to @Adnan for -5 bytes!

**Uses CP-1252 encoding.**

Try It Online!

Explanation:

```
4B       - Take input and convert to base 4.
  12Â    - Push 12 bifurcated.
     ‡   - Transliterate [1, 2] to [2, 1].
      4ö - Convert to base 10.

```
> 3 votes

# Answer
# C, ~~32~~ ~~30~~ 29 bytes

```
f(x){return(x&~0U/3)*3+x>>1;}                // 30 bit version, see below

// less golfed:
f(x){return ((x & 0x55555555)*3 + x) >>1;}   //  >> is lower precedence than +

```

Algorithm copied from xsot's comment on xnor's Python answer. Instead of masking both ways, mask one way and combine.

This compiles to the same asm as the last version I tested, and it works (for x up to `0x3FFFFFFF`, and for x above that as long as bit 30 isn't set, see below). In machine code, it's the same length as my existing asm answer.

---

**The above version always clears the high bit of the result**. The best safe version is 32 bytes:

```
g(x){return 2*x-3*(x/2U&~0U/3);}   // safe 32bit version, works for all x

```

The Python version doesn't have this problem, because python uses arbitrary-precision integer types when needed, instead of truncating to a fixed upper limit.
> 3 votes

# Answer
# Javascript (ES6), ~~113~~ 109 bytes

Saved 4 bytes thanks to Upgoat

```
n=>+('0b'+/(..)+$/.exec('0'+n.toString`2`)[0].split``.reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])[0],2)

```

### How it works

```
n=>+('0b'+                              //parse as binary literal
    /(..)+$/.exec('0'+n.toString`2`)[0] //convert to binary string with an even number of digits
        .split``                        //convert to array
        .reduce((p,c)=>p.length-1?[p.join(c)]:[p[0],c],[''])
                                        //swap all numbers
)

```
> 2 votes

# Answer
# J, 20 bytes

```
4#.0 2 1 3{~4#.^:_1]

```

### Usage

```
>> f =: 4#.0 2 1 3{~4#.^:_1]
>> f 85
<< 170

```

Where `>>` is STDIN and `<<` is STDOUT.

### Ungolfed

```
to_base   =: 4 #.^:_1 ]
transpose =: 0 2 1 3 {~ to_base
from_base =: 4 #. transpose

```

Three forks.

### Sidenote

In the official interpreter, `^:_1` can be replaced by `inv`, saving 1 byte.

However, none of the online interpreters implement this.
> 1 votes

# Answer
# C#, 44 bytes

Based on the C implementation

`int f(int n)=>n>3?4*f(n/4)+f(n%4):n%2*2+n/2;`

Try it here: C# pad
> 1 votes

# Answer
# INTERCAL, 60 bytes

```
DOWRITEIN.1PLEASE.1<-!1~#21845'$.1~#43690DOREADOUT.1DOGIVEUP

```

Try it online!

Works for 16-bit integers, with I/O done in the most natural format for INTERCAL: the input is a series of decimal digits spelled out in one of several natural or constructed languages, and the output is in "butchered Roman numerals".

This is one of those rare challenges where INTERCAL's binary operators can actually be used at all intuitively, since repositioning bits is what they're all about. Select (`~`) takes the bits from its first argument corresponding to ones in its second argument and pads them to the right with zeroes, and mingle (`$`) interleaves the bits from its arguments such that the bits from the first argument are more significant. So the straightforward solution is to select out the less significant alternating bits (`.1~#21845`), select out the more significant alternating bits (`.1~#43690`), and interleave them back together in the opposite order. Fortunately for byte count, although INTERCAL's operators have no defined precedence (as the language's goal is to have no precedents), it turns out that the C-INTERCAL on TIO doesn't require much grouping for this particular expression, costing only one byte since `'.` can be abbreviated `!`.

With support for 32-bit integers:

# INTERCAL, 67 bytes

```
DOWRITEIN:1PLEASE:1<-':1~#0$#65535'$:1~#65535$#0DOREADOUT:1DOGIVEUP

```

Try it online!

INTERCAL doesn't allow 32-bit literals, which actually makes this a bit *easier* to read, since it means the magic constants for selecting alternating bits have to be constructed by mingling two 16-bit literals together, where one's all zeroes and the other's all ones. (Actually, even if there were 32-bit literals, this would still be shorter. `#0$#65535` is two bytes off `#1431655765`, and the same goes for the other one.) This communicates the whole process unnaturally well for INTERCAL.

An alternate approach with clumsy use of *operand overloading*:

# INTERCAL, 71 bytes

```
DO:1<-:1/.2$.3PLEASEWRITEIN:2DO:1<-:2PLEASE:2<-.3$.2DOREADOUT:2DOGIVEUP

```

Try it online!

This does away with selecting altogether by declaring that `:1` is `.2` mingled with `.3`, setting `:1` to the input, then outputting `.3` mingled with `.2`. Since `:1` was overloaded as `.2$.3`, `DO :1 <- :2` assigns values to `.2` and `.3` such that `:1` acquires the value of `:2`, which results in `.2` containing the more significant alternating bits from `:2` and `.3` containing the less significant alternating bits. This would be the shorter of the two 32-bit solutions by four bytes if `PLEASE WRITE IN :1` could replace `PLEASE WRITE IN :2 DO :1 <- :2` with overloaded `:1`, but `CALCULATING` turns out to be necessary for using overloading. I also feel like there might be some shorter way to carry out the overloading itself than starting the program with `DO:1<-:1/.2$.3`, but since this is INTERCAL I also also feel like there can't be.
> 1 votes

# Answer
# Husk, 8 bytes

```
ḋṁo↔‰2B4

```

Try it online!

Same as the Jelly solution.

# Husk, ~~9~~ 8 bytes

```
ḋṁ↔C_2Θḋ

```

Try it online!

General method.

-1 byte from Jo King. (using `Θ`)
> 1 votes

# Answer
## Mathematica, 44 bytes

```
Fold[3#+##&,#~IntegerDigits~4/.{1->2,2->1}]&

```

Same approach as my CJam answer: convert to base-4, swap 1s and 2s, convert back. It also uses alephalpha's trick to replace `FromDigits` with a `Fold` operation to save one byte.
> 0 votes

# Answer
## Actually, 16 bytes

```
4@¡"21""12"(t4@¿

```

Try it online!

Explanation:

```
4@¡"21""12"(t4@¿
4@¡               base 4 representation of n
   "21""12"(t     translate (swap 1s and 2s)
             4@¿  base 4 to decimal

```
> 0 votes

# Answer
# J, 22 bytes

```
([:,_2|.\,&0)&.(|.@#:)

```

Alternative approach based on array manipulation instead of the base 4 trick.

## Usage

```
   f =: ([:,_2|.\,&0)&.(|.@#:)
   (,.f"0) 0 1 9 85 220 1827 47525
    0     0
    1     2
    9     6
   85   170
  220   236
 1827  2835
47525 30298

```

## Explanation

```
([:,_2|.\,&0)&.(|.@#:)  Input: n
                   #:   Get the value as a list of base 2 digits
                |.@     Reverse it
(           )&.         Apply to the list of base 2 digits
         ,&0            Append a zero to the end of the list
    _2  \               Split the list into nonoverlapping sublists of size 2
      |.                Reverse each sublist
 [:,                    Flatten the list of sublists into a list
             &.(    )   Apply the inverse of (reversed base 2 digits)
                        to convert back to a number and return it

```
> 0 votes

# Answer
## REXX, 88 bytes

```
n=x2b(d2x(arg(1)))
o=0
do while n>''
  parse var n a+1 b+1 n
  o=o||b||a
  end
say x2d(b2x(o))

```
> 0 votes

# Answer
## x86 machine code - 19 bytes

Callable function, input in `ebx` output in `eax`.

Lisitng :

```
    16                                  global tukar_bits
    17                                  tukar_bits:
    18
    19 00000016 89DA                    mov  edx, ebx
    20 00000018 8D0412                  lea  eax, [edx + edx]
    21 0000001B D1EA                    shr  edx, 1
    22 0000001D 81E255555555            and  edx, 0x55555555
    23 00000023 8D1452                  lea  edx, [edx + edx * 2]
    24 00000026 29D0                    sub  eax, edx
    25 00000028 C3                      ret

```

Try it online!, using x86-64 caller.

---

## x86 machine code - 21 bytes

Callable function, input in `ebx`output in `eax`.

Listing :

```
     1                                  global tukar_bits
     2                                  tukar_bits:
     3
     4 00000000 89D8                    mov  eax, ebx
     5 00000002 89C2                    mov  edx, eax
     6 00000004 2555555555              and  eax, 0x55555555
     7 00000009 D1EA                    shr  edx, 1
     8 0000000B 81E255555555            and  edx, 0x55555555
     9 00000011 8D0442                  lea  eax, [edx + eax * 2]
    10 00000014 C3                      ret

```

Try it online!, using x86-64 caller.
> 0 votes

---
Tags: code-golf, sequence, number-theory, binary
---


title: Pretty Printing Parentheses

text:
# Question
Title: Pretty Printing Parentheses
The worst part about long lines or code or math equations are the parentheses. Nobody wants to read through `2x(3y+4*abs(x^[2*e^x])-5{3(x+y)-5})`!

So, the goal of this challenge is to make it at least slightly easier to read these parentheses-filled beasts! For the above math equation, the output should be:

```
2x (
  3y+4*abs (
    x^ [
      2*e^x
    ]
  )
  -5 {
    3 (
      x+y
    )
    -5
  }
)

```

A parenthesis is defined as either of these characters: `()[]{}`. Indents should each be two spaces, and there should be one space of seperation between the expression and the parenthesis: `2x (`, `x^ [` as some examples.

I would like to debut the Atomic Code Golf metric in this question. Take out all separators in your code (`()[]{}. ;` to name some common ones), and then take the length of your program if every reserved word and operator were 1 character long. That is your program's score. `if x**(3.2)==b[3]:print x` is 11 points: `if|x|**|3|.|2|==|b|3|print|x`, or `ix*3.2=b3px`. Any quick questions about the metric can be posted here; larger questions should be discussed in meta using the link above.

Lowest score wins. Good luck, have fun!

# Answer
> 4 votes
## C, 139 137 chars, 67 tokens

```
i,n;                                                      // 2 tokens
main(c){                                                  // 2 tokens
        while(~(c=getchar()))                             // 5 tokens
                n=strchr("([{}])",c)?                     // 11 tokens
                        n=c%4!=1,                         // 7 tokens
                        i+=n*4-2,                         // 7 tokens
                        printf("\n%*s%c"+n,n?1:i,"",c)    // 15 tokens
                :                                         // 1 token
                        !printf("\n%*s%3$c"+!n*4,i,"",c); // 17 tokens
}

```

Logic:

* Read until EOF (detect it because `~EOF==0`).
* If parenthesis, check open/close (for `c` in `")]}"`, `c%4==1`), update indentation (`i`), print with some whitespace.
* If not, print the character, possibly prefixed by newline and indentation (`n` is true after parenthesis).

# Answer
> 2 votes
## Python, 102(?) Tokens

(Please correct if I didn't count correctly)

```
def f(t):
#1  2 3
    l,s,p,c,e,n=0,"",1," ",")]}","\n"
#   4 5 6 7 8 9ab cd e fgh ijklm no p
    for i in t:
#   q   r s  t
        if i in"([{": l+=2;s+=c+i+n+l*c
#       u  v w xyzAB  CD E FG HIJKLMNOP
        elif i in e: l-=2;s+=n+l*c+i+p*(n+l*c);p=1
#       Q    R S  T  UV W XY Z123456789 abcde  fgh
        else:
#       i
            if len(s) and s[-1]in e: s+=n+l*c
#           j  k   l  m   n  o p  q  rs tuvwx
            s+=i;p=0
#           yz A BCD
    return s
#   E      F

```

# Answer
> 2 votes
## Perl, 86 char

57 tokens? (21+25+5+3+1+2?) Newlines are significant.

```
s![[{()}\]]!1-(3&ord$&)?" $&
"."  "x++$x:$/.($y="  "x--$x)."$&
$y"!ge;s/
 *
/
/g;print

```

# Answer
> 1 votes
# JavaScript (V8), ~~76~~ 74

```
(a,d)=>(d=0)||a.replaceAll(/[(\[{]/g,b=>` ${b}\n`+'  '.repeat(++d)).replaceAll(/[)\]}]/g,b=>`\n${(f='  '.repeat(--d))+b}\n${f}`)

```

Try it online!

```
(a,d)=>               pas argument a and d (a is the string, d is just as decleration)
 (d=0)||               set d to 0
 a.replaceAll(         replace everything in a that matches....
   /[(\[{]/g,            [,(,{   with....
   b=>                   pass matches into function
     ` ${b}\n`             space, bracket(the match) and newline
     +'  '.repeat(++d)     increment d and repeat the 2 spaces d times
   )
 .replaceAll(/[)\]}]/g,  match all ),],} and replace them with....
    b=>                  pass matches into function
      `\n${(f='  '.repeat(--d))+b}\n${f}`   newline, decrement d and repeat the 2 spaces d times, closing bracket(the match), newline and once again the repeated spaces
)

```

results in

```
#a#,#d#=>#d#=#0#||#a#replaceAll#/#[#(#\#[#{#]#/#g#b#=>#`# #$#{#b#}#\#n#`#+#'# # #'#repeat#++#d#replaceAll#/#[#)#\#]#}#]#/#g#b#=>#`#\#n#$#{#f#=#'# # #'#r#e#p#e#a#t#--#d#+#b#}#\#n#$#{#f#}#`#

```

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