title: RLE Brainfuck dialect

text:
# Question
Title: RLE Brainfuck dialect
# RLE Brainfuck

(related to BF-RLE)

The hypothetical RLE (Run-Length Encoding) dialect of Brainfuck accepts the symbols for the 8 commands and also accepts digits. The digits are used to represent the number of successive repetitions of a command, thus allowing run-length encoding of the source code.

`8>` is equal to `>>>>>>>>`.

The length is always on the left side of the command.

Your task is to write the shortest program/function that translates the input string (RLE Brainfuck fragment) into a regular Brainfuck program.

For example:

Input:

```
10+[>+>3+>7+>10+4<-]3>2+.>+.7+2.3+.2<2+.>15+.>.3+.6-.8-.2<+.<.

```

Ouptut:

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

```

The shortest code in byte count in each language will win.

# Answer
# Python 2, ~~62~~ 61 bytes

```
lambda s:eval(re.sub('(\d*)(.)',r'+1*\1*1*"\2"',s))
import re

```

Try it online!

The regex substitution expands `3<2+-` into the string:

```
+1*3*1*"<"+1*2*1*"+"+1**1*"-"

```

which is then `eval`ed. (Note how when `\1` is empty, we get `1**1 = 1`.) The first `+` is a unary operator which binds to the first number, and the other `+`s are string concatenation. This beats the more obvious

```
lambda s:re.sub('(\d+)(.)',lambda m:int(m.group(1))*m.group(2),s)
import re

```

by 14 bytes. Ordinarily `"\2"` wouldn’t always work, but thankfully `\` and `"` aren’t brainfuck commands.

---

**xnor** saved a byte, supplying the `1*\1*1` trick. Previously I had `\1L` in the regex, and defined `L=1` as a lambda argument, which is also pretty cool: `3L` is a long int literal and `L` is a variable.
> 24 votes

# Answer
# Pyth, 2 bytes

```
r9

```

**Try it here!**

## How it works

```
r9  - Full program receiving the String from STDIN.

r   - Pyth's set of extended string operations.
 9  - The ninth command of that set (run-length decode). This supports multi-digit numbers.

```
> 18 votes

# Answer
## Lua, ~~65~~ ~~64~~ 63 Bytes

~~Great ! For once, Lua beats Python !~~

**Edit: Saved one byte thanks to @Jarhmander, thanks to him for the useful trick to force a single result**

```
print(((...):gsub("(%d+)(.)",function(a,b)return b:rep(a)end)))

```

Try it online!

### Explanations

```
print)((...):gsub(             -- iterate over the argument and replace the strings
            "(%d+)(.)",       -- matching this pattern (at least one digit and a non-digit)
            function(a,b)     -- capture the digit and non-digit parts in separate variables
              return b:rep(a) -- repeat the non-digit a times, a being the digit part
            end)))

```
> 17 votes

# Answer
# Scala, ~~73~~ 69 bytes

```
"(\\d+)(.)".r.replaceSomeIn(_:String,m=>Some("$2"*m.group(1).toInt))

```

Try it online!
> 11 votes

# Answer
## Perl 5, 18 bytes

**17 bytes code + 1 for `-p`.**

```
s/\d+(.)/$1x$&/ge

```

Try it online!
> 10 votes

# Answer
# RLE Brainfuck, 204 bytes

```
-3>,[[->+>+<<]>>47-3<10+<->[-<+4>->+<[>-]>[3<+<[-]4>->]5<]3>57+[-]+<<[>>-<<[3>+3<-]]3>[3<+3>-]<[>>+7<+[->11-<+[-<+]->>+[-<[->10+<]>>+]<[-4>.4<]4>[-]-3<-<+7>-7<[8>+8<-]]8>[8<+8>-]<[3<.3<[-]-6>-]7<--5>-]<,]

```

As I understand it the specs for the brainfuck environment aren't super well-defined. This program assumes that the cells in the tape allow arbitrarily large positive and negative integers, with no overflow. This code will transcribe non-command comments as well, but it will expand the run-length encoding of comments (eg "see 3b" → "see bbb"). The resulting program should run the same, so I'm not too concerned.

I'm pretty sure I could still golf a few bytes off this but I'm exhausted from working with it.

Here's the custom interpreter + tests I've been using to test it. If you pass it input in the Standard Input box it should run against that input instead of running the tests.

My messy ungolfed workpad:

```
->>>,
[
  [->+>+<<]>>  clone 2 into 3 and 4
  if read char is between zero and nine
  (num buffer | max | is_digit | original char | read | temp0 | temp1)
                                                   ^
  47-
  <<<10+  set max
  <->  handle gross 0 case
  [  while max
    -  max minus one
    <+  buffer plus one
    >>>>-  read minus one
    IF STATEMENT : if read is 0
    >+<
    [>-]>[<
      <<+  is_digit = 1
      <[-]>>>  max = 0
    >->]<<  back to read
    <<<     back to max
  ]

  >>>57+[-]  reset `read` (need to add first to avoid infinite negative)

  +<<  check is_digit flag
  ( end marker | 0 | is_digit | original char | temp0 | temp1 | temp2 | temp3)
  x[  IF READ WAS DIGIT
    CODE 1a
    >>temp0 -<<x
    [>>>temp1 +<<<x-]
  ]
  >>>temp1 [<<<x+>>>temp1 -]
  <temp0 [
    START CODE 2a
    >>temp2 +
    7<y+[  IF THERE IS A NUMBER PREFIX
      -
      START CODE 1b
      >11-  end marker is negativeone
      <   on smallest digit
      +[-<+]->  find largest digit
      >+[  sum digits until we hit the end marker negativeone
        -
        <[->10+<]>  h1 = ten * h0; h0 = 0
        >
        +
      ]  leave the negativeone at zero though
      num | 0 | 0 | 0 | original char
            ^
      <num
      [->>>>.<<<<]  print `original char` `num` times
      >>>>[-]-  set `char` to negativeone
      <<<- last ditch guess
      END CODE 1b
      <y+
      7>temp2 -
      7<y[8>temp3 +8<y-]
    ]
    8>temp3 [8<y+8>temp3 -]
    <temp2 [
      CODE 2b
      <<<.  print original char
      <<<[-]-  set num buffer to new left edge
      >>>>>>temp2 -
    ]
    7<y--

    END CODE 2a
    5>temp0 -
  ]
  <
  ,
]

```
> 9 votes

# Answer
# vim, 29 25 23 22 16 bytes

```
:s/\D/a&<C-v><ESC>/g
D@"

```

`<C-V>` is 0x16, `<ESC>` is 0x1b.

It works by replacing each non-digit with a command that appends that character to the buffer. The counts are left alone and modify those commands. At this point, the buffer is a vimscript program that produces the desired Brainfuck program, so we pull it into a register and run it.

Try it online!

Edit: Size reductions thanks to suggestions: H.PWiz: 5, TheFamilyFroot: 5, DJMcMayhem: 1
> 8 votes

# Answer
# Stacked, 24 bytes

```
['(\d+)(.)'[\#~*]3/repl]

```

Try it online!

## Explanation

```
['(\d+)(.)'[\#~*]3/repl]
[                      ]   anonymous function, taking string as argument
 '(\d+)(.)'                for all matches of this regex:
           [    ]3/repl      replace (stack = (whole match, digit, repetend))
            \#~              convert digit to number
               *             repeat the character by that digit

```
> 6 votes

# Answer
# Retina, ~~28~~ 23 bytes

*thanks to @Leo for -5 bytes*

```
\d+
$*
+`1(1\D)
$1$1
1

```

Try it online!
> 5 votes

# Answer
# TeX, 124 bytes

```
\newcount\n\def\b{\afterassignment\r\n0}\def\r#1{\ifx;#1\else\p#1\expandafter\b\fi
}\def\p#1{#1\ifnum\n>1\advance\n-1\p#1\fi}

```

(wrote in two lines to be visible, but the code can be written in one line)

This defines a macro `\b` that takes the input in the form `\b<input>;`, and prints the output wanted to the document.
> 5 votes

# Answer
# Pyon, 66 bytes

```
print(re.sub("\d+.",lambda k:(int(k.group()[:-1])*k.group()[-1]),a

```

Try it online!

Pyon is pretty much just Python, but this is shorter because `re` is automatically imported when you use it, and `a` is automatically set to an argument or the input

-4 bytes thanks to Mr. Xcoder
> 4 votes

# Answer
# Python 2, ~~100~~ ~~93~~ 89 bytes

-7 with thanks to Mr.Xcoder

```
n=b=""
for y in input():
 if"/"<y<":":n+=y
 elif""==n:b+=y
 else:b+=y*int(n);n=""
print b

```

Try it online!
> 4 votes

# Answer
# Haskell, 60 bytes

```
f(a:b)|[(c,d:e)]<-reads$a:b=(<$)d[1..c]++f e|1<2=a:f b
f a=a

```

Try it online!
> 3 votes

# Answer
# , ~~121~~ ~~106~~ 90 bytes

```
function(s,a=strsplit)cat(rep(el(a(gsub("\\d","",s),"")),pmax(el(a(s,"\\D")),"1")),sep="")

```

Try it online!

Saved 15 bytes by realising that `rep()` will coerce to numeric. Saved another 16 thanks to Giuseppe, mainly from the use of `pmax` to replace empty strings with `1`

```
function(s) {
  x <- el(strsplit(s,"\\D")) # Split the string on anything that is not a digit...
  x <- pmax(x, "1")          # ... and replace any empty strings with 1. This gets us the numbers of repeats
  y <- gsub("\\d","",s)      # Remove all digits from the original string...
  y <- el(strsplit(y))       # ... and split into individual units. This gets us the symbols to repeat
  z <- rep(y, x)             # Implement the repeats. x is coerced to numeric
  cat(z, sep = "")           # Print without separators
}

```
> 3 votes

# Answer
# PowerShell, ~~66~~ 62 bytes

```
-join("$args"-split'\b'|%{(,$(,$_[0]*$n+$_))[!!($n=$($_-1))]})

```

Try it online!

# Breakdown

What a mess!

Starting from `$args`, which is a single element array containing the RLE string, I'm forcing into an actual string by wrapping it quotes.

Then split it by word boundary (`\b` in regex). That will give me an array of strings, where each element is either a number or the BF token(s) that come after the number. So in the example, the first 4 elements of this split array are `10`,`+]>+>`,`3`,`+>` (all are string).

Next, I pipe that into `ForEach-Object` (`%`) to deal with each *element*.

The middle is a well-known PowerShell golfism, with a twist; it's essentially a DIY ternary operator, in which you create a 2 element array then index into it using the boolean expression you want to test, whereby a false result gives you element 0 and a true result gives you element 1.

In this case, I actually create a single element array with the unary comma `,` operator, because I don't want output in the true case.

First let's look at the indexer, even though it gets executed later.

The idea of this is that `$_` (the current element) could either be a valid number, or some other string. If it's a number, I want `$n` to be the value of that number minus 1 (as a number, not a string). If it's not, I want `$n` to be false-y.

PowerShell usually tries to coerce the right-hand value to the type of the left side, but it can depend on the operation. For addition, `"10"+5` would give you a new string, `"105"`, whereas `10+"5"` will give you an integer (`15`).

But strings can't be subtracted so instead PowerShell can infer the numeric value automatically with a string on the left side of subtraction, therefore `"10"-5` gives `5`.

SO, I start with `$_-1`, which will give me the number I want when `$_` is actually a number, but when it's not I get nothing. On the surface, "nothing" is falsey, but the problem is that is stops execution of that assignment, so `$n` will retain its previous value; not what I want!

If I wrap it in a subexpression, then when it fails, I get my falsey value: `$($_-1)`.

That all gets assigned to `$n` and since that assignment is itself wrapped in parentheses, the value that was assigned to `$n` also gets passed through to the pipeline.

Since I'm using it in the indexer, and I want `1` if the conversion succeeded, I use two boolean-`not` expressions `!!` to convert this value to boolean. A successful number conversion ends up as true, while the falsey nothingness gives us that sweet, sweet `0` that allows for returning the only element in that fake ternary array.

Getting back to that array, the element is this: ~~`$("$($_[0])"*$n*$_)`~~ `$(,$_[0]*$n+$_)`

~~`"$($_[0])"` \- this is an annoyingly long way of getting the first character of the current element (let's say, getting `+` from `+[>+`), but as a string and not as a `[char]` object. I need it to be a string because I can multiply a string by a number to duplicate it, but I can't do that with a character.~~

Actually I managed to save 4 characters by using a `[char]` array instead of a string (by using another unary comma `,`), so I was able to remove the quotes and extra sub-expression. I *can* multiply an array to duplicate its elements. And since the entire result of this iteration ends up being an array anyway and needs to be `-join`ed, using an array here incurs no additional cost.

Then, I multiply that ~~string~~ array by `$n`, to duplicate it `$n` times. Recall that `$n` could be `$null` or it could be the value of the preceding digits minus one.

Then `+$_` adds the current element onto the end of the duplicated first character of that element. That's why `$n` is minus one.

This way, `10+[>+` ends up with `$n` equal to 9, then we make 9 `+`'s and add that back to the `+[>+` string to get the requisite 10, plus the other single elements along for the ride.

The element is wrapped in a subexpression `$()` because when `$n` is `$null`, the entire expression fails, so creating the array fails, so the indexer never runs, so `$n` never gets assigned.

The reason I used this ternary trick is because of one of its peculiarities: unlike a real ternary operator, the expressions that define the elements *do* get evaluated whether or not they are "selected", and first for that matter.

Since I need to assign and then use `$n` on separate iterations, this is helpful. The ternary array element value gets evaluated with the previous iteration's `$n` value, then the indexer re-assigns `$n` for the current iteration.

So the `ForEach-Object` loops ends up outputting everything its supposed to (a bunch of errors we ignore), but as an array of new strings.

So that whole thing is wrapped in parentheses and then preceded by unary `-join` to give the output string.
> 2 votes

# Answer
# QuadR, 17 bytes

```
\d+.
¯1((⍎↓)⍴↑)⍵M

```

Try it online!

Thanks to Adám for providing the correct version of the code.

### How it works:

```
\d+.          ⍝ Regex to match any sequence of digits followed by a character.
¯1((⍎↓)⍴↑)⍵M  ⍝ Transformation line
¯1(      )⍵M  ⍝ Arguments: -1 and the matching expression
   ( ↓)       ⍝ 'Drop' the last item (-1) from the match (⍵M), yielding a string which is a sequence of digits.
    ⍎         ⍝ Execute. In this case, it transforms a string into a number.
        ↑     ⍝ 'Take' the last item (-1) from the match (⍵M), yielding a character.
       ⍴      ⍝ Reshape it. That will take the character resulting from the 'Take' operation and repeat it n times,
              ⍝ where n is the result from the 'Drop' and 'Execute' operations.

```
> 2 votes

# Answer
# Proton, 50 bytes

```
x=>/\d+./.sub(k=>int((e=k.group())[to-1])*e[-1],x)

```

Try it online!
> 1 votes

# Answer
# Java 8, 148 bytes

```
s->{for(s=s.format(s.replaceAll("(\\d+)","%1\\$0$1d"),0);!s.matches("\\D+");s=s.replaceAll("0(\\D)","$1$1"));return s.replaceAll("((.)+)\\2","$1");}

```

~~*Gdamn*~~ Java regexes are so useless sometimes.. Last time it was lack of using the capture group `"$1"` for anything, now this.. I want to replace `3c` with `ccc` or `000c` with `ccc` as a one-liner, but unfortunately Java has no way of doing this without a loop. Ah well.

**Explanation:**

Try it here.

```
s->{                          // Method with String as both parameter and return-type
  for(s=s.format(s.replaceAll("(\\d+)","%1\\$0$1d"),0);
                              //  Replace every numbers of that many zeroes
                              //  (i.e. "3>2+" -> "000>00+")
      !s.matches("\\D+");     //  Loop as long as the String contains zeroes
    s=s.replaceAll("0(\\D)",  //   Replace every 0 followed by a non-0 character,
                   "$1$1")    //   with two times this captured non-0 character
  );                          //  End of loop
  return s.replaceAll("((.)+)\\2","$1");
                              //  Reduce every repeated character amount by 1,
                              //  and return this as result
}                             // End of method

```
> 1 votes

# Answer
# , 151 bytes

Outgolfed by user2390246! This is now basically a garbage approach compared to that one, but I'll continue to improve it.

```
function(s,G=substr)for(i in el(strsplit(gsub("(\\d+.)","!\\1!",s),"!")))cat("if"(is.na(g<-as.double(G(i,1,(n=nchar(i))-1))),i,rep(G(i,n,n),g)),sep='')

```

Try it online!

Also outputs a bunch of warnings.

```
function(s){
s <- gsub("(\\d+.)","!\\1!",s)               # surround groups with !
X <- el(strsplit(s,"!"))                   # split to groups
for( i in X ){                             # iterate over groups
 n <- nchar(i)                             # length of group
 r <- substr(i,1,n-1)                      # potential number (first n-1 chars)
 d <- substr(i,n,n)                        # last character
 if( is.na(as.double(r)) ){                # if it's not a number
   cat(i)                                  # print out the whole string
  } else {
   cat(rep(d,as.double(r)),sep="")         # repeat d r times, and print with no separator
  }
 }
}
```

Next up, seeing if using a `grep` is more efficient than `substr`
> 1 votes

# Answer
# Haskell, 84 bytes

```
f s@(x:r)|(n:m,x:r)<-span(`elem`['0'..'9'])s=(x<$[1..read$n:m])++f r|1<3=x:f r
f e=e

```

Try it online!

**Explanation:**

`span(`elem`['0'..'9'])s` splits the given string `s` into a prefix of digits and the remainder. Matching on the result on the pattern `(n:m,x:r)` ensures that the digit prefix is non-empty and binds the character after the digits to `x` and the remainder to `r`. `x<$[1..read$n:m]` reads the string of digits `n:m` as number and repeats `x` that many times. The result is concatenated to the recursive treatment of the remaining string `r`.
> 1 votes

# Answer
## JavaScript (ES6), 46 bytes

```
a=>a.replace(/(\d+)(.)/g,(_,n,b)=>b.repeat(n))

```

Pretty straightforward explanation:

```
a=>a.replace(/(\d+)(.)/g,                      // Match globally the following: a number N followed by a character
                         (_,n,b)=>b.repeat(n)) // Replace each occurrence by the matched character repeated N times

```
> 1 votes

# Answer
# Ruby, 35 bytes

```
->s{s.gsub(/(\d+)(.)/){$2*$1.to_i}}

```

Try it online!
> 1 votes

# Answer
## C++, ~~239~~ 235 bytes

-4 bytes thanks to Zacharý

```
#include<regex>
using s=std::string;std::regex m("[0-9]*[<>+.,\\[\\]-]");s t(s r){s d,h;std::sregex_iterator i(r.begin(),r.end(),m),e;while(i!=e){h=(*i)[0];int g=std::strtol(h.data(),NULL,10);g+=!g;d+=s(g,h[h.size()-1]);++i;}return d;}

```
> 1 votes

# Answer
## Untyped Lambda Calculus, 452 bytes

```
(λp.λq.(λb.λg.(λi.(λp.λq.λb.p q b)(q(λq.λj.λl.j((λq.λj.qλq.λl.(λu.g i j(λp.u)(g j(λq.λg.q(b(p(λp.λq.p q))(p(λp.λq.p(p q)))q g))(λp.u)(λu.u qλq.λu.g j i q(b l(p(λp.λq.p(p(p(p q)))))q u))))λp.p(λp.λb.q p((λp.λq.l(λp.l)(λp.λq.p q)(λq.p j q)q)p b))λp.λp.p)l q))(λp.p)(λp.p(λp.λp.p)λp.λp.p)(λp.λq.p)))(b(p(λp.λp.p))(p(λp.λq.p(p q)))))(λp.λq.λb.p(q b))λp.λq.q(λp.λq.λb.p(λp.λb.b(p q))(λp.b)λp.p)p)λp.λq.λb.q(q(q(q(q(q(p q b))))))

```

Input and output comprise of right-fold lists of church encoded character codes, for example the character code of a newline is 10 so the church encoding would be `λf.λx.f(f(f(f(f(f(f(f(f(f x)))))))))`. Converting "ABCD" to a list looks like `λf.λx.f 65 (f 66 (f 67 (f 68 x)))` but with the numbers church-encoded.

Applying an encoded string to the program and reducing it all the way should give you an encoded output string with the RLE applied.
> 1 votes

# Answer
# Funky, 42 bytes

```
s=>s::gsub("(\\d+)(.)",(_,a,b)=>b::rep(a))

```

Try it online!
> 1 votes

# Answer
# Stax, 24 bytes

```
▒tP☻↕╘`¼½ª√ΘBöQm>\%▒IïR}

```

Run and debug it

Regex replace and execute.
> 1 votes

# Answer
# ///, 114 bytes

```
/a/*l//b/l*//l/\/\///1/0a2/1a3/2a4/3a5/4a6/5a7/6a8/7a9/8a*0/9a0*/|l0l/|l/*>/>>b</<<b+/++b-/--b[/[[b]/]]b,/,,b./../

```

Try it online!

This is fairly trivial program as far as actual algorithm, it just happens that repeating characters is a strong suit of ///.

If you change the specification of the RLE, then its 106 bytes.

# ///, 106 bytes

```
/b/l*//a/*l//l/\/\///1/0a2/1a3/2a4/3a5/4a6/5a7/6a8/7a9/8a*0/9a0l/*>/>>b</<<b+/++b-/--b[/[[b]/]]b,/,,b./../

```

Try it online!

A 0 will never occur, and a 1 just adds a byte. 2 is the first number where anything is actually compressed, so it makes much more sense to start at that number. In other words, subtract 1 from each number. This is was the original program, just without the code to subtract one. It takes up so much space because there is an indeterminate amount of zeros at the beginning of each number, depending on the number of digits. If I just used `/0*//` to delete a zero and subtract one, it would delete one for each 0 instead. So it has to add another symbol like this `/0*/|/`, then remove that symbol `/|//`, then remove the `0`s `/0//`.

Commented version
> 1 votes

# Answer
## Dart, 78 bytes (with regex), 102 bytes (without regex)

With Regex:

```
(i)=>i.splitMapJoin(new RegExp(r"(\d+)(.)"),onMatch:(m)=>m[2]*int.parse(m[1]))

```

Without Regex:

```
(i,[n=0,d=0])=>i.codeUnits.map((c)=>i[d++]*((c-=48)>=0&&c<10?0*(n=n*10+c):n<1?1:(n=0*(c=n))+c)).join()

```

Both must be invoked like `(<code here>)("input string")`.

Regex one is quite standard, but the regex-less one is quite special.

Regex-less abuses optional parameters to allocate local variables in "single return" function, otherwise you'd need to make a block and have the return keyword. For each code unit, if the code unit is between 0 and 9 it is accumulated to `n` and an empty string is returned. Otherwise, the the character is multiplied by the value of `n` (special cased if n == 0, in that case it will always emit 1 character) and `n` is set to 0. `(n=0*(c=n))+c` sets the char code argument to the value of `n`, multiplies `n`/`c` with 0, stores 0 to `n`, then adds `c`. This resets our `n` without being in a statement context.
> 0 votes

# Answer
# Python3, 96 bytes

```
s,r=input(),""
while s:
 d=0
 while"/"<s[d]<":":d+=1
 r+=int(s[:d] or 1)*s[d];s=s[d+1:]
print(r)

```

I tried another implementation in Python, but i don't beat https://codegolf.stackexchange.com/a/146923/56846 :(
> 0 votes

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


title: CSI: Minecraft Items

text:
# Question
Title: CSI: Minecraft Items
Minecraft 1.12 will be released tomorrow, so let's celebrate!

Write code that takes in a non-negative integer N which represents the number of items of something in Minecraft. Output it in a way more helpful to players, giving the number of chests, stacks, and items N is equivalent to. Use the format

```
XcYsZi

```

where

* `X` is the number of chests you can completely fill with N items,
* `Y` is the number of stacks you can fill with the items remaining after filling chests,
* `Z` if the number of items remaining after filling chests and stacks.

Note that:

* 64 items fit in a stack. (We'll ignore items that stack to 16 or don't stack.)
* 27 stacks fit in a chest. (These are single chests, not double chests.)

So it would never make sense if `Y` is more than 26 or if `Z` is more than 63.

A caveat with the format is that if there is zero of something, that term is not printed.

* So, for example, if `Y` were zero and `X` and `Z` nonzero, the format would look like `XcZi`.
* Likewise if `Y` and `Z` were zero and `X` nonzero, the format would be `Xc`.
* **The exception here is when N is zero.** Then `0i` is the output rather than an empty string.

You can assume all N items are of the same type, hence all stackable.

You may not output a list or tuple of three numbers. You must give a string with the exact "csi" notation, in that order, with no spaces or commas.

For reference, here's a chest completely filled with stacks of items:

# Testcases

```
in -> out
0 -> 0i
1 -> 1i
2 -> 2i
62 -> 62i
63 -> 63i
64 -> 1s
65 -> 1s1i
66 -> 1s2i
127 -> 1s63i
128 -> 2s
129 -> 2s1i
200 -> 3s8i
512 -> 8s
1337 -> 20s57i
1664 -> 26s
1727 -> 26s63i
1728 -> 1c
1729 -> 1c1i
1791 -> 1c63i
1792 -> 1c1s
1793 -> 1c1s1i
4096 -> 2c10s
5183 -> 2c26s63i
5184 -> 3c
5200 -> 3c16i
9999 -> 5c21s15i
385026 -> 222c22s2i
1000000000 -> 578703c19s

```

**The shortest code in bytes wins.**

# Answer
> 11 votes
# Jelly,  ~~26~~  24 bytes

```
d64d1¦27Fża¥“csi”Fḟ0ȯ⁾0i

```

A full program taking the number and printing the result.
It does seem too long to me...

**Try it online!** or see the test suite.

### How?

*updating...*

```
d64d1¦27Fża¥“csi”Fḟ0ȯ⁾0i - Main link: number n
 64                      - literal 64
d                        - divmod (whole divisions and remainder)
      27                 - literal 27
    1¦                   - apply to index 1 (the whole division from above)
   d                     - divmod
        F                - flatten into a single list (of three items i.e. [(n/64)/27, (n/64)%27, n%64]
            “csi”        - literal ['c','s','i']
           ¥             - last two links as a dyad:
         ż               -   zip
          a              -   logical and (any 0s in the divmod result become [0,0], others become [integer, character]
                 F       - flatten (from list of three lists to one list)
                  ḟ0     - filter discard zeros
                     ⁾0i - literal ['0','i']
                    ȯ    - logical or (non-vectorising)
                         - implicit print (smashed together representation, so [578703,'c',19,'i'] prints as 578703c19i)

```

# Answer
> 7 votes
# Retina, ~~49~~ ~~48~~ 41 bytes

```
.+
$*i
i{64}
s
s{27}
c
(.)\1*
$.&$1
^$
0i

```

Try it online! Includes all test cases except the last, in case it overloaded TIO. Edit: Saved 7 bytes thanks to @MartinEnder. Explanation:

```
.+
$*i

```

Convert the input number to unary using `i`s.

```
i{64}
s

```

64 items fill one stack.

```
s{27}
c

```

27 stacks fill one chest.

```
(.)\1*
$.&$1

```

Convert any chests, stacks or remaining items to decimal, but leaving the type as a suffix.

```
^$
0i

```

If the input was zero, make the result `0i`.

# Answer
> 4 votes
# 05AB1E, 24 bytes

```
1728‰`64‰)˜…csiøvyJ¬0Êi?

```

Try it online!

**Explanation**

```
1728‰                      # input divmod 1728 (64*27)
     `                     # split as separate with mod result on top of stack
      64‰                  # divmod 64
         )˜                # wrap stack in flattened list
           …csiø           # zip with the string "csi"
                vy         # for each
                  J        # join amount with storage-type
                   ¬0Êi    # if head != 0
                       ?   # print

```

# Answer
> 4 votes
# C#, 84 86 bytes

```
_=>(_/1728>0?_/1728+"c":"")+((_-=_/1728*1728)/64>0?_/64+"s":"")+(_%64>0?_%64+"i":"")

```

Notice the inline subtraction, didn't realize it was possible but `i--` made sense so why not `i-=10`

# Edit:

```
_=>_>0?(_/1728>0?_/1728+"c":"")+((_%=1728)/64>0?_/64+"s":"")+(_%64>0?_%64+"i":""):"0i"

```

for 0 edge case and suggestion.

# Answer
> 3 votes
# Python 3, 87 bytes

```
lambda n:g(n//1728,"c")+g(n//64%27,"s")+g(n%64,"i")or"0i"
g=lambda n,s:(str(n)+s)*(n>0)

```

Try it online!

# Answer
> 3 votes
# C, 85 ~~87~~ ~~105~~ ~~110~~ ~~111~~ ~~112~~ bytes

```
#define a(x,y)x?printf("%d%c",x,y+99):0;
f(z){a(z/1728,0)a(z%1728/64,16)!z+a(z%64,6)}

```

Try it here.

The code even works properly on negative numbers. You may now owe server OP blocks!

# Answer
> 3 votes
## JavaScript (ES6), ~~77~~ 76 bytes

```
n=>[n+1,1728,64,1].map((v,i,a)=>(v=n%a[--i]/v|0)?v+'csi'[i]:'').join``||'0i'

```

### Test cases

```
let f =

n=>[n+1,1728,64,1].map((v,i,a)=>(v=n%a[--i]/v|0)?v+'csi'[i]:'').join``||'0i'

console.log(f(0)) // -> 0i
console.log(f(1)) // -> 1i
console.log(f(2)) // -> 2i
console.log(f(62)) // -> 62i
console.log(f(63)) // -> 63i
console.log(f(64)) // -> 1s
console.log(f(65)) // -> 1s1i
console.log(f(66)) // -> 1s2i
console.log(f(127)) // -> 1s63i
console.log(f(128)) // -> 2s
console.log(f(129)) // -> 2s1i
console.log(f(200)) // -> 3s8i
console.log(f(512)) // -> 8s
console.log(f(1337)) // -> 20s57i
console.log(f(1664)) // -> 26s
console.log(f(1727)) // -> 26s63i
console.log(f(1728)) // -> 1c
console.log(f(1729)) // -> 1c1i
console.log(f(1791)) // -> 1c63i
console.log(f(1792)) // -> 1c1s
console.log(f(1793)) // -> 1c1s1i
console.log(f(4096)) // -> 2c10s
console.log(f(5183)) // -> 2c26s63i
console.log(f(5184)) // -> 3c
console.log(f(5200)) // -> 3c16i
console.log(f(9999)) // -> 5c21s15i
console.log(f(385026)) // -> 222c22s2i
console.log(f(1000000000)) // -> 578703c19s
```

# Answer
> 2 votes
# Java 8, 86 bytes

```
i->i>0?(i/1728>0?i/1728+"c":"")+((i%=1728)/64>0?i/64+"s":"")+((i%=64)>0?i+"i":""):"0i"

```

Try it here.

# Answer
> 2 votes
# CJam, 31 bytes

```
ri64md\27md@]"csi"]z{0=},"0i"e|

```

Try it online!

### Explanation

```
ri                               e# Read an int from input.
  64md                           e# Divmod by 64, gives total #stacks, #items.
      \27md                      e# Divmod total #stacks by 27, gives #chests, #stacks.
           @                     e# Bring #items back to top.
            ]                    e# Wrap in an array: [#chests, #stacks, #items]
             "csi"               e# Push "csi".
                  ]z             e# Zip with the other array.
                    {0=},        e# Filter out subarrays where the first element is 0.
                         "0i"e|  e# Logical or with "0i". An input of 0 gives an empty array
                                 e# from the rest of the program, in that case yield "0i"
                                 e# instead.

```

# Answer
> 2 votes
# ///, 179 bytes

```
/|/\/\///b/l0|d/11|x/dddd|sbxxxxxxxx/1sb|cbxxxd1/1cb|bxd/1b|d/2|2222/8|222/6|22/4|21/3|81/9|61/7|41/5|bc/gc|cb/c|bs/gs|sb/s|bi/gi|b|/g/0|mc/m|ms/m|mi/0i|m|/si/s|cs/c|ci/c/mcl0sl0i

```

Try it online!

Input is taken in unary `1`s at the end of the program right before the `i`.
Ex:

```
.../si/s|cs/c|ci/c/mcl0sl0<--input here-->i

```

You can also use an `x` in place of 8 `1`s as a side affect of golfing the program. There is a wrapper for easier testing below.

Testing wrapper: Try it online!

Ungolfed: Try it online!

It does 2 divmods, one to separate into chests, stacks, and items, then again to convert to decimal. I could have it convert input from decimal as well, but I would also have to change all of the symbol names and add additional logic to keep it from breaking, so I'm not going to do that. Besides, I think unary is a recognized standard input for ///.

# Answer
> 1 votes
# Batch, <sub>~~347 335 283 246 234 202 199 191~~</sub> 189 bytes

```
@set/al=%1,c=%1/1728,l-=c*1728,s=l/64,l-=s*64
@set c=%c%c
@set s=%s%s
@set i=%l%i
@if %c%==0c set c=
@if %s%==0s set s=
@if %i%==0i set i=
@if %c%%s%%i%.==. set i=0i
@echo(%c%%s%%i%

```

# Answer
> 1 votes
# JavaScript (ES6) 71 bytes

```
n=>[n/1728|0,(n/64|0)%27,n%64].map((a,i)=>a?a+'csi'[i]:'').join``||'0i'

```

**Snippet:**

```
f=
n=>[n/1728|0,(n/64|0)%27,n%64].map((a,i)=>a?a+'csi'[i]:'').join``||'0i'

console.log(f(0)) // 0i
console.log(f(1)) // 1i
console.log(f(2)) // 2i
console.log(f(62)) // 62i
console.log(f(63)) // 63i
console.log(f(64)) // 1s
console.log(f(65)) // 1s1i
console.log(f(66)) // 1s2i
console.log(f(127)) // 1s63i
console.log(f(128)) // 2s
console.log(f(129)) // 2s1i
console.log(f(200)) // 3s8i
console.log(f(512)) // 8s
console.log(f(1337)) // 20s57i
console.log(f(1664)) // 26s
console.log(f(1727)) // 26s63i
console.log(f(1728)) // 1c
console.log(f(1729)) // 1c1i
console.log(f(1791)) // 1c63i
console.log(f(1792)) // 1c1s
console.log(f(1793)) // 1c1s1i
console.log(f(4096)) // 2c10s
console.log(f(5183)) // 2c26s63i
console.log(f(5184)) // 3c
console.log(f(5200)) // 3c16i
console.log(f(9999)) // 5c21s15i
console.log(f(385026)) // 222c22s2i
console.log(f(1000000000)) // 578703c19s
```

# Answer
> 1 votes
# Python 2, 82 bytes

I converted Gabor Fekete's comment from above into a working example:

```
lambda n:g(n/1728,"c")+g(n/64%27,"s")+g(n%64,"i")or"0i"
g=lambda n,s:(`n`+s)*(n>0)

```

Try it online!

# Answer
> 1 votes
# dc, 76 bytes

```
?dddsf[1728/n99P]sc1728/0<c1728%ddd[64/n115P]si64/0<i[64%n105P]sy64%0<ylf0=y

```

Try it online!

# Answer
> 0 votes
# Braingolf, 71 bytes

```
V"isc"R#@!%>93*!*,>,>!/!*,>,$_-,>,>,/<$_<&,!?_v@R:>|!?_v@R:>|!?_v@R:>|;

```

Try it online!

Not at all golfy, but it works

# Answer
> 0 votes
# PHP, 84 bytes

```
<?=($c=($a=$argn)/1728^0)?$c.c:"",($s=$a/64%27)?$s.s:"",($i=$a%64)||$c+$s<1?$m.i:"";

```

Try it online!

# PHP, 93 bytes

```
$i-=64*$s=($i-=1728*$c=($i=$argn)/1728^0)/64^0;echo$c?$c.c:"",$s?$s.s:"",$i||$c+$s<1?$i.i:"";

```

Try it online!

# Answer
> 0 votes
# Mathematica, 155 bytes

```
A=AppendTo;G={};P=Print;(z=Mod[t=Mod[#,1728],64];If[(x=⌊#/1728⌋)>0,A[G,{x,c}]];If[(y=⌊t/64⌋)>0,A[G,{y,s}]];If[z>0||#==0,A[G,{z,i}]];Row@Flatten@G)&

```

# Answer
> 0 votes
# T-SQL, ~~139 134~~ 139 bytes

Input is stored in column *a* of pre-existing table *t*.

```
SELECT IIF(a=0,'0i',REPLACE(IIF(a<1728,'',STR(a/1728)+'c')
                           +IIF(a%1728<64,'',STR(a%1728/64)+'s')
                           +IIF(a%64=0,'',STR(a%64)+'i'),' ',''))FROM t

```

Line breaks for readability, not counted in byte total. Tested on MS SQL Server 2012.

**EDIT 1:** Changed multiple `REPLACE` to `IIF` to save 5 bytes. Final `REPLACE` still necessary because `STR` annoyingly pads with spaces to 10 chars.

**EDIT 2:** Fixed to follow the rules by using the approved input type for SQL, values stored in a named table. This cost bytes for the `FROM`, also requires `SELECT` instead of `PRINT`. Recovered 2 bytes by dropping an unnecessary parens.

# Answer
> 0 votes
# PowerShell, 113 Bytes

```
param($i)("$(($c=[math]::floor($i/1728)))c","")[!$c]+("$(($s=[math]::floor(($i%1728)/64)))s","")[!$s]+"$($i%64)i"

```

This hits a bunch of powershell's pain points very precisely.

`[math]::Floor` is required for this as PS does Bankers Rounding by default.

the PS Ternary also takes up a load of bytes compared to other languages, to do a simple null coallescence (`$a="This";$a?$a:"That"` or `"This"?:"That"`) we need to do `(($a="This"),"That")[$a-ne$null]`

then we need to use all of these twice, and also add in another set of brackets in some places due to powershell's default operation order.

# Answer
> 0 votes
# Python 2, 77 bytes

```
lambda n:''.join(`k`+c for k,c in zip([n/1728,n/64%27,n%64],'csi')if k)or'0i'

```

Try it online!

# Answer
> 0 votes
# Jelly, 21 bytes

```
d64d1¦27FµTȯ3ịż“csi”$

```

Try it online!

Like Jonathan Allan's essentially-the-same answer before it, this does seem too long.

Even more essentially the same:

# Jelly, 21 bytes

```
d64d1¦27Fż“csi”ẠƇȯ⁾0i

```

Try it online!

---
Tags: code-golf, math, arithmetic, game, integer
---


title: Repair the ranges

text:
# Question
Title: Repair the ranges
Given an input of a list of positive integers with some replaced with `0`, output the list with the missing numbers that were changed to `0` replaced.

Characteristics of the input list:

* The list will always have a length of at least 2.
* Let us define the input list as `a` and the "original list" (that is, the list before numbers were replaced with `0`s) as `b`. For any `n`, `a[n]` is either `b[n]` or `0`.
* For any `n`, `b[n]` is either `b[n-1] + 1` or `b[n-1] - 1`. That is, the numbers in `b` will always change by `1` at each index from its previous. The first element is, of course, exempt from this rule.
* For every run of zeroes in `a` (that is, consecutive elements replaced with `0`), with `x` representing the index of the start of the run and `y` representing the end, `a[x-1]` to `a[y+1]` will always be either solely increasing or solely decreasing. Therefore, there will only be one possible way to fill in the zeroes.

+ This also means that neither the first nor the last element of the array can be zeroes.

In simpler terms, to fill in a run of zeroes, simply replace it with a range from the number before to the number following it. For example, an input of

```
1 2 0 0 0 6 7

```

must output

```
1 2 3 4 5 6 7

```

Since this is , the shortest code in bytes will win.

Test cases:

```
In                      Out
-----------------------------------------------------
1 0 0 0 5 6 0 4 0 0 1 | 1 2 3 4 5 6 5 4 3 2 1
7 6 0 0 3 0 0 0 7 0 5 | 7 6 5 4 3 4 5 6 7 6 5
1 0 3 0 5 0 3 0 5 0 7 | 1 2 3 4 5 4 3 4 5 6 7
14 0 0 0 0 0 0 0 0 23 | 14 15 16 17 18 19 20 21 22 23

```

# Answer
> 15 votes
# JavaScript (ES6), ~~72 66 64 54~~ 53 bytes

*Saved 12 bytes thanks to @Neil!*

*Saved 1 byte thanks to @IsmaelMiguel*

```
a=>a.map((l,i)=>l?b=l:b+=a.find((q,r)=>r>i&&q)>b||-1)

```

Pretty good for JavaScript.

---

Try it online (all browsers work)

## Explanation

```
a=>  // Function with arg `a`
  a.map((l,i)=>  // Loop through input
    l?             // If nonzero
      b=l          // Set `b` to current number
    :a.find((q,r)=>r>i&q) // Otherwise look for the next nonzero number
     >b?           // If it's increased since nonzero last number
       ++b:--b)    // Increasing? increase `b` (the previous nonzero number)
                   // otherwise decrease `b`

```

# Answer
> 7 votes
# MATL, 11 ~~12~~ bytes

```
fGXzGn:3$Yn

```

Works with current release (13.0.0) of the language/compiler.

**Try it online!**

```
f        % implicitly input array. Indices of nonzero elements (*)
GXz      % push input and get its nonzero elements (**)
Gn:      % vector [1,2,...,n], where n is input length (***)
3$Yn     % interpolate at positions (***) from data (**) defined at positions (*)

```

# Answer
> 7 votes
## Haskell, ~~68~~ ~~61~~ 58 bytes

```
g(a:b:r)=[a..b-1]++[a,a-1..b+1]++g(b:r)
g x=x
g.filter(>0)

```

Usage example: `g.filter(>0) $ [7,6,0,0,3,0,0,0,7,0,5]`-\> `[7,6,5,4,3,4,5,6,7,6,5]`.

How it works: remove zeros from the input, then call `g`. Let `a` be the first and `b` then second element of the remaining list. Concatenate the lists from `a` upwards to `b-1` and from `a` downwards to `b+1` (one of them will be empty) and a recursive call with `a` dropped.

Edit: @Zgarb saved 3 bytes. Thanks!

# Answer
> 6 votes
# Mathematica, 59 bytes

```
#//.{a___,x_,0..,y_,b___}:>{a,##&@@Range[x,y,Sign[y-x]],b}&

```

**Test case**

```
%[{1,0,3,0,5,0,3,0,5,0,7}]
(* {1,2,3,4,5,4,3,4,5,6,7} *)

```

# Answer
> 4 votes
# Perl, 47 45 44 39 37 bytes

Includes +1 for `-p`

```
s%\S+%$p+=/\G(0 )+/?$'<=>$p:$&-$p%eg

```

Expects the list on stdin. Example: echo 1 0 3 0 1 | perl -p file.pl

# Answer
> 3 votes
# Jelly, ~~12~~ 11 bytes

```
ḢWW;ḟ0Ṫr¥\F

```

Try it online!

### Alternative version, 8 bytes (non-competing)

Unfortunately, Jelly's `pop` did not cast to iterable, in the latest version that predates this challenge. This has been fixed, and the following works in the current version.

```
ḟ0Ṫr¥\FḊ

```

Try it online!

### How it works

```
ḢWW;ḟ0Ṫr¥\F  Main link. Input: A (list)

Ḣ            Pop the first element of A. Let's call it a.
 WW          Yield [[a]].
   ;         Concatenate with the popped A.
             This wraps the first element of A in an array.
    ḟ0       Filter; remove all zeroes.
        ¥    Create a dyadic chain:
      Ṫ        Pop the last element of the left argument.
       r       Call range on the popped element and the right argument.
         \   Reduce the modified A by this chain.
          F  Flatten the resulting list of ranges.

```

In the alternate version, `ḢWW;` becomes unnecessary. However, since the first element is cast to iterable before popping, it is not actually modified. The final  removes the duplicate of the first element.

# Answer
> 3 votes
# Retina, ~~39~~ ~~34~~ 31 bytes

*3 bytes saved thanks to @Martin.*

```
+`1(1*) (?= +((1)\1)?)
$0$1$3$3

```

Takes input and gives output in unary.

The code iteratively fills every empty place (0's) with `previous_number - 1 + 2 * if_next_nonzero_number_bigger`. `previous_number - 1` is `$1` and `if_next_nonzero_number_bigger` is `$3`.

With decimal I/O the code is 51 bytes long as you can see in the online interpreter with all the test cases.

# Answer
> 2 votes
# GNU Sed (with `exec` extension using bash), 61

Score includes +1 for `-r` option to sed.

```
:
s/( 0)+ /../
s/\w+..\w+/{&}/
s/.*/bash -c 'echo &'/e
/ 0/b

```
* Find runs of `0`s and replace them `..`
* Put braces around the endpoint numbers to create a bash brace expansion like `{1..4}` for the local endpoints. The beauty of bash brace expansions here is that the generated sequence will always run in the right direction, regardless of whether the start or end is larger.
* Use the `e` option to the `s` command to call out to bash to evaluate this brace expansion
* If any more `0`s are found, jump back to the start.

Ideone.

# Answer
> 2 votes
# Python 2, ~~195~~ 111 bytes (thanks Alex!)

```
t=input()
z=0
for i,e in enumerate(t):
 if e:
  while z:t[i-z]=e+z if l>e else e-z;z-=1
  l=e
 else:z+=1
print t

```

Input: must be a `[list]` of ints
Output: `[list]` of ints

# Answer
> 2 votes
# Jelly, 8 bytes

```
ḟ0rƝṖ€Fo

```

Try it online!

# Answer
> 1 votes
# Perl, ~~85~~ 82 bytes

*includes +1 for `-p`*

```
s/(\d+)(( 0)+) (\d+)/$s=$1;$e=$4;$_=$2;$c=$s;s!0!$c+=$e<=>$s!eg;"$s$_ $e"/e&&redo

```

Expects the list on stdin. Example: `echo 1 0 3 0 1 | perl -p file.pl`.

This uses a nested regexp. Somewhat readable:

```
s/(\d+)(( 0)+) (\d+)                  # match number, sequence of 0, number
 /
    $s=$1;                            # start number
    $e=$4;                            # end number
    $_=$2;                            # sequence of ' 0'
    $c=$s;                            # initialize counter with start number
    s!0! $c += $s <=> $e !eg          # replace all 0 with (in|de)cremented counter
    "$s$_ $e"                         # return replacement
 /e
&& redo                               # repeat until no more changes.

```

# Answer
> 1 votes
# Python 2, ~~92~~ 88 bytes

(Removed intermediate variable)

```
t=filter(bool,input())
print sum([range(o,p,cmp(p,o))for o,p in zip(t,t[1:])],[])+t[-1:]

```

# Answer
> 1 votes
# Pyth, 17 bytes

```
u+G+treGHHfTtQ[hQ

```

The way it works:

```
u                 reduce
              [hQ     seed: the first element of input, in a list
                      iterable:
          tQ              all except the first element of input
        fT                remove if 0
                      lambda: G is the list to be returned, H is the current item
 +G                       append to return list
    reGH                  a range from the last element of the return list and the current item
   +                      concatenated with
        H                 the last item (this step forms a bidirectional inclusive list)

```

In other words: all zeroes are removed from input, then an exclusive range is inserted between every element. This range is zero length on elements only one apart.

# Answer
> 1 votes
# 05AB1E, 3 bytes

This was a feature added after the challenge. Code:

```
0KŸ

```

Explanation:

```
0K   # Remove all zeroes from the input list
  Ÿ  # Rangify, [1, 4, 1] would result into [1, 2, 3, 4, 3, 2, 1]

```

Try it online! or Verify all test cases!

# Answer
> 1 votes
# Vim: 231 Key Commands

Note that any ^ preceding a character means you should hold control while typing that character

```
mbomayiwo^V^R"^V^V^V^X ^V^["sy0dd`a@f ^["bc0yiwo^V^V^V^X^V^R"^V^[0l@sa^V^V^V^A-^V^[0f-"ayhdd`a@i ^["dc0mbyiwo^V^R"Exe@b^V^[0fel"ty2ldd`b@t ^["ec0wmbyiwo@f @d^V^[@z ^["fc0"xyiwwmbyiwocw^V^V^V^Rx^V^V^V^[@a@i @e^V^[@z ^["ic0IB0 B^V^R" ^V^OWB0 ^V^OA B0^V^[0*w"tyiWdd`b@t ^["zd0dd`bAe^[0@e

```

## Steps so you can run this too!

1. Copy the line into Vim
2. Type `:s/\^V/<Ctrl-V><Ctrl-V>/g` and press enter (the two s should give you a blue ^V)
3. Type `:s/\^R/<Ctrl-V><Ctrl-R>/g` and press enter (you should see blue ^Rs now)
4. Type `:s/\^X/<Ctrl-V><Ctrl-X>/g` and press enter (you should see blue ^Xs now)
5. Type `:s/\^O/<Ctrl-V><Ctrl-O>/g` and press enter
6. Type `:s/\^A/<Ctrl-V><Ctrl-A>/g` and press enter
7. Type `:s/\^\[/<Ctrl-V><Ctrl-[>/g` and press enter (this command is slightly different because I needed to escape the \[)
8. Type `0"yy$`. The command is now stored in the y register
9. Set up input on a line, and run with `@y`

If someone knows a better way to share the command, please let me know. I know this is lengthy, but it's the best I could come up with.

## Input/Output

The input string should be alone on any line in the file. 1 0 0 4 3 0 0 0 7

The output will simply overwrite the input string 1 2 3 4 3 4 5 6 7

## Explanation

### Algorithm

1. Start at a non-zero number, make sure it's not the last number
2. Find the next non-zero number
3. Take their difference. If the answer is negative, you should decrement to repair the range, otherwise, increment to repair the range.
4. Go back to the first character and replace each zero by incrementing/decrementing the previous number.
5. Repeat until you get to the last character

### Macros Used

@e - Check for end. The last number will have an e appended to it. If the number under the cursor has an e at the end, delete the e and stop execution. Otherwise, start an interpolation cycle with @b.

```
mbyiwo^R"Exe@b^[0fel"ty2ldd`b@t

```

@b - Begin interpolation cycle. Save the number under the cursor for a subtraction operation (@s) and then find the next non-zero term (@f)

```
mayiwo^R"^V^X ^["sy0dd`a@f

```

@s - Stores the subtraction command to use in @d. It is simply `(val)^X` where `(val)` is the number at the start of the interpolation step. This is set by the @b command.

@f - Find the next non-zero term. Write the current value to the unnamed register, then write `@f @d` on the next line, and then run @z. This will repeat this command if the number is a zero, and execute @d if it isn't.

```
wmbyiwo@f @d^[@z

```

@z - Conditional execute if unnamed register is 0. This command expects two commands on a new line in the format `command1 command2`. If the unnamed register is 0, `command1` is executed, otherwise `command2` is executed. Note that neither command can have any spaces in it.

```
 IB0 B^R" ^OWB0 ^OA B0^[0*w"tyiWdd`b@t`

```

@t - Temporary command register. Stores various commands for a short time before executing them. Used primarily in if statements.

@d - Determine interpolation direction. Subtracts the first number in the sequence from the number under the cursor (using @s). If the result is negative, the interpolation must decrement so ^X is saved to @a. Otherwise, we should increment so ^A is saved to @a. Once this is saved, move back to the beginning of this interpolate cycle and run @i to actually interpolate

```
yiwo^V^X^R"^[0l@sa^V^A-^[0f-"ayhdd`a@i

```

@a - Stores either `^A` or `^X` to increment or decrement during the interpolation step. This is set by the @d command.

@i - Interpolate. Copy the number at the current location to @x and move to the next number. If that number is zero, replace it with @x and run @a to properly modify it up or down, then repeat this command. If the number isn't a zero, we have reached the end of this interpolation cycle. A new one should be started with this number as the beginning, so run @e to check for the end and run again.

```
"xyiwwmbyiwocw^V^Rx^V^[@a@i @e^[@z

```

@x - Temporary storage register. Used in the interpolate command (@i)

### Breaking Down the keystrokes

```
mbo :Set b mark to current position and open a new line below to write macros
mayiwo^V^R"^V^V^V^X ^V^["sy0dd`a@f ^["bc0 :Write to @b and reset line

yiwo^V^V^V^X^V^R"^V^[0l@sa^V^V^V^A-^V^[0f-"ayhdd`a@i ^["dc0 :Write to @d and reset line

mbyiwo^V^R"Exe@b^V^[0fel"ty2ldd`b@t ^["ec0 :Write to @e and reset line

wmbyiwo@f @d^V^[@z ^["fc0 :Write to @f and reset line

"xyiwwmbyiwocw^V^V^V^Rx^V^V^V^[@a@i @e^V^[@z ^["ic0 :Write to @i and reset line

IB0 B^V^R" ^V^OWB0 ^V^OA B0^V^[0*w"tyiWdd`b@t ^["zd0 :Write to @z and reset line

dd`b :Delete this line and move cursor back to original line

Ae^[ :Append an e to the last number

0@e  :Move to the beginning of the line and run

```

# Answer
> 0 votes
## Python 3.5, 159 bytes

a recursive solution

```
def f(s):
 h=s[0]
 g=lambda s,h,v:h*(h[-1]==s[0])if len(s)==1else(g(s[1:],h+[h[-1]-v],-v)+g(s[1:],h+[h[-1]+v],+v))*(s[0]==0 or h[-1]==s[0])
 return g(s,[h],1)

```

## Ungolfed

```
def f(s):
    h=s[0]
    def g(s,h,v):
        if len(s)==1:
            if h[-1]!=s[0]:
                r=[]
            else:
                r=h
        else:
            if s[0]==0:
                r=g(s[1:],h+[h[-1]+v],v)
            elif h[-1]!=s[0]:
                r=[]
            else:
                r=g(s[1:],h+[h[-1]-v],-v)+g(s[1:],h+[h[-1]+v],+v)
        return r
return g(s,[h],1)

```

In the golfed solution, I replace conditions by using the fact that `h*True=h` and `h*False=[]`

## Result

```
>>> f([7, 6, 0, 0, 3, 0, 0, 0, 7, 0, 5])
[7, 6, 5, 4, 3, 4, 5, 6, 7, 6, 5]

```

# Answer
> 0 votes
# Perl 6, 54 bytes

```
{$_=$^a;1 while s/:s(\d+) 0 + (\d+)/{+~$0...+~$1}/;$_}

```

# Answer
> 0 votes
# **MATLAB, ~~39~~ ~~38~~ 37 bytes**

```
@(a)interp1(find(a),a(a>0),find(a/0))

```

Anonymous function that linearly interpolates between the points in `a`. `find(a)` is an array of indices of non-zero elements in `a` and `a(a>0)` are the positive values. Saved 1 byte thanks to a friend's suggestion of `>` rather than `~=`.

# Answer
> 0 votes
# , 32 bytes

```
{:,~[:;2<@({.+(i.@|**)@-~/)\-.&0

```

Try it online!

* `-.&0` Remove zeroes.
* `2...\` For each infix of size 2...
* `@-~/` Subtract the left from the right and...
* `(i.@|**)` Create integers `0..<size of difference>`, multiplied by `*` the sign of the difference `*`.
* `<@` And box (technical necessity for ragged arrays in J).
* `[:;` Raise the result to remove the boxes.
* `{:,~` And append the last element of the original array.

# Answer
> 0 votes
# Husk, 3 bytes

```
…fI

```

Try it online!

---
Tags: code-golf, number, array
---


title: Compute the Fibonomial Coefficient

text:
# Question
Title: Compute the Fibonomial Coefficient
## Background

The Fibonacci sequence is defined as

$$f(1) = 1 \\ f(2) = 1 \\ f(n) = f(n-1) + f(n-2)$$

The Fibonorial, similar to the factorial, is the product of the first \\$n\\$ Fibonacci numbers.

$$g(n) = f(1) \times f(2) \times ... \times f(n-1) \times f(n)$$

The Fibonomial coefficient, similar to the binomial coefficient is defined as

$$\begin{align}a(n, 0) & = 1 \\ a(n, k) & = \frac {g(n)} {g(n-k) \times g(k)} \\ & = \frac {f(n) \times f(n-1) \times ... \times f(n-k+1)} {f(1) \times f(2) \times ... \times f(k)} \end{align}$$

## Task

Your goal is to create a function or program to compute the Fibonomial coefficient given two non-negative integers \\$n\\$ and \\$k\\$ with \\$l \le n\\$.

## Test Cases

```
a(0, 0) = 1
a(1, 1) = 1
a(2, 0) = 1
a(3, 2) = 2
a(8, 3) = 1092
a(11, 5) = 1514513
a(22, 7) = 7158243695757340957617
a(25, 3) = 49845401197200
a(50, 2) = 97905340104793732225
a(100, 1) = 354224848179261915075

```

## Rules

* This is so the shortest code wins.
* Builtins are allowed.

## Related

# Answer
# Jelly, 16 bytes

```
0+⁸Ð¡1ḊP
;_/Ç€:/

```

Try it online!

Credits to Dennis for the Fibonacci-orial helper link.

```
;_/Ç€:/     Main chain,  argument: [n,r]
 _/         Find n-r
;           Attach it to original: [n,r,n-r]
   Ç€       Apply helper link to each element, yielding [g(n),g(r),g(n-r)]
     :/     Reduce by integer division, yielding g(n)//g(r)//g(n-r)

0+⁸Ð¡1ḊP    Helper link, argument: n
0+⁸Ð¡1ḊP    Somehow return the n-th Fibonacci-orial.

```
> 1 votes

# Answer
# Python 67 bytes

```
f=lambda n,a=1,b=1:n<1or a*f(n-1,b,a+b)
lambda n,k:f(n)/f(k)/f(n-k)

```

Call using `a(n,k)`. Uses @Dennis fibonorial answer (is that allowed?), and a straightforward implementation of the question otherwise.
> 4 votes

# Answer
## Haskell, 46 bytes

```
l=0:scanl(+)1l;a%0=1;a%b=(a-1)%(b-1)*l!!a/l!!b

```

Outputs floats. Generates the infinite Fibonacci list. Then, does the binomial recusion, multiplying and dividing by elements from the Fibonacci list.
> 4 votes

# Answer
# Haskell, ~~77 57 55 52~~ 50 bytes

The first line is originally coming from the Fibonacci function or sequence challenge and was written by @Anon.

The second line was added in the Fibonacci-orial challenge by @ChristianSievers.

Now I added the third line. How much further will those challenges go?=)

```
f=1:scanl(+)1f
g=(scanl(*)1f!!)
n#k=g n/g(n-k)/g k

```

Thanks for 5 bytes @xnor!
> 3 votes

# Answer
# C, 206 bytes:

```
#include <inttypes.h>
uint64_t F(x){return x<1 ? 0:x==1 ? 1:F(x-1)+F(x-2);}uint64_t G(H,B){uint64_t P=1;for(B=3;B<=H;B++)P*=F(B);return P;}main(U,Y){scanf("%d %d",&U,&Y);printf("%llu\n",G(U)/(G(U-Y)*G(Y)));}

```

Upon execution, asks for 2 space separated integers as input. The `#include` preprocessor is *required*, as without it, `uint_64` is not a valid type, and the only other way to make this work for fairly big outputs is using `unsigned long long` return types for both the `F` (Fibonacci) and `G` (Fibonorial) functions, which is much longer than just including the `<inttypes.h>` and using 3 `uint64_t` type declarations. However, even with that, it stops working correctly at input values `14 1` (confirmed by using this, which lists the first `1325` values in the Fibonomial Coefficient sequence), most likely because the Fibonacci and/or Fibnorial representation of numbers `15` and above overflow the 64-bit integer type used.

C It Online! (Ideone)
> 3 votes

# Answer
# Cheddar, ~~75~~ 64 bytes

```
a->b->(g->g((a-b+1)|>a)/g(1|>b))(n->n.map(Math.fib).reduce((*)))

```

## Usage

```
cheddar> var f = a->b->(g->g((a-b+1)|>a)/g(1|>b))(n->n.map(Math.fib).reduce((*)))
cheddar> f(11)(5)
1514513

```
> 3 votes

# Answer
# MATL, ~~25~~ 23 bytes

```
1ti2-:"yy+]vtPi:)w5M)/p

```

**Try it online!**

### Explanation

```
1t      % Push 1 twice
i2-:    % Take input n. Generate vector [1 2 ... n-2]
"       % Repeat n-2 times
  yy    %   Push the top two elements again
  +     %   Add them
]       % End
v       % Concatenate into column vector of first n Fibonacci numbers
tP      % Duplicate and reverse
i:      % Take input k. Generate vector [1 2 ... k]
)       % Apply index to get last k Fibonacci numbers
w       % Swap to move vector of first n Fibonacci numbers to top
5M      % Push [1 2 ... k] again
)       % Apply index to get first k Fibonacci numbers
/       % Divide element-wise
p       % Product of vector. Implicitly display

```
> 2 votes

# Answer
# R, 120 bytes

Some more golfing is probably be possible, so comments are of course welcomed !
I used my answer of the Fibonacci-orial question in the begining of the code :

```
A=function(n,k){p=(1+sqrt(5))/2;f=function(N){x=1;for(n in 1:N){x=prod(x,(p^n-(-1/p)^n)/sqrt(5))};x};f(n)/(f(k)*f(n-k))}

```

**Ungolfed :**

```
A=function(n,k){
p=(1+sqrt(5))/2
    f=function(N){
        x=1
        for(n in 1:N){
           x=prod(x,(p^n-(-1/p)^n)/sqrt(5))
                     }
        x
        }

f(n)/(f(k)*f(n-k))
}

```
> 2 votes

# Answer
# Java: 304 260 257

I saved some bytes by compacting the memoization function a bit and removing `f(n)` entirely, replacing it with direct array access.

```
BigInteger[]c;BigInteger a(int n,int k){m(n);return g(n).divide(g(n-k)).divide(g(k));}BigInteger g(int n){return n<3?BigInteger.ONE:g(n-1).multiply(c[n-1]);}void m(int n){c=new BigInteger[n];for(int i=0;i<n;++i)c[i]=(i<2)?BigInteger.ONE:c[i-2].add(c[i-1]);}

```

Unfortunately, `BigInteger` is required due to overflows and I had to add memoization. Even on a generation 6 i7, it was taking *way* too long to run with large inputs.

Ungolfed, with boilerplate `class` and `main` code:

```
import java.math.BigInteger;

public class ComputeTheFibonomialCoefficient {

  public static void main(final String[] args) {
    // @formatter:off
    String[][] testData = new String[][] {
      { "0", "0", "1" },
      { "1", "1", "1" },
      { "2", "0", "1" },
      { "3", "2", "2" },
      { "8", "3", "1092" },
      { "11", "5", "1514513" },
      { "22", "7", "7158243695757340957617" },
      { "25", "3", "49845401197200" },
      { "50", "2", "97905340104793732225" },
      { "100", "1", "354224848179261915075" }
    };
    // @formatter:on

    for (String[] data : testData) {
      System.out.println("a(" + data[0] + ", " + data[1] + ")");
      System.out.println("  Expected -> " + data[2]);
      System.out.print("    Actual -> ");
      System.out.println(new ComputeTheFibonomialCoefficient().a(
          Integer.parseInt(data[0]), Integer.parseInt(data[1])));
      System.out.println();
    }
  }

  // Begin golf

  BigInteger[] c;

  BigInteger a(int n, int k) {
    m(n);
    return g(n).divide(g(n - k)).divide(g(k));
  }

  BigInteger g(int n) {
    return n < 3 ? BigInteger.ONE : g(n - 1).multiply(c[n - 1]);
  }

  void m(int n) {
    c = new BigInteger[n];
    for (int i = 0; i < n; ++i)
      c[i] = (i < 2) ? BigInteger.ONE : c[i - 2].add(c[i - 1]);
  }
  // End golf
}

```

Program output:

```
a(0, 0)
  Expected -> 1
    Actual -> 1

a(1, 1)
  Expected -> 1
    Actual -> 1

a(2, 0)
  Expected -> 1
    Actual -> 1

a(3, 2)
  Expected -> 2
    Actual -> 2

a(8, 3)
  Expected -> 1092
    Actual -> 1092

a(11, 5)
  Expected -> 1514513
    Actual -> 1514513

a(22, 7)
  Expected -> 7158243695757340957617
    Actual -> 7158243695757340957617

a(25, 3)
  Expected -> 49845401197200
    Actual -> 49845401197200

a(50, 2)
  Expected -> 97905340104793732225
    Actual -> 97905340104793732225

a(100, 1)
  Expected -> 354224848179261915075
    Actual -> 354224848179261915075

```
> 2 votes

# Answer
# JavaScript (ES6), 70 bytes

```
a=n=>n<2?1:a(--n)+a(--n);b=n=>n?a(--n)*b(n):1;c=n=>k=>b(n)/b(n-k)/b(k)

```

Call using `c(n)(k)`, pretty straightforward.
> 1 votes

# Answer
# Ruby, 72 bytes

Special thanks to @st0le for the really short Fibonacci generation code.

```
->n,k{f=[a=b=1,1]+(1..n).map{b=a+a=b}
r=->i{f[i,k].inject:*}
k>0?r[n-k]/r[0]:1}

```
> 1 votes

# Answer
# dc, 67 bytes

```
?skdsn[si1d[sadlarla+zli>b*]sbzli>b*]dsgxsplnlk-lgxsqlklgxlprlqr*/f

```

Input is taken as space-delimited decimal constants on a single line.

This uses my answer to the `/Fibon(acci-)?orial/` question, which multiplies all numbers on the stack in the last step, requiring the other numbers to be stored elsewhere while the other Fibonorials are calculated.

```
?       # Take input from stdin
skdsn   # Store second number in register `k'; store a copy of first number in register `n'
[si1d[sadlarla+zli>b*]sbzli>b*] # Compute Fibonorial of top-of-stack, multiplying
                                #   until stack depth is 1
dsgx    # Store a copy of this function as g and execute it: g(n)
sp      # Store g(n) in register `p'
lnlk-   # Compute n-k
lgx     # Compute g(n-k)
sq      # Store g(n-k) in register `q'
lk lgx  # Compute g(k)
        # Top ---Down--->
lp      #  g(n)    g(k)
r       #  g(k)    g(n)
lq      #  g(n-k)  g(k)    g(n)
r       #  g(k)    g(n-k)  g(n)
*       # (g(k)g(n-k))     g(n)
/       #  g(n)/(g(k)g(n-k))
f       # Dump stack to stdout

```
> 1 votes

# Answer
# Julia, 53 bytes

```
!x=[([1 1;1 0]^n)[2]for n=1:x]|>prod;n\k=!n/!(n-k)/!k

```

Credits to @Lynn for his Fibonorial answer.
> 1 votes

# Answer
**Axiom 108 bytes**

```
b(n,k)==(n<=k or k<1=>1;reduce(*,[fibonacci(i) for i in (n-k+1)..n])/reduce(*,[fibonacci(i) for i in 1..k]))

```

some test

```
(34) -> b(0,0),b(1,1),b(2,0),b(3,2),b(8,3),b(11,5),b(22,7)
   Compiling function b with type (NonNegativeInteger,
      NonNegativeInteger) -> Fraction Integer
   Compiling function b with type (PositiveInteger,PositiveInteger) ->
      Fraction Integer
   Compiling function b with type (PositiveInteger,NonNegativeInteger)
       -> Fraction Integer

   (34)  [1,1,1,2,1092,1514513,7158243695757340957617]
                                                 Type: Tuple Fraction Integer
(35) -> b(25,3),b(50,2),b(100,1)

   (35)  [49845401197200,97905340104793732225,354224848179261915075]

```

## Type: Tuple Fraction Integer
> 1 votes

# Answer
# Mathematica, 30 bytes

```
(f=Fibonorial)@#/f[#-#2]/f@#2&

```
> 1 votes

# Answer
# Jelly, 10 bytes

```
;ạ/RÆḞP€÷/

```

Try it online!

## How it works

```
;ạ/RÆḞP€÷/ - Main link. Takes [n, r] on the left
 ạ/        - Calculate |n-r|
;          - Yield [n, r, |n-r|]
   R       - Convert each to a range
    ÆḞ     - For each integer i, yield the i'th Fibonacci number
      P€   - Get the product of each array, yielding [g(n), g(r), g(n-r)]
        ÷/ - Yield g(n) ÷ g(r) ÷ g(n-r) = g(n) ÷ (g(r) × g(n-r))

```
> 1 votes

---
Tags: code-golf, fibonacci, approximation
---


title: Time to adjust some prices!

text:
# Question
Title: Time to adjust some prices!
I'm sure you know about the $9.99 price scheme, instead of using $10. Well, in your new job as a sys admin at a large retail store, they want prices to adhere to a similar scheme:

* All prices are in whole dollars, no cents.
* All prices should end with 5 or 9, rounding to the closest but up if the last digit is right between 5 and 9. (Applies to last digit 2 and 7)
* Lowest input is $1, and the lowest outputted price should be $5.

Your input is a list of integers:

```
12
8
41
27
144
99
3

```

And the output should a list of the new prices. In the above case:

```
15
9
39
29
145
99
5

```

# Answer
# Brainfuck, 4428 bytes (invalid)

Once I knew the algorithm worked, I lost interest and didn't finish the input handler. That's why this solution technically solves the problem, but is very hard to use. When you start the program in an **interactive** interpreter (faster is better), you can enter your "number". It has to be entered in Base256 if your interpreter doesn't support number conversion (mine does). The maximum price you can enter is therefore 255.

It then performs a looping modulo if the number is greater than 9 to split off all digits except the last one. The division results are saved, while the last digit is rounded to 5 or 9. Then they are added and printed. Then the program cleans all used registers (probably overkill) and asks for the next number.

It handles all special cases (`$1`, `$20/$21 -> $19` etc.). Watch it run for the number `4` here (about 3 minutes, video shortened):

## Code

```
>+<+[>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<[>[-]+<-]>
[<+>>>>>>>>>>>[-],>>[-]<[-]<[>+<<<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>
>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>[-]+++++++++>[<<<<+
>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]
+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<<<[-]]<<<[-]<->>>>>>>>[<<<<<<<<->>>>
>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>[>>>>>+<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<
-]>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<
<[>[-]+<-]>[<+>>>>>>>>>>>>[-]<[>+<<<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>
>>>>>[-]++++++++++>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>[<<<<<+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<
<<<<<-]>>[>-[<<+<+>>>-]<<<[>>>+<<<-]+>[<->[-]]<[>>-[>>>>>>>>-<<<<<<<<[-]]+<<[-]]>>-]>>>>
>>>>+<<<<<<<]>>>>>[-]>>[<<+<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>
>[-]++++++++++>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>[>+<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<
<<<-]>-]>>>>>>>>>[-]<<[>>+<<-][-]>>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<
<<<<<<<<<<-]>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>
>>>[>+<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>>>>>[-]<<<[>>>+<<<-][-]>[<+<<<<<
<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<
<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>[>-<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>
>>>>[-]<[>+<-]<<<<<<<<<-]>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>-]
<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>>[<<+<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>
>>>>>>+<<<<<<<<<<-]>>>>>>>[-]>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<
-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<
<<[-]]<<<[-]<->>>>>>>>[<<<<<<<<->>>>>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>[>>>>>>>>>
>>>+<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<+>>>>>
>>>>>>>>>>-]<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>
>>>>>>>>+<<<<<<<<<-]>>>>>>>[-]++++>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<
<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>
>>-<<<<[-]]<<<[-]<->>>>>>>>[<<<<<<<<->>>>>>>>-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>>>>>>>[>>>>
>>+<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]<[>[-]+<-]>[<+>>>>>>>>>>>[-]+++++++++>>>>>>
>>+<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>-]<<<<<<<<<<<
<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>[<+<<<<<<<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>
>>>>>[-]++>[<<<<+>>>>-]<[<<<<<<+>+<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>[>>[<+<<<+>>>>-
]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]<[>>>>>>>-<<<<<<<[-]]>>>[-]>>
>[-]>>>>[<<<<+<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>>>>>[-]+
++++++++<<<<<[<<<+>>>-]>>>>>[<<<<<<<<<<<+>+<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<
<<<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]
>>[>>>-<<<[-]]<<<[-]>>>>>>>[<<<<<<<<+>>>>>>>>-]<<<<<<<<[[-]>>>>>>>[<<<<<<<+>+>>>>>>-]<<<
<<<[>>>>>>+<<<<<<-]<[>>>>>>>>-<<<<<<<<[-]]]->>>>>>>>[<<<<<<<<->>>>>>>>-]<<<<<<<<[>>>>>>>
>+<<<<<<<<-]>>>>>>>>[>>>>>>>>+<<<<<<<<<<<<<<<<<<->>>>>>>>>>[-]]<<<<<<<<<-]<[>[-]+<-]>[<+
>>>>>>>>>>[-]>>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>
->>>[-]<<<[>>>+<<<-]>[-]>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>[<<<<<<
<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>>[-]+++++<<<<<
<<<<<-]>>>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>-]<<<<[<<<<
<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>>[-]>>>[<<
<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>[-]>>[<<+<<<<<<<+>>>
>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>>>>>>[>+<<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<
<<-]>>>>>>>>>>>[-]<<<[>>>+<<<-][-]>>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+
<<<<<<<<<<<-]>[-]>[-]>[-]>[-]>>>>[<<<<<+[>+<<<<+>>>-]<<<[>>>+<<<-]+>>>>----------[<<<<->
>>>[-]]<<<<[>>+>[-]<<<-]>>[>>+<<<<+>>-]<<[>>+<<-]+>>>>----------[<<<<->>>>[-]]<<<<[>+>[-
]<<-]>>>>>>>>-]<<<<<<<[<++++++++[>++++++>++++++<<-]>.>.[-]<[-]]>[<<++++++++[>>++++++<<-]
>>.[-]]<<++++++++[>>>++++++<<<-]>>>.[-]<<<++++++++++.[-]>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<
<->-]<[>[-]+<-]>[<+<->>-]<<]

```
> 15 votes

# Answer
# CJam, ~~19~~ 17 bytes

```
q~{2-Ab)4>59s=N}/

```

Test it here.

Takes input as a CJam-style list and returns output newline separated.

# Explanation

```
qN/{   e# Run this block for each line of the input...
  ~    e#   Evaluate the current line to get the integer.
  2-   e#   Subtract 2 to get all but the last digit right.
  Ab)  e#   Convert to base 10 (discarding a potential minus sign) and split off
       e#   the last digit.
  4>   e#   Test if it's greater than 4.
  59s= e#   Select the correct digit from the string "59" based on this result.
  N    e#   Push a line feed.
}/

```
> 12 votes

# Answer
## Python 2, 47

```
lambda l:[max(5,(n+3)/5*5-(n-2)/5%2)for n in l]

```

If we look at the sequence of rounded values, we see that they come in blocks of 5.

```
... 25, 29, 29, 29, 29, 29, 35, 35, 35, 35, 35, 39, ...

```

We find what number block we're in with `(n+3)/5` (call this value `J`). Then, we get the right multiple of `5` with `J*5`, and adjust things like `30` down to `29` by subtracting `1` whenever `J` is even.

To special-case `1` give `5` rather than `-1`, we pass the result to `max(5,_)`.
> 12 votes

# Answer
# Retina, 32 bytes

Accepts input in a comma separated list. There must be a trailing comma. Outputs in the same format.

```
T`d`aa555559`.,
T+`da`ad`\da
a
5

```

**Explanation:**

```
T`               #Transliteration mode.
  d`aa555559`    #Map the digits 0-9 to aa55555999
             .,  #Map only the trailing digits.
T+`              #Do until input does not change.
   da`ad`        #Map a to 9, 0 to a, and 1-9 to 0-8
         \da     #Only do this to each a and the character before each a.
a                #Match all leftover a's. This only happens when the input contains the integer 1.
5                #Replace them with 5.

```
> 8 votes

# Answer
## Python 3, 74 82 bytes

```
a=eval(input())
for i in a:print(round(i,-1)+[5,-1][max(4,i-2)%10>4])

```

I struggled for brevity on values less than 11 and the requirement for 1 to evaluate to 5.
> 6 votes

# Answer
# R, ~~51~~ ~~49~~ ~~47~~ 43 bytes

```
(f=((n=scan()-2)%/%5+1+(n<0))*5)-(f%%10==0)

```

There should be room to improve this, but I thinking a different strategy might be better. Takes a vector of integers from scan and outputs a vector of integers. Essentially this uses integer division to round the number down, adds 1 and multiples it by five. Anything divisible by 10 has 1 taken away. If n = 1 then it increments the integer division by 1.

Test run

```
> (f=((n=scan()-2)%/%5+1+(n<0))*5)-(f%%10==0)
1: 1
2: 12
3: 8
4: 41
5: 27
6: 144
7: 99
8: 3
9:
Read 8 items
[1]   5  15   9  39  29 145  99   5
>

```
> 5 votes

# Answer
# Pyth, ~~21~~ ~~18~~ ~~29~~ 28 bytes

Thanks to @Jakube for cutting 3 bytes!

```
KeQJ-QKI<K2tJ.q;I<K6+J5;E+J9

```

Try it here.

**EDIT:** Apparently it was invalid. I fixed it up at the cost of 11 bytes; I'll try to golf it more.
> 4 votes

# Answer
# Pyth, 21 bytes

```
m?tdtt+d@jC"²a<"6ed5Q

```

Sadly I have to spend 4 bytes to correctly handle $1.
> 4 votes

# Answer
# Pyth, 18 bytes

```
m-|*K5hJ/-d2K6%J2Q

```

Try it online: Demonstration or Test Suite

This answer is based on @xor's Python/Pyth solution. The main difference is, that I handle the special case `1` differently. The actual result for `1` would be `0 - 1 = -1`. Using Python's `or` I can replace the `0` with a `6`, resulting in `6 - 1 = 5`. This saves the pain of taking the maximum of `5` and the result.

### Explanation:

```
m-|*K5hJ/-d2K6%J2Q
m                Q   map each number d of the input list Q to:
    K5                  K = 5
       J/-d2K           J = (d - 2) / K
   *K hJ                   K * (J + 1)
  |                     or
             6             6 # if K*(J+1)==0
 -            %J2       minus (J mod 2)

```
> 4 votes

# Answer
# Hassium, 133 Bytes

```
func main(){i=[12,8,41,27,144,99,3];foreach(e in i){f=e%10;if(!(e/10==0))print(e/10);if(f<5)r=5;else if(f>5)r=9;elser=f;println(r);}}

```

Run and see the expanded online: http://hassiumlang.com/Hassium/index.php?code=4f1c14f4d699b11da7a6392a74b720c4
> 3 votes

# Answer
# TI-BASIC, 19 bytes

```
int(Ans/5+.6
max(5,5Ans-not(fPart(Ans/2

```

Uses xnor's algorithm. TI-BASIC gets vectorization and multiplication for free, but we spend a few more bytes because it doesn't have modulo.
> 3 votes

# Answer
# Ruby, ~~55~~ 50 + 1 bytes

Run it with the `n` flag, like so: `ruby -n prices.rb`. Enter each price on a separate line.

```
x=$_.to_i
p x<7?5:(x-2).round(-1)+(~/[2-6]$/?5:-1)

```
> 2 votes

# Answer
# JavaScript, 50

```
l=>l.map(n=>Math.max(5,((n+3)/5|0)*5-((n-2)/5&1)))

```

I use an `&1` to save bytes instead of `|0` and mod 2
> 2 votes

# Answer
# Perl 5 `-p`, 33 bytes

```
/.1$|[60]$/?$_--:$_++until/[59]$/

```

Try it online!
> 2 votes

# Answer
# Haskell, 114 bytes

```
g n
 |n>6=9-n
 |n>1=5-n
 |1>0=(-n-1)
f n=show$(read n)+(g$read$(:[])$last n)
main=interact(unlines.(map f).lines)

```

## Explanation:

The function `g` returns `9-n` if `n>6` or else `5-n` if `n>1` or else `-n-1`. `g` is given the last digit and returns what should be added to the input number. `f` uses `g` to get the solution (plus lots of string manipulation). `main` outputs the result of `f` for each line of input.
> 1 votes

# Answer
# Vyxal, `ja`, ~~13~~ 12 bytes

```
ƛ⇩ȧṫ4>59$iJṅ

```

Try it Online!

I simply ported the CJam answer.

## Explained

```
ƛ⇩ȧṫ4>59$iJṅ
ƛ             # Over every number in the input,
 ⇩ȧ           #   abs(a - 2)
   ṫ4>        #   ↑[:-1], ↑[-1] > 4
      59$i    #   indexed into 59
          Jṅ  #   merged and joined on ""

```
> 1 votes

# Answer
# Stax, 12 bytes

```
Ç«δv▀▼ÖP▄¶⌠"

```

Run and debug it

Yet another port of the CJam answer.

-1 more byte if a list of integers is taken as input.
> 0 votes

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


title: Simulate a Minsky Register Machine (I)

text:
# Question
Title: Simulate a Minsky Register Machine (I)
There are many formalisms, so while you may find other sources useful I hope to specify this clearly enough that they're not necessary.

A RM consists of a finite state machine and a finite number of named registers, each of which holds a non-negative integer. For ease of textual input this task requires that the states also be named.

There are three types of state: increment and decrement, which both reference a specific register; and terminate. An increment state increments its register and passes control to its one successor. A decrement state has two successors: if its register is non-zero then it decrements it and passes control to the first successor; otherwise (i.e. register is zero) it simply passes control to the second successor.

For "niceness" as a programming language, the terminate states take a hard-coded string to print (so you can indicate exceptional termination).

Input is from stdin. The input format consists of one line per state, followed by the initial register contents. The first line is the initial state. BNF for the state lines is:

```
line       ::= inc_line
             | dec_line
inc_line   ::= label ' : ' reg_name ' + ' state_name
dec_line   ::= label ' : ' reg_name ' - ' state_name ' ' state_name
state_name ::= label
             | '"' message '"'
label      ::= identifier
reg_name   ::= identifier

```

There is some flexibility in the definition of identifier and message. Your program **must** accept a non-empty alphanumeric string as an identifier, but it **may** accept more general strings if you prefer (e.g. if your language supports identifiers with underscores and that's easier for you to work with). Similarly, for message you **must** accept a non-empty string of alphanumerics and spaces, but you **may** accept more complex strings which allow escaped newlines and double-quote characters if you want.

The final line of input, which gives the initial register values, is a space-separated list of identifier=int assignments, which must be non-empty. It is not required that it initialise all registers named in the program: any which aren't initialised are assumed to be 0.

Your program should read the input and simulate the RM. When it reaches a terminate state it should emit the message, a newline, and then the values of all the registers (in any convenient, human-readable, format, and any order).

Note: formally the registers should hold unbounded integers. However, you may if you wish assume that no register's value will ever exceed 2^30.

### Some simple examples

a+=b, a=0
```
s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4

```

Expected results:

```
Ok
a=0 b=7

```
b+=a, t=0
```
init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4

```

Expected results:

```
Ok
a=3 b=7 t=0

```
Test cases for trickier-to-parse machines
```
s0 : t - s0 s1
s1 : t + "t is 1"
t=17

```

Expected results:

```
t is 1
t=1

```

and

```
s0 : t - "t is nonzero" "t is zero"
t=1

```

Expected results:

```
t is nonzero
t=0

```

### A more complicated example

Taken from the DailyWTF's Josephus problem code challenge. Input is n (number of soldiers) and k (advance) and output in r is the (zero-indexed) position of the person who survives.

```
init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3

```

Expected results:

```
Ok
i=40 k=3 n=0 r=27 t=0

```

That program as a picture, for those who think visually and would find it helpful to grasp the syntax:

If you enjoyed this golf, have a look at the sequel.

# Answer
## Perl, 166

```
@p=<>;/=/,$_{$`}=$' for split$",pop@p;$o='\w+';(map{($r
,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p),$_=$o=($_{$r}
+=','cmp$o)<0?do{$_{$r}=0;$b}:$,until/"/;say for eval,%_

```

Run with `perl -M5.010 file`.

It started wildly different, but I'm afraid it converged with the Ruby solution in many areas towards the end. Seems like Ruby's advantage is "no sigils", and Perl's "better regex integration".

A bit of detail from the innards, if you don't read Perl:

* `@p=<>`: read the whole machine description to `@p`
* `/=/,$_{$`}=$' for split$",pop@p`: for each (`for`) assignment (`split$"`) in the last machine description line (`@p`), locate equal sign (`/=/`) then assign value `$'` to hask `%_` key `$``
* `$o='\w+'`: initial state would be first one to match Perl regex "word characters"
* `until/"/`: loop until we reach a termination state:
    + `map{($r,$o,$,,$b)=$'=~/".*?"|\S+/g if/^$o :/}@p`: loop on machine description `@p`: when we're on the line matching current state (`if/^$o :/`), tokenize (`/".*?"|\S+/g`) the rest of the line `$'` to variables `($r,$o,$,,$b)`. Trick: the same variable `$o` if used initially for label name and subsequently for operator. As soon as the label matches, the operator overrides it, and as a label can't (reasonably) be named + or -, it never matches again.
    + `$_=$o=($_{$r}+=','cmp$o)<0?do{$_{$r}=0;$b}:$,`:
    \- adjust target register `$_{$r}` up or down (ASCII magic: `','cmp'+'` is 1 whereas `','cmp'-'` is -1);
    \- if the result is negative (`<0?`, can only happens for -)
    \- then stay at 0 (`$_{$r}=0`) and return second label `$b`;
    \- else return first (possibly sole) label `$,`
    + BTW, it's `$,` instead of `$a` so it can be glued to next token `until` with no whitespace in between.
* `say for eval,%_`: dump report (`eval`) and contents of registers in `%_`
> 10 votes

# Answer
## Ruby 1.9, 214 212 211 198 195 192 181 175 173 175

```
*s,k=*$<
a,=s
b=Hash.new 0
eval k.gsub /(\w+)=/,';b["\1"]='
loop{x,y,r,o,t,f=a.scan /".*?"|\S+/
l=(b[r]-=o<=>?,)<0?(b[r]=0;f):t
l[?"]&&puts(eval(l),b)&exit
a,=s.grep /^#{l} /}

```
> 6 votes

# Answer
## Haskell, 444 characters

```
(w%f)(u@(s,v):z)|s==w=(s,f+v):z|t=u:(w%f)z
(w%f)[]=[(w,f)]
p#(a:z)|j==a=w p++[j]&z|t=(p++[a])#z;p#[]=w p
p&(a:z)|j==a=p:""#z|t=(p++[a])&z
c x=q(m!!0)$map((\(s,_:n)->(s,read n)).break(=='=')).w$last x where
 m=map(""#)$init x
 q[_,_,r,"+",s]d=n s$r%1$d
 q[_,_,r,_,s,z]d|maybe t(==0)(lookup r d)=n z d|t=n s$r%(-1)$d
 n('"':s)d=unlines[s,d>>=(\(r,v)->r++'=':shows v" ")]
 n s d=q(filter((==s).head)m!!0)d
main=interact$c.lines
t=1<3;j='"';w=words

```

Man, that was hard! Proper handling of messages with spaces in them cost over 70 characters. Output formatting to be more "human readable", and match the examples cost another 25.

---

* Edit: (498 -\> 482) various small in-linings, and some of @FUZxxl's suggestions
* Edit: (482 -\> 453) switch back using actual numbers for the registers; many golf tricks applied
* Edit: (453 -\> 444) inlined output formatting and initial value parsing
> 6 votes

# Answer
## Delphi, 646

Delphi does not offer very much with regard to splitting strings and stuff. Luckily, we do have generic collections, which does help a bit, but this is still a rather largish solution :

```
uses SysUtils,Generics.Collections;type P=array[0..99]of string;Y=TDictionary<string,P>;Z=TDictionary<string,Int32>;var t:Y;l,i:string;j,k:Int32;q:P;u:Z;v:TPair<string,Int32>;begin t:=Y.Create;repeat if i=''then i:=q[0];t.Add(q[0],q);ReadLn(l);for j:=0to 6do begin k:=Pos(' ',l+' ');q[j]:=Copy(l,1,k-1);Delete(l,1,k)end;until q[1]<>':';u:=Z.Create;j:=0;repeat k:=Pos('=',q[j]);u.Add(Copy(q[j],1,k-1),StrToInt(Copy(q[j],k+1,99)));Inc(j)until q[j]='';repeat q:=t[i];i:=q[4];u.TryGetValue(q[2],j);if q[3]='+'then Inc(j)else if j=0then i:=q[5]else Dec(j);u.AddOrSetValue(q[2],j)until i[1]='"';WriteLn(i);for v in u do Write(v.Key,'=',v.Value,' ')end.

```

Here the indented and commented version :

```
uses SysUtils,Generics.Collections;
type
  // P is a declaration line, offsets:
  // 0 = label
  // 1 = ':'
  // 2 = register
  // 3 = operation ('-' or '+')
  // 4 = 1st state (or message)
  // 5 = 2nd state (or message)
  P=array[0..99]of string;
  // T is a dictionary of all state lines :
  Y=TDictionary<string,P>;
  // Z is a dictionary of all registers :
  Z=TDictionary<string,Int32>;
var
  t:Y;
  l,
  i:string;
  j,
  k:Int32;
  q:P;
  u:Z;
  v:TPair<string,Int32>;
begin
  // Read all input lines :
  t:=Y.Create;
  repeat
    // Put all lines into a record
    if i=''then i:=q[0];
    t.Add(q[0],q);
    // Split up each input line on spaces :
    ReadLn(l);
    for j:=0to 6do
    begin
      k:=Pos(' ',l+' ');
      q[j]:=Copy(l,1,k-1);
      Delete(l,1,k)
    end;
    // Stop when there are no more state transitions :
  until q[1]<>':';
  // Scan initial registers :
  u:=Z.Create;
  j:=0;
  repeat
    k:=Pos('=',q[j]);
    // Add each name=value pair to a dictionary :
    u.Add(Copy(q[j],1,k-1),StrToInt(Copy(q[j],k+1,99)));
    Inc(j)
  until q[j]='';
  // Execute the state machine :
  repeat
    q:=t[i];
    i:=q[4];
    u.TryGetValue(q[2],j);
    if q[3]='+'then
      Inc(j)
    else
      if j=0then
        i:=q[5]
      else
        Dec(j);
    u.AddOrSetValue(q[2],j)
  until i[1]='"';
  WriteLn(i);
  for v in u do
    Write(v.Key,'=',v.Value,' ')
end.

```
> 3 votes

# Answer
# Stax, ~~115~~ 100 bytes

```
╥áípßNtP~£G±☼ΩtHô⌐╒╡~·7╝su9êq7h50Z`╩ë&ñ╝←j╞.½5└∩√I|ù┤╧Åτ╘8┼ç╕╒Æ►^█₧♫÷?²H½$IG☺S╚]«♀_≥å∩A+∩╣Δ└▐♫!}♥swα

```

Run and debug it
> 2 votes

# Answer
# JavaScript (V8), 300 bytes

```
p=>{g=p.split`
`;r=g[g.length-1].split` `.map(R=>R.split`=`);g.pop();l=g.map(L=>L.match(/\w+|[+-]|"[ \w]+"/g));t=l[0][0];for(;;){c=l.find(L=>L[0]==t);(e=r.find(R=>R[0]==c[1]))||r.push(e=[c[1],0]);t=eval(c[2]+c[2]+"e[1]")<0?e[1]++&&c[4]:c[3];if(t[0]==`"`)return t.slice(1,-1)+`
`+r.map(R=>R.join`=`)}}

```

Try it online!

I used a trick with `eval` to choose between `++e[1]` and `--e[1]`... it only saved a few bytes but it's fun.
> 2 votes

# Answer
## PHP, ~~446~~ ~~441~~ ~~402~~ ~~398~~ ~~395~~ ~~389~~ ~~371~~ ~~370~~ 366 characters

```
<?$t=trim;$e=explode;while($l=$t(fgets(STDIN))){if(strpos($l,"=")){foreach($e(" ",$l)as$b){list($k,$c)=$e("=",$b);$v[$k]=$c;}break;}list($k,$d)=$e(":",$l);$r[$z=$t($k)]=$t($d);$c=$c?:$z;}while($d=$e(" ",$r[$c],4)){$c=$v[$a=$d[0]]||!$d[3]?$d[2]:$d[3];if(!$r[$c]){eval("echo $c.'\n';");foreach($v as$k=>$c)echo$k."=".$c." ";die;}if(!$d[3]&&++$v[$a]||$v[$a]&&--$v[$a]);}

```

## Ungolfed

---

```
<?php

$register = array();
$values = array();

while($line = trim(fgets(STDIN))){

    if(strpos($line, "=")){

        // Set each value and then continue to the calculations

        foreach(explode(" ", $line) as $var){
            list($key, $val) = explode("=", $var);

            $values[$key] = $val;
        }

        break;
    }

    list($key, $data) = explode(":", $line);

    // Add data to the register

    $register[$z = trim($key)] = trim($data);

    // Set the first register

    $current = $current?:$z;
}

while($data = explode(" ", $register[$current], 4)){

    // Determine next register and current register

    $current = $values[$target = $data[0]] || !$data[3]? $data[2] : $data[3];

    // Will return true if the register does not exist (Messages wont have a register)

    if(!$register[$current]){

        // No need to strip the quotes this way

        eval("echo$current.'\n';");

        // Print all values in the right formatting

        foreach($values as $key => $val)
            echo $key."=".$val." ";

        die();
    }

    // Only subtraction has a third index
    // Only positive values return true

    // If there is no third index, then increase the value
    // If there is a third index, increment the decrease the value if it is positive

    // Uses PHP's short-circuit operators

    if(!$data[3] && ++$values[$target] || $values[$target] && --$values[$target]);
}

```

## Changelog

---

**446 -\> 441**: Supports strings for the first state, and some slight compression
**441 -\> 402**: Compressed if/else and assignment statements as much as possible
**402 -\> 398**: Function names can be used as constants which can be used as strings
**398 -\> 395**: Uses short circuit operators
**395 -\> 389**: No need for the else part
**389 -\> 371**: No need to use array\_key\_exists()
**371 -\> 370**: Removed unneeded space
**370 -\> 366**: Removed two unneeded spaces in the foreach
> 1 votes

# Answer
# Groovy , 338

```
m={s=r=[:];z=[:]
it.eachLine{e->((e==~/\w+=.*/)?{(e=~/((\w+)=(\d+))+/).each{r[it[2]]=it[3] as int}}:{f=(e=~/(\w+) : (.*)/)[0];s=s?:f[1];z[f[1]]=f[2];})()}
while(s[0]!='"'){p=(z[s]=~/(\w+) (.) (\w+|(?:".*?")) ?(.*)?/)[0];s=p[3];a=r[p[1]]?:0;r[p[1]]=p[2]=='-'?a?a-1:{s=p[4];0}():a+1}
println s[1..-2]+"\n"+r.collect{k,v->"$k=$v"}.join(' ')}

['''s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4''':'''Ok
a=0 b=7''',
'''init : t - init d0
d0 : a - d1 a0
d1 : b + d2
d2 : t + d0
a0 : t - a1 "Ok"
a1 : a + a0
a=3 b=4''':'''Ok
a=3 b=7 t=0''',
'''s0 : t - s0 s1
s1 : t + "t is 1"
t=17''':'''t is 1
t=1''',
'''s0 : t - "t is nonzero" "t is zero"
t=1''':'''t is nonzero
t=0''',
'''init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3''':'''Ok
i=40 k=3 n=0 r=27 t=0'''].collect {input,expectedOutput->
    def actualOutput = m(input)
    actualOutput == expectedOutput
}

```
> 1 votes

# Answer
# Clojure (344 chars)

With a few linebreaks for "readability":

```
(let[i(apply str(butlast(slurp *in*)))]
(loop[s(read-string i)p(->> i(replace(zipmap":\n=""[] "))(apply str)(format"{%s}")read-string)]
(let[c(p s)](cond(string? s)(println s"\n"(filter #(number?(% 1))p))
(=(c 1)'-)(let[z(=(get p(c 0)0)0)](recur(c(if z 3 2))(if z p(update-in p[(c 0)]dec))))
1(recur(c 2)(update-in p[(c 0)]#(if %(inc %)1)))))))

```
> 1 votes

# Answer
## Postscript () () ~~(852)~~ (718)

For reals this time. Executes all the test cases. It still requires the RM program to immediately follow in the program stream.

*Edit:* More factoring, reduced procedure names.

```
errordict/undefined{& " * 34 eq{.()= !{& " .(=). load " .( ).}forall ^()=
stop}{^ ^ " 0 @ : 0}ifelse}put<</^{pop}/&{dup}/:{def}/#{exch}/*{& 0
get}/.{print}/~{1 index}/"{=string cvs}/`{cvn # ^ #}/+={~ load add :}/++{1
~ length 1 sub getinterval}/S{/I where{^}{/I ~ cvx :}ifelse}/D{/? # :/_ #
cvlit :}/+{D S({//_ 1 +=//?})$ ^ :}/-{/| # : D S({//_ load 0 ne{//_ -1
+=//?}{//|}ifelse})$ ^ :}/![]/@{~/! #[# cvn ! aload length & 1 add #
roll]:}/;{(=)search ^ # ^ # cvi @ :}/${* 32 eq{++}if * 34 eq{& ++(")search
^ length 2 add 4 3 roll # 0 # getinterval cvx `}{token ^
#}ifelse}>>begin{currentfile =string readline ^( : )search{`( + )search{`
$ ^ +}{( - )search ^ ` $ $ ^ -}ifelse}{( ){search{;}{; I}ifelse}loop}ifelse}loop

```

Indented and commented with appended program.

```
%!
%Minsky Register Machine Simulation
errordict/undefined{ %replace the handler for the /undefined error
    & " * 34 eq{ % if, after conversion to string, it begins with '"',
        .()= !{ % print it, print newline, iterate through the register list
            & " .(=). load " .( ). % print regname=value
        }forall ^()= stop % print newline, END PROGRAM
    }{ % if it doesn't begin with '"', it's an uninitialized register
        ^ ^ " 0 @ : 0 %initialize register to zero, return zero
    }ifelse
}put
<<
/^{pop}
/&{dup}
/:{def} % cf FORTH
/#{exch}
/*{& 0 get} % cf C
/.{print} % cf BF

% these fragments were repeated several times
/~{1 index}
/"{=string cvs} % convert to string
/`{cvn # ^ #} % convert to name, exch, pop, exch
/+={~ load add :} % add a value to a variable
/++{1 ~ length 1 sub getinterval} % increment a "string pointer"

/S{/I where{^}{/I ~ cvx :}ifelse} %setINIT define initial state unless already done
/D{/? # :/_ # cvlit :} %sr define state and register for generated procedure
/+{D S({//_ 1 +=//?})$ ^ :} % generate an increment state and define
/-{/| # : D S({//_ load 0 ne{//_ -1 +=//?}{//|}ifelse})$ ^ :} % decrement state
/![] %REGS list of registers
/@{~/! #[# cvn ! aload length & 1 add # roll]:} %addreg append to REGS
/;{(=)search ^ # ^ # cvi @ :} %regline process a register assignment
/${ %tpe extract the next token or "string"
    * 32 eq{++}if %skip ahead if space
    * 34 eq{ %if quote, find the end-quote and snag both
        & ++(")search ^ length 2 add 4 3 roll # 0 # getinterval cvx `
    }{
        token ^ # %not a quote: pull a token, exch, pop
    }ifelse
}
>>begin

{
    currentfile =string readline ^
    ( : )search{ % if it's a state line
        `( + )search{ % if it's an increment
            ` $ ^ + %parse it
        }{
            ( - )search ^ ` $ $ ^ - %it's a decrement. Parse it
        }ifelse
    }{ % not a state, do register assignments, and call initial state
        ( ){search{;}{; I}ifelse}loop %Look Ma, no `exit`!
    }ifelse
}loop
init0 : k - init1 init3
init1 : r + init2
init2 : t + init0
init3 : t - init4 init5
init4 : k + init3
init5 : r - init6 "ERROR k is 0"
init6 : i + init7
init7 : n - loop0 "ERROR n is 0"
loop0 : n - loop1 "Ok"
loop1 : i + loop2
loop2 : k - loop3 loop5
loop3 : r + loop4
loop4 : t + loop2
loop5 : t - loop6 loop7
loop6 : k + loop5
loop7 : i - loop8 loopa
loop8 : r - loop9 loopc
loop9 : t + loop7
loopa : t - loopb loop7
loopb : i + loopa
loopc : t - loopd loopf
loopd : i + loope
loope : r + loopc
loopf : i + loop0
n=40 k=3

```
> 1 votes

# Answer
# AWK - 447

```
BEGIN{FS=":"}NF<2{split($1,x," ");for(y in x){split(x[y],q,"=");
g[q[1]]=int(q[2])}}NF>1{w=$1;l=$2;gsub(/ /,"",w);if(!a)a=w;for(i=0;;)
{sub(/^ +/,"",l);if(l=="")break;if(substr(l,1,1)=="\""){l=substr(l,2);
z=index(l,"\"")}else{z=index(l," ");z||z=length(l)+1}d[w,i++]=
substr(l,1,z-1);l=substr(l,z+1)}}END{for(;;){if(!((a,0)in d))break;h=d[a,0];
if(d[a,1]~/+/){g[h]++;a=d[a,2]}else{a=g[h]?d[a,2]:d[a,3];g[h]&&g[h]--}}
print a;for(r in g)print r"="g[r]}

```

This is the output for the first test:

```
% cat | awk -f mrm1.awk
s0 : a - s1 "Ok"
s1 : b + s0
a=3 b=4
^D
Ok
a=0
b=7

```
> 1 votes

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


title: Have you learned your fib-abc?

text:
# Question
Title: Have you learned your fib-abc?
I don't like numbers, but I do like the Fibonacci sequence. I'm sure we could work something out.

Please read one integer *n* from STDIN and output the *n*th Fibonacci number in base 26 (`abcdefghijklmnopqrstuvwxyz` instead of `0123456789`) to STDOUT.

The first Fibonacci number is 0. The second one is 1. The *n*th fibonacci number is the sum of the *n*-2nd and *n*-1st Fibonacci numbers.

First 32 fib-abc numbers:

```
fib(0) = a
fib(1) = b
fib(2) = b
fib(3) = c
fib(4) = d
fib(5) = f
fib(6) = i
fib(7) = n
fib(8) = v
fib(9) = bi
fib(10) = cd
fib(11) = dl
fib(12) = fo
fib(13) = iz
fib(14) = on
fib(15) = xm
fib(16) = blz
fib(17) = cjl
fib(18) = dvk
fib(19) = gev
fib(20) = kaf
fib(21) = qfa
fib(22) = baff
fib(23) = bqkf
fib(24) = cqpk
fib(25) = egzp
fib(26) = gxoz
fib(27) = leoo
fib(28) = scdn
fib(29) = bdgsb
fib(30) = bvivo
fib(31) = cypnp

```

This is code golf, so shortest code in bytes wins!

# Answer
> 12 votes
# CJam, 18 bytes

```
UXri{_@+}*;26b'af+

```

Try it online in the CJam interpreter.

### How it works

```
UX    e# Push 0 and 1.
ri{   e# Read an integer and execute the loop that many times.
  _   e#   Push a copy the topmost integer.
  @   e#   Rotate the bottom-most integer on top of the stack.
  +   e#   Pop the two topmost integers and push their sum.
}*    e#
;     e# Discard the topmost integer from the stack.
26b   e# Convert the remaining integer to base 26.
'af+  e# Add the character 'a' to each base-26 digit.

```

# Answer
> 8 votes
# TeaScript, 34 bytes  ~~37~~   ~~51~~   ~~54~~

TeaScript is JavaScript for golfing. It also brings ES2015 features to the average browser.

```
F(x)b(26)l(#C(lc()+(l<'a'?49:10)))

```

Try it online

### Explanation

```
          // x is the input
F(x)      // Fibonacci from input
.b(26)    // To Base-26 string but with 0-9, a-p
          // instead of a-z, to fix this...
.l(#      // Loops through each char
   C(          // Charcode from...
       l.c()+  // Charcode from char
       (l<'a'? // If number
           49  // Add 49 to char code
          :10  // Else add 10
       )
   )
)

```

<sub>\*This answer is non-competing</sub>

# Answer
> 6 votes
# Mathematica, ~~67~~ 61 bytes

```
Print[""<>Alphabet[][[Fibonacci@Input[]~IntegerDigits~26+1]]]

```

Calculates `f(1000000)` in about 51 milliseconds.

# Answer
> 5 votes
# Simplex v.0.6, 35 bytes

Sometimes I sigh and think, "Is this even worth submitting? It doesn't win, so why bother?" In response, I think, "Heck. It was fun. Besides, this is really fancied-up brainf\*** anyhow. Not too shabby."

```
5_*Ij1~SRpRi@T[Uj&ERp]pSR5_Vj26@pWo
5_                                  ~~ sqrt(5)
  *                                 ~~ copy to next byte, move right
   I                                ~~ increment [sqrt(5),sqrt(5)+1]
    j1                              ~~ insert a new cell and set it to one
                                    ~~ [sqrt(5),1,sqrt(5)+1]
      ~                             ~~ switch the previous with the current byte
                                    ~~ [1,sqrt(5),sqrt(5)+1]
       S                            ~~ perform subtraction [1-sqrt(5),0,sqrt(5)+1]
        Rp                          ~~ remove next cell [1-sqrt(5),sqrt(5)+1]
          Ri@                       ~~ take numeric input (n) into register
             T[      ]              ~~ applies the following to every cell
               U                    ~~ halves the current cell
                j&                  ~~ dumps and restores the value to the register
                  ERp               ~~ raises cell to the nth power, remove cell made
                      p             ~~ remove last cell
                       S            ~~ subtract the two values
                        R5_         ~~ goes right and sets sqrt(5)
                           V        ~~ divides the prev. two cells
                            j       ~~ inserts new cell
                             26@    ~~ puts 26 into the register
                                p   ~~ removes cell
                                 Wo ~~ converts the current to base 26 and outputs as number

```

# Answer
> 4 votes
# Pyth, 17 bytes

```
s@LGjhu,eGsGQU2lG

```

Try it online.

# Answer
> 3 votes
## Minkolang 0.9, 40 bytes

```
10n[0c+r]$x'26'r(d0c%1G0c:d$)xrx("a"+O).

```

Try it here.

### Explanation

```
10n[0c+r]                                   Calculates f(n) where n is taken from input
         $x'26'r                            Dumps the addend I don't need and pushes a 26
                (d0c%1G0c:d$)               Base-encodes f(n) in base 26
                             xrx            Dumps the 0, reverses, dumps the 26
                                ("a"+O).    Outputs the letters

```

# Answer
> 3 votes
# Python 2.7, 82 bytes

```
a=0
b=1
s=''
exec"a,b=b,a+b;"*input()
while a:s=chr(a%26+97)+s;a/=26
print s or'a'

```

# Answer
> 2 votes
# Whispers v3, 111 bytes

```
> Input
> fₙ
>> ≺1
>> 2ᶠ1
>> 4ⁿ3
> 26
>> 5⊥6
> 97
>> 8+R
>> Each 9 7
>> 'R
>> Each 11 10
>> Output 12

```

Try it on repl.it!

Needs to be run as `python3 whispers\ v3.py fibabc.wisp < input.txt 2> /dev/null` with input given on the first line of `input.txt`.

I think the first and last lines can be removed as per the consensus here, but I'm not sure.

8 bytes shorter than hardcoding the alphabet: Try it on repl.it!

# Answer
> 1 votes
# Haskell, 114 chars.

It is unexpectedly long. Any help welcome. Previously found a bug for fib(0)

```
f=scanl(+)0$1:f
k 0=[]
k x=k(x`div`26)++[toEnum$97+x`mod`26]
l 0=0
l x=k x
main=interact$l.(f!!).read.head.lines

```

`f` is infinite list of fibonacci. `toEnum` is same with `chr`, except that former doesn't need to import Data.Char.

# Answer
> 1 votes
# Jelly, 8 bytes

```
ÆḞṃØaṙ1¤

```

Try it online!

## How it works

```
ÆḞṃØaṙ1¤ - Main link. Takes an integer N on the left
ÆḞ       - Take the Nth Fibonacci number
       ¤ - Group the previous links into a nilad:
   Øa    -   "abc...xyz"
     ṙ1  -   Rotate once; "bcd...yza"
  ṃ      - Base decompress; Convert to base 26 then index into the string

```

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

```
x=>(f=n=>n>1?f(n-1)+f(n-2):1)(x)[S="toString"](26).replace(/./g,l=>(parseInt(l,26)+10)[S](36))

```

Try it online!

Uses recursion to find factorial, and some `toString`, `replace`, and `parseInt` magic to convert to letters.

# Answer
> 1 votes
# Zsh, 68 bytes

```
<<<A;{for ((a=1;b+=a;a+=b))<<<$[[##26]a]<<<$[[##26]b]}|tr 0-9A-P A-Z

```

Try it online!

Pure fibonacci code stolen from here.

# Answer
> 1 votes
# 05AB1E, 6 bytes

If a list of characters is fine as output, the `J` can be removed.

```
ÅfAÅвJ

```

Try it online!

```
Åf      # get the nth Fibonacci number
  A     # push the lowercase alphabet
   Åв   # convert the Fibonacci number to this custom base
     J  # join the list of digits into a string

```

# Answer
> 0 votes
# Ruby, 67 bytes

```
a,b=0,1
gets.to_i.times{a,b=b,a+b}
puts a.to_s(26).tr"0-9a-p","a-z"

```

# Answer
> 0 votes
# Matlab, 133 bytes

```
n=input('');if n<2,y=n;else
f=0;g=1;for k=2:n
h=f+g;f=g;g=h;end
y=fix(mod(g./26.^(fix(log(g)/log(26)):-1:0),26));end
disp(char(y+97))

```

# Answer
> 0 votes
# Ruby, 125 bytes

Not gonna win any time soon, but it was fun & my first code golf :')

```
def f(n);n<3?(n>0?1:0):f(n-1)+f(n-2);end
def a(s);s.bytes.map{|n|n<58?n+49:n+10}.pack("C*");end
puts a(f(gets.to_i).to_s(26))

```

First line is a function to compute fibonacci, second converts from Ruby's built-in base 26 encoding (0-9 then a-p) into a-z encoding, third gets a line from STDIN and runs it through both.

---
Tags: code-golf, number, base-conversion, fibonacci, encoding
---