title: The Non-Zero Digital Product Challenge

text:
# Question
Title: The Non-Zero Digital Product Challenge
Originally the Multiplicative digital root

# Challenge

~~Basically do what the title says~~

# Method

Given a positive integer **1** \<= **N** \<= **100000000** through one of our standard input methods, multiply every digit together, ignoring zeroes.

**Ex:** Take a number, say `361218402`:

* `3` * `6` = `18`
* `18` * `1` = `18`
* `18` * `2` = `36`
* `36` * `1` = `36`
* `36` * `8` = `288`
* `288` * `4` = `1152`
* `1152` * `1` *(ignore zeroes or turn them into ones)* = `1152`
* `1152` * `2` = `2304`

**The output for `361218402` is `2304`**

***Note: Treat the digit `0` in numbers as `1`.***

# Test Cases

```
1 => 1
10 => 1
20 => 2
100 => 1
999 => 729
21333 => 54
17801 => 56
4969279 => 244944
100000000 => 1

```

Standard Loopholes are disallowed, and this is , so shortest byte count wins!

Congrats to Jo King who got the bounty with his 70 byte brain-flak answer!

# Answer
> 4 votes
# Pyt, 3 bytes

```
ąžΠ

```

Explanation:

```
ą       Convert input to array of digits (implicit input as stack is empty)
 ž      Remove all zeroes from the array
  Π     Get the product of the elements of the array

```

Try it online!

# Answer
> 11 votes
# Haskell, 27 bytes

```
foldr((*).max 1.read.pure)1

```

Try it online!

## Ungolfed with UniHaskell and `-XUnicodeSyntax`

```
import UniHaskell

f ∷ String → Int
f = product ∘ map (max 1 ∘ read ∘ pure)

```

---

## Explanation

I'll start with what I initially had:

```
product.map(max 1.read.pure)

```

This is a *point-free* expression that evaluates to a function taking a string (or a list of characters) **s** (`"301"`) as an argument. It maps `max 1.read.pure` over **s**, essentially taking each character **i**, injecting it into a list (which makes it a string) (`["3", "0", "1"]`), then reading it, which evaluates the string (`[3, 0, 1]`) and finally taking the greater of **i** and **1** (`[3, 1, 1]`). Then it takes the `product` of the resulting list of integers (`3`).

I then golfed it by a byte with:

```
foldr((*).max 1.read.pure)1

```

This works because `product` is equivalent to `foldr (*) 1`. Instead of mapping and folding, I combined the two by folding with `(*).max 1.read.pure` which takes each non-zero digit and multiplies it with the accumulator.

# Answer
> 9 votes
# Python 2, 34 bytes

```
f=lambda n:n<1or(n%10or 1)*f(n/10)

```

Try it online!

# Answer
> 7 votes
# Jelly, 4 bytes

```
Do1P

```

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

## How it works

```
Do1P - Main link. Argument: n (integer)  e.g. 1230456
D    - Digits                                 [1, 2, 3, 0, 4, 5, 6]
 o1  - Replace 0 with 1                       [1, 2, 3, 1, 4, 5, 6]
   P - Product                                720

```

# Answer
> 6 votes
# , 40 bytes

```
cat(prod((x=scan()%/%10^(0:12)%%10)+!x))

```

Try it online!

Since input is guaranteed to have no more than 12 digits, this should work nicely. Computes the digits as `x` (including leading zeros), then replaces zeros with `1` and computes the product.

```
cat(					#output
    prod(				#take the product of
         (x=				#set X to
	    scan()			#stdin
		  %/%10^(0:12)%%10)	#integer divide by powers of 10, mod 10, yields digits of the input, with leading zeros. So x is the digits of the input
                                   +!x  #add logical negation, elementwise. !x maps 0->1 and nonzero->0. adding this to x yields 0->1, leaving others unchanged
                                      ))

```

# Answer
> 5 votes
# C (gcc), 39 bytes

```
k;f(n){for(k=1;n;n/=10)k*=n%10?:1;k=k;}

```

Needs to be compiled without optimizations (which is the default setting for gcc, anyway).

Try it online!

# Answer
> 5 votes
# Brain-Flak, ~~74~~ ~~72~~ 70 bytes

-2 thanks to Nitrodon for suggesting getting the negation of the number so that you only have to increment rather than decrement later

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

```

Try it online!

There might be a few ways to golf this further, such as  ~~redoing the multiplication to avoid having to initialise the total with 1.~~ (-2 bytes)

### How It Works:

```
{ Loop over every number
  ([{}]((((()()()){}){}){}){}) Add 48 to the negative of the ASCII to get the negation of the digit
  { If the number is not 0
     ({<({}())><>([[]](){})<>}<><{}>)<> Multiply the total by the number
                                          If the total is on an empty stack, add 1
  }
  {} Pop the excess 0
}<> Switch to the stack with the total

```

# Answer
> 4 votes
# 05AB1E, 4 bytes

```
0KSP

```

Try it online!

**Explanation**

```
0K     # remove zeroes
  S    # split to list of digits
   P   # product

```

# Answer
> 4 votes
# , ~~17~~ ~~14~~ 13 bytes

### -4 bytes courtesy of @GalenIvanov

```
[:*/1>.,.&.":

```

Try it online!

Probably can be improved some. Edit: and so it was.

# Explanation

```
[: */ 1 >. ,.&.":
                 ": Convert to string
             ,.     Convert row to column vector
               &.   Convert to numbers
      1 >.        Maximum of each element with 1 (convert 0 to 1)
   */              Product
[:                 Cap fork

```

`&.`-under is a nifty adverb that applies the verb on the right, then the verb on the left, then the *inverse* of the verb on the right. Also converting back to numbers is technically using eval (`".`-do).

# Answer
> 3 votes
# Python 2, 43 bytes

```
lambda n:eval('*'.join(`n`.replace(*'01')))

```

Try it online!

# Answer
> 3 votes
# Octave, 21 bytes

*Thanks to @Luis Mendo for saving a byte and thanks to @alephalpha for saving another byte!*

```
@(n)prod((k=n-48)+~k)

```

Takes input as a string of digits.

Try it online!

**30 bytes:**

```
@(n)prod((k=num2str(n)-48)+~k)

```

Takes input as a number.

Try it online!

# Answer
> 3 votes
# Bash \+ coreutils + sed + bc, ~~27~~ ~~24~~ 23 bytes

```
tr 0 1|sed s/\\B/*/g|bc

```

Try it online!

# Answer
> 3 votes
# JavaScript (ES6), 28 bytes

Designed for 32-bit integers.

```
f=n=>!n||(n%10||1)*f(n/10|0)

```

### Test cases

```
f=n=>!n||(n%10||1)*f(n/10|0)

console.log(f(1))        // => 1
console.log(f(10))       // => 1
console.log(f(20))       // => 2
console.log(f(100))      // => 1
console.log(f(999))      // => 729
console.log(f(21333))    // => 54
console.log(f(17801))    // => 56
console.log(f(4969279))  // => 244944
```

# Answer
> 3 votes
# Brachylog, 5 bytes

```
⊇ẹ×ℕ₁

```

Try it online!

### Explanation

```
⊇        Take a subset of the input
 ẹ       Split the subset into a list of digits
  ×      Product
   ℕ₁    This product must be in [1, +∞)

```

This works because  unifies from large subsets to small subsets, so the first one that will result in a non-zero product is when all zeroes are excluded and nothing else.

# Answer
> 3 votes
# Java 8, ~~55~~ ~~54~~ ~~53~~ 51 bytes

```
int f(int n){return n>0?(n%10>0?n%10:1)*f(n/10):1;}

```

Port of *@Dennis*' Python 2 answer.
-1 byte thanks to *@RiaD*.

Try it here.

**~~55~~ 54 bytes version:**

```
n->{int r=1;for(;n>0;n/=10)r*=n%10>0?n%10:1;return r;}

```

Try it online.

# Answer
> 3 votes
# Perl 5, 23 + 1 (`-p`) = 24 bytes

```
$\=1;s/./$\*=$&||1/ge}{

```

Try it online!

# Answer
> 3 votes
# Julia 0.6, 26 bytes

```
!x=prod(max.(digits(x),1))

```

Example of use:

```
julia> !54
20

```

Try it online!

# Answer
> 3 votes
# JavaScript (Node.js), 30 bytes

```
f=([a,...b])=>a?(+a||1)*f(b):1

```

Try it online!

Takes **string** as an input, treats it as array, and by array destructuring separates the first element `[a,...b]`. `+a||1` returns digit corresponding to `a` character. I guess that rest is self explaining..

# Answer
> 3 votes
# Vyxal, 3 bytes

```
fꜝΠ

```

Try it Online!

Pyt isn't the only language to do 3 bytes :3

### Explained

```
fꜝΠ
f   # flatten to a list
 ꜝ  # remove all 0's
  Π # product

```

# Answer
> 2 votes
# Brain-Flak, 88 bytes

Readable version:

```
#Push a 1 onto the alternate stack. Return to the main stack
(<>())<>

#While True:
{

    #Push the current digit minus 48 (the ASCII value of '0') onto the alternate stack
    ({}[((((()()()){}){}){}){}]<>)

    #If it's not 0...
    {
        (<

            #Multiply the top two values (the current digit and the current product that started at 1)
            ({}<>)({<({}[()])><>({})<>}{}<><{}>)

        #Also push a 0
        >)

    #Endwhile
    }

    #Pop the 0
    {}

    #Return to the main stack
    <>

#Endwhile
}

#Toggle to the alternate stack, and implicitly display
<>

```

Try it online!

# Answer
> 2 votes
# Clojure, 56 bytes

```
(fn[n](apply *(replace{0 1}(map #(-(int %)48)(str n)))))

```

Pretty basic. Turns the number into a string, then subtracts 48 from each character to turn them back into numbers. It then replaces each 0 with a 1, and applies `*` to the resulting list of numbers (which reduces `*` over the list). Can accept a number, or a stringified number.

Try it online!

```
(defn non-zero-prod [n]
  (let [; Abusing strings to get each digit individually
        str-n (str n)

        ; Then turn them back into numbers
        digits (map #(- (int %) 48) str-n)

        ; Substitute each 0 for a 1
        replaced (replace {0 1} digits)]

    ; Then get the product
    (apply * replaced)))

```

# Answer
> 2 votes
# Ruby, ~~42~~ ~~40~~ ~~35~~ ~~32~~ 27 bytes

```
p eval (gets.chars-[?0])*?*

```

Assumes no newlines in input Major influence

-2 bytes thanks to @GolfWolf

-5 bytes thanks to @Conor O'Brien

# Answer
> 2 votes
# JavaScript (Node.js), 36 33 bytes

Simple Javascript (ES6) method that takes input as number string, spreads it into an array, then reduces it through multiplication or returns the value if the result is 0.

3 bytes saved thanks to Shaggy

```
s=>[...s].reduce((a,b)=>b*a||a,1)

```

Try it online!

# Answer
> 2 votes
# MATL, 5 bytes

```
!UXzp

```

Input is taken as a string

Try it at MATL Online! Or verify test cases in Try It Online!

### Explanation

```
!     % Implicit input: string (row vector of chars). Transpose into
      % a column vector of chars
U     % Convert from string to number. Treats each row independently,
      % producing a column vector of numbers
Xz    % Keep only nonzeros
p     % Product. Implicit display

```

# Answer
> 2 votes
# Befunge, ~~23~~ 22 bytes

```
1<*_$#`.#0@#:+!:-"0"~$

```

Try it online!

**Explanation**

```
1<                        Push 1, turn back left, and push a second 1.
                     $    Drop one of them, leaving a single 1, the initial product.

                -"0"~     Read a char and subtract ASCII '0', converting to a number.
             +!:          If it's 0, make it 1 (this is n + !n).
      `  0  :             Then test if it's greater than 0, to check for EOF.
   _                      If it is greater than 0, it wasn't EOF, so we continue left.
  *                       Multiply with the current product, becoming the new product.
1<                        Now we repeat the loop, but this time push only a single 1...
                     $    ...which is immediately dropped, leaving the current product.

   _                      On EOF, the input value will be negative, so we branch right.
    $                     We don't need the input, so drop it.
       .  @               Leaving us with the product, which we output, then exit.

```

# Answer
> 2 votes
# Java (OpenJDK 8), 45 bytes

```
s->s.chars().reduce(1,(a,b)->b<49?a:a*(b-48))

```

Try it online!

# Answer
> 2 votes
# Ruby + `-n`, 25 bytes

```
p eval ($_.chars-[?0])*?*

```

Try it online!

### Ruby (vanilla), 27 bytes

```
p eval (gets.chars-[?0])*?*

```

Try it online!

# Answer
> 2 votes
# **C#, 97 Bytes (First code golf)**

```
static int X(int y){var z=y.ToString();int r=1;foreach(var q in z){if(q!=48){r*=q-48;}}return r;}

```

Not sure if i had to wrap it in a method or not so just included it to be safe.

Takes an Int in, converts it to a string and returns the multiple of each of the characters ignoring 0's. Had to minus 48 due to the program using the ascii value as it reads it as a char.

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 46 bytes

```
i.Select(c=>c>48?c-48:1).Aggregate((p,c)=>p*c)

```

Try it online!

# Answer
> 2 votes
# Rockstar, 61 bytes

```
Listen to N
Cut N
O's 1
While N
Let O be*roll N-0 or 1

Say O

```

Try it (Code will need to be pasted in)

# Answer
> 1 votes
# Jelly, ~~6~~, 5 bytes

```
ṢU×\Ṁ

```

Try it online!

# Answer
> 1 votes
# Haskell, 36 bytes

```
f n=product[read[d]|d<-show n,d>'0']

```

Same byte count:

```
f n=product[max 1$read[d]|d<-show n]

```

Try it online!

# Answer
> 1 votes
# APL (Dyalog), ~~11~~ 7 bytes

*4 bytes saved thanks to @EriktheOutgolfer*

```
×/0~⍨⍎¨

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~46~~ 44 bytes

```
f=lambda n,v=1:n and f(n/10,n%10*v or v)or v

```

Try it online!

2 bytes thx to Lynn.

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

```
1i:&0(?n&c4*-:0=+*!

```

Try it online!

# Answer
> 1 votes
# Add++, 12 bytes

```
L,EDBFEZB]B*

```

Try it online!

# Answer
> 1 votes
# Clean, 55 bytes

```
import StdEnv
@n=prod[toInt c-48\\c<-:toString n|c>'0']

```

Try it online!

# Answer
> 1 votes
# APL+WIN, 9 bytes

```
×/(⍎¨⎕)~0

```

Prompts for screen input as a character string, convert to digits, drop zeros and multiply all.

# Answer
> 1 votes
# Japt, 5 bytes

```
ì f ×

```

Test it here

---

## Explanation

In order: split to an array of digits, filter to remove zeroes and reduce by multiplication.

# Answer
> 1 votes
# K (oK), ~~10~~ 7 bytes

**Solution:**

```
*/1|.:'

```

Try it online!

**Example:**

```
*/1|.:'"4969279"
244944

```

**Explanation:**

Convert the input string to a list of integers, take max compared to `1` (inspiration from the  solution) and then multiply over the list.

Evaluation is performed right to left.

```
*/1|.:' / the solution
    .:' / value (.:) each (')
  1|    / or with 1 ( 0=>1, 1=>1, 2=>2 )
*/      / multiply (*) over (/)

```

# Answer
> 1 votes
# Forth (gforth), 62 bytes

```
: f 1 swap begin ?dup while 10 /mod -rot 1 max * swap repeat ;

```

Try it online!

# Answer
> 1 votes
# Lua, 45 bytes

```
a=1(...):gsub("[^0]",load("a=a*..."))print(a)

```

Try it online!

# Answer
> 1 votes
# Pyth, ~~10~~ 9 Bytes

```
.U*s!BsZs

```

Try it!

## Explanation

```
.U*s!BsZs
.U        Q     Fold over the implicit input string
      sZ        Convert each char to int
   s!B          Form the list [d,not d] and sum it, so that 0 becomes 1
  *     sb      Multiply by the prev product (implicit). s needed because 1st value is char

```

# Answer
> 1 votes
# JavaScript, ~~33~~ 32 bytes

Feels like ages since I've done an array mapping solution in JS!

Takes input as a string.

```
n=>[...n].map(x=>t*=+x||1,t=1)|t

```

---

## Try it

```
o.innerText=(f=
n=>[...n].map(x=>t*=+x||1,t=1)|t
)(i.value="361218402");oninput=_=>o.innerText=f(i.value)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 1 votes
# Perl 6, 19 bytes

```
{[*] grep +*,.comb}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  [*]        # reduce using &infix:«*»

    grep     # find the values
      +*,    # that aren't "0"
      .comb  # split ｢$_｣ into digits (returns single character strings)
}

```

# Answer
> 1 votes
## Batch, 78 bytes

```
@set/ap=%2+0,p+=!p,d=%1%%10,p*=d+!d,n=%1/10
@if %1 gtr 0 %0 %n% %p%
@echo %2

```

Previous 80-byte solution:

```
@set/an=%1,p=1
:l
@set/ad=n%%10,p*=d+!d,n/=10
@if %n% gtr 0 goto l
@echo %p%

```

(This version outputs 1 for an input of zero, rather than failing.)

# Answer
> 1 votes
# Attache, ~~20~~ 19 bytes

```
Prod##Max&1=>Digits

```

Try it online! Function that takes an integer as an argument and returns an integer.

## Explanation

This first takes the `Digits` of the input number, then each number's `Max` with `1` is taken, then the `Prod`uct is taken.

## Other solutions

```
Prod@Larger&1@Digits
Prod@Map[Max&1]@Digits
Prod@Map&:(Max&1)@Digits
{Prod[Max&1=>Digits[_]]}

```

# Answer
> 1 votes
# dc, 40 bytes

Sad to see `dc` so underrepresented here.

This is essentially my first code golf post, so if I've misjudged how bytes should be counted, go easy on me! :)

```
?[1+]sc[10~rdZ1<a]dsax1[rd0=c*z1<b]dsbxp

```

You can run this in the terminal like so:

```
$ echo 361218402 | dc -e '?[1+]sc[10~rdZ1<a]dsax1[rd0=c*z1<b]dsbxp'
2304

```

Or you can try it online!

---

Explanation (probably too verbose):

```
? # Read and execute a line from standard input
  # (A number just goes on the stack)
[ # Begin a literal string (ended by a matched ']')
1 # Push 1 onto the stack (when this string is executed as a macro)
+ # Pop top two numbers, add them, push result
] # End literal string
s # Pop top of stack (the string) and store it in...
c # ...register c
[
10 # Push 10 (duh)
~ # Pop top two numbers, divide second popped by first popped, push quotient and then remainder
r # Reverse top two numbers of stack
d # Duplicate top of stack (pop and then push it twice)
Z # Pop top of stack and push its length in digits
1
< # Pop two numbers and compare; if first popped is less than second then...
a # ...run macro stored in register a (a recursive call, here)
] # End string
d # Duplicate top of stack
s # Store in...
a # ...register a
x # Execute the top of stack!
  # At this point the stack will consist of one digit entries, the digits of input
1
[
r # Reverse
d # Duplicate
0
= # If top two numbers are equal then...
c # ...run macro in register c
* # Pop two, multiply, push product
z # Push "height" of stack
1
< # If height of stack is greater than 1 then...
b # ...run macro b
]
d # Duplicate the string on the stack
sb # Store it as macro b
x # Execute!
p # Print top of stack

```

# Answer
> 1 votes
# Microsoft Excel - ~~62~~ 47 Bytes

```
{=PRODUCT(IFERROR(1/(1/MID(A1,ROW(A:A),1)),1))}

```

# Explanation

Converts value in cell A1 to array of digits, changes 0s to 1s using absolute value, then multiplies.

*15 bytes saved thanks to Engineer Toast*

# Answer
> 1 votes
# Husk, 4 bytes

```
ΠfId

```

Try it online!

```
ΠfId  -- implicit input N, for example 1607
   d  -- digigts: [1,6,0,7]
 fI   -- filter by identity function: [1,6,7]
Π     -- product: 42

```

# Answer
> 1 votes
# Javascript, 58 bytes

```
f=a=>{b=1;for(i=0;a[i];i++){(a[i]>0)&&(b=+b*a[i])}alert(b)

```

Input via function(arg) outputs alert

# Answer
> 1 votes
# Red, 68 bytes

```
func[n][p: 1 while[n > 0][d: n // 10 n: n / 10 if d > 0[p: p * d]]p]

```

Try it online!

Since 100000000000 is beyond the integer range of the Red language, here's another approach that solves this issue, using string manipulation:

Red, 74 bytes

```
func[n][p: 1 foreach c to-string n[if c >#"0"[p: p * to-integer c - 48]]p]

```

Try it online!

# Answer
> 1 votes
# SNOBOL4 (CSNOBOL4), 83 bytes

```
	DEFINE('O(N)')
O	O =1
R	N LEN(1) . X REM . N	:F(RETURN)
	X =EQ(X) 1
	O =O * X	:(R)

```

Try it online!

A function that takes input as a string.

# Answer
> 1 votes
# Julia 0.6, 33 bytes

```
x->prod(filter(x->x>0,digits(x)))

```

Try it online!

# Answer
> 1 votes
# Pyth, 7 bytes

```
*FsMs#Q

```

Try it online!

---

```
*FsMs#Q Full program, takes input in "" from stdin and prints to stdout
    s#Q Filter input for truthiness of int-parse(digit), then
  sM    map int-parse to this,
*F      then fold over multiplication

```

# Answer
> 1 votes
# C# (.NET Core), 78 bytes

```
using System.Linq

n=>n.Replace("0","").Select(c=>c-'0').Aggregate(1,(a,b)=>a*b)

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 34 bytes

```
n->fold((a,b)->a*(b+!b),digits(n))

```

Try it online!

# Answer
> 1 votes
# Pyth, 6 bytes

```
*F #sM

```

Try it Online!

Explanation:

```
    sM   Get digits of implicit string input
   #     Filter on identity, removing 0s
*F       Fold on multiplication

```

# Answer
> 1 votes
# Pip, 7 bytes

```
$*YaDC0

```

Try it online!

`D`elete `C`haracter `0` from the argument `a` and fold (`$`) on multiplication (`*`). The `Y`ank operator is used to adjust the precedence of the subexpression (one byte shorter than `$*(aDC0)`).

# Answer
> 1 votes
# Jelly, 4 bytes

```
Dḟ0P

```

Try it online!

```
Dḟ0P    main link

D       int to dec
 ḟ0     filter out 0
   P    product of list

```

# Answer
> 1 votes
# Befunge-98 (PyFunge), 14 bytes

```
1<*+!:-0'~.j@#

```

Try it online!

# Answer
> 1 votes
# Stax, 4 bytesCP437

```
┤caü

```

5 bytes when unpacked,

```
E0-k*

```

Run and debug online!

## Explanation

```
E         Convert number to digits
 0-       Remove all zeros
   k*     Reduce array with multiplication

```

# Answer
> 1 votes
# Java 8, 52 bytes

```
n->(n+"").chars().reduce(1,(x,y)->x*=(y-=48)>0?y:1);

```

Try it online!
Obligatory stream answer.

# Answer
> 1 votes
# Factor \+ `math.extras math.unicode`, 21 bytes

```
[ 48 v-n nonzero Π ]

```

Attempt This Online!

Takes input as a string and gives output as an integer.

* `48 v-n` Subtract 48 from each code point in the input, converting it to a list of digits.
* `nonzero` Take only the non-zero numbers.
* `Π` Calculate the product of a sequence.

# Answer
> 1 votes
# Thunno 2, 3 bytes

```
0op

```

Attempt This Online!

#### Explanation

```
0op  # Implicit input
0o   # Remove 0s
  p  # Product
     # (Yes, both of those work on numbers)
     # Implicit output

```

# Answer
> 1 votes
# (,), 175 Chars or \\$175\log\_{256}(3)\approx34.67\\$ Bytes

```
(()()()(),()()()()()()())(()(),())(,((),(())(),,,(()()())(),(())(()()()(),,,,(),,(()()()())))(()(),(()(),,,,(),,(())))((),(,,,,,())),,,(,(()()(),((()))))(()()()),())(,,(()()))

```

TIO

# Answer
> 0 votes
# PHP, 52 Bytes

```
$t=1;foreach(array_filter(str_split($n))as$b)$t*=$b;

```

# Answer
> 0 votes
# tinylisp, 67 bytes

```
(load library
(d f(q((N)(i N(*(i(mod N 10)(mod N 10)1)(f(/ N 10)))1

```

Try it online!

### Explanation + ungolfed

The function `f` computes the non-zero digit product of its argument `N`. It uses a divmod algorithm to process the digits: If `N` is nonzero, it computes (`N` mod 10 if `N` mod 10 is nonzero, `1` otherwise), and multiplies that quantity by the result of recursing on `N` divided by 10. Once `N` becomes zero, all the digits have been processed and we return `1`.

```
(load library)

(def digit-product
 (lambda (num)
  (if num
   (*
    (if (mod num 10) (mod num 10) 1)
    (digit-product (/ num 10)))
   1)))

```

---

This implementation commits the cardinal sin of not using tail recursion. It's not a problem for the size of number this challenge requires us to handle, but for big enough numbers, we would eventually hit the max recursion depth. Here's a proper tail-recursive implementation (with helper function) in **83 bytes**:

```
(load library
(d _(q((N P)(i N(_(/ N 10)(*(i(mod N 10)(mod N 10)1)P))P
(q((N)(_ N 1

```

Try it online!

Ungolfed:

```
(load library)

(def _digit-product
 (lambda (num accum)
  (if num
   (_digit-product
    (/ num 10)
    (*
     (if (mod num 10) (mod num 10) 1)
     accum))
   accum)))

(lambda (num) (_digit-product num 1))

```

# Answer
> 0 votes
# Arturo, 29 bytes

```
$=>[∏filter digits&=>[0=&]]

```

Try it!

```
$=>[                   ; a function; assign input to &
    ∏                  ; product of...
    filter digits&=>[  ; digits of the input that aren't...
        0=&            ; equal to zero
    ]                  ; end filter
]                      ; end function

```

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


# Question
Title: Permutations such that no k+2 points fall on any polynomial of degree k
# Description

Let a permutation of the integers `{1, 2, ..., n}` be called *minimally interpolable* if no set of `k+2` points (together with their indices) fall on a polynomial of degree `k`. That is,

1. No two points fall on a horizontal line (0-degree polynomial)
2. No three points fall on a line (1-degree polynomial)
3. No four points fall on a parabola (2-degree polynomial)
4. Et cetera.

---

# Challenge

Write a program that computes OEIS sequence A301802(n), the number of minimally interpolable permutations of `{1, 2, ..., n}` for `n` as a large as possible.

---

# Scoring

I will time your code on my computer (2.3 GHz Intel Core i5, 8 GB RAM) with increasing inputs. Your score will be the greatest input that takes less than 1 minute to output the correct value.

---

# Example

For example, the permutation `[1, 2, 4, 3]` is minimally interpolable because

```
the terms together with their indices
[(1, 1), (2, 2), (3, 4), (4, 3)]
have the property that
  (0) No two points have the same y-value.
  (1) No three points lie on a line.
  (2) No four points lie on a parabola.

```

In the illustration, you can see that the horizontal lines (red) have at most one point on them, the lines (blue) have at most two points on them, and the parabolas (green) have three points on them.

---

# Data

Here are the minimally interpolable permutations for `n=3`, `n=4`, and `n=5`:

```
n = 3: [1,3,2],[2,1,3],[2,3,1],[3,1,2]
n = 4: [1,2,4,3],[1,3,2,4],[1,3,4,2],[1,4,2,3],[2,1,3,4],[2,1,4,3],[2,3,1,4],[2,4,1,3],[2,4,3,1],[3,1,2,4],[3,1,4,2],[3,2,4,1],[3,4,1,2],[3,4,2,1],[4,1,3,2],[4,2,1,3],[4,2,3,1],[4,3,1,2]
n = 5: [1,2,5,3,4],[1,3,2,5,4],[1,3,4,2,5],[1,4,2,3,5],[1,4,3,5,2],[1,4,5,2,3],[1,4,5,3,2],[1,5,3,2,4],[2,1,4,3,5],[2,3,1,4,5],[2,3,5,1,4],[2,3,5,4,1],[2,4,1,5,3],[2,4,3,1,5],[2,4,5,1,3],[2,5,1,3,4],[2,5,1,4,3],[2,5,3,4,1],[2,5,4,1,3],[3,1,4,5,2],[3,1,5,2,4],[3,1,5,4,2],[3,2,5,1,4],[3,2,5,4,1],[3,4,1,2,5],[3,4,1,5,2],[3,5,1,2,4],[3,5,1,4,2],[3,5,2,1,4],[4,1,2,5,3],[4,1,3,2,5],[4,1,5,2,3],[4,1,5,3,2],[4,2,1,5,3],[4,2,3,5,1],[4,2,5,1,3],[4,3,1,2,5],[4,3,1,5,2],[4,3,5,2,1],[4,5,2,3,1],[5,1,3,4,2],[5,2,1,3,4],[5,2,1,4,3],[5,2,3,1,4],[5,2,4,3,1],[5,3,2,4,1],[5,3,4,1,2],[5,4,1,3,2]

```

If my program is correct, the first few values of `a(n)`, the number of minimally interpolable permutations of `{1, 2, ..., n}`:

```
a(1) = 1
a(2) = 2
a(3) = 4
a(4) = 18
a(5) = 48
a(6) = 216
a(7) = 584
a(8) = 2870

```

# Answer
> 5 votes
## C#

```
using System;
using System.Diagnostics;
using BigInteger = System.Int32;

namespace Sandbox
{
    class PPCG160382
    {
        public static void Main(params string[] args)
        {
            if (args.Length != 0)
            {
                foreach (var arg in args) Console.WriteLine(CountValidPerms(int.Parse(arg)));
            }
            else
            {
                int[] smallValues = new int[] { 1, 1, 2, 4, 18, 48 };
                for (int n = 0; n < smallValues.Length; n++)
                {
                    var observed = CountValidPerms(n);
                    var expected = smallValues[n];
                    Console.WriteLine(observed == expected ? $"{n}: Ok" : $"{n}: expected {expected}, observed {observed}, error {observed - expected}");
                }
                for (int n = smallValues.Length; n < 13; n++)
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    Console.WriteLine($"{n}: {CountValidPerms(n)} in {sw.ElapsedMilliseconds}ms");
                }
            }
        }

        private static long CountValidPerms(int n)
        {
            // We work on the basis of exclusion by extrapolation.
            var unused = (1 << n) - 1;
            var excluded = new int[n];
            int[] perm = new int[n];

            // Symmetry exclusion: perm[0] < (n+1) / 2
            if (n > 1) excluded[0] = (1 << n) - (1 << ((n + 1) / 2));

            long count = 0;
            CountValidPerms(ref count, perm, 0, unused, excluded);
            return count;
        }

        private static void CountValidPerms(ref long count, int[] perm, int off, int unused, int[] excluded)
        {
            int n = perm.Length;
            if (off == n)
            {
                count += CountSymmetries(perm);
                return;
            }

            // Quick-aborts
            var completelyExcluded = excluded[off];
            for (int i = off + 1; i < n; i++)
            {
                if ((unused & ~excluded[i]) == 0) return;
                completelyExcluded &= excluded[i];
            }
            if ((unused & completelyExcluded) != 0) return;

            // Consider each unused non-excluded value as a candidate for perm[off]
            var candidates = unused & ~excluded[off];
            for (int val = 0; candidates > 0; val++, candidates >>= 1)
            {
                if ((candidates & 1) == 0) continue;

                perm[off] = val;

                var nextUnused = unused & ~(1 << val);

                var nextExcluded = (int[])excluded.Clone();
                // For each (non-trivial) subset of smaller indices, combine with off and extrapolate to off+1 ... excluded.Length-1
                if (off < n - 1 && off > 0)
                {
                    var points = new Point[off + 1];
                    var denoms = new BigInteger[off + 1];
                    points[0] = new Point { X = off, Y = perm[off] };
                    denoms[0] = 1;
                    ExtendExclusions(perm, off, 0, points, 1, denoms, nextExcluded);
                }

                // Symmetry exclusion: perm[0] < perm[-1] < n - 1 - perm[0]
                if (off == 0 && n > 1)
                {
                    nextExcluded[n - 1] |= (1 << n) - (2 << (n - 1 - val));
                    nextExcluded[n - 1] |= (2 << val) - 1;
                }

                CountValidPerms(ref count, perm, off + 1, nextUnused, nextExcluded);
            }
        }

        private static void ExtendExclusions(int[] perm, int off, int idx, Point[] points, int numPoints, BigInteger[] denoms, int[] excluded)
        {
            if (idx == off) return;

            // Subsets without
            ExtendExclusions(perm, off, idx + 1, points, numPoints, denoms, excluded);

            // Just add this to the subset
            points[numPoints] = new Point { X = idx, Y = perm[idx] };
            denoms = (BigInteger[])denoms.Clone();
            // Update invariant: denoms[s] = prod_{t != s} points[s].X - points[t].X
            denoms[numPoints] = 1;
            for (int s = 0; s < numPoints; s++)
            {
                denoms[s] *= points[s].X - points[numPoints].X;
                denoms[numPoints] *= points[numPoints].X - points[s].X;
            }
            numPoints++;

            for (int target = off + 1; target < excluded.Length; target++)
            {
                BigInteger prod = 1;
                for (int t = 0; t < numPoints; t++) prod *= target - points[t].X;

                Rational sum = new Rational(0, 1);
                for (int s = 0; s < numPoints; s++) sum += new Rational(prod / (target - points[s].X) * points[s].Y, denoms[s]);

                if (sum.Denom == 1 && sum.Num >= 0 && sum.Num < excluded.Length) excluded[target] |= 1 << (int)sum.Num;
            }

            // Subsets with
            ExtendExclusions(perm, off, idx + 1, points, numPoints, denoms, excluded);
        }

        private static int CountSymmetries(int[] perm)
        {
            if (perm.Length < 2) return 1;

            int cmp = 0;
            for (int i = 0, j = perm.Length - 1; i <= j; i++, j--)
            {
                cmp = perm.Length - 1 - perm[i] - perm[j];
                if (cmp != 0) break;
            }

            return cmp > 0 ? 4 : cmp == 0 ? 2 : 0;
        }

        public struct Point
        {
            public int X;
            public int Y;
        }

        public struct Rational
        {
            public Rational(BigInteger num, BigInteger denom)
            {
                if (denom == 0) throw new ArgumentOutOfRangeException(nameof(denom));

                if (denom < 0) { num = -num; denom = -denom; }

                var g = _Gcd(num, denom);
                Num = num / g;
                Denom = denom / g;
            }

            private static BigInteger _Gcd(BigInteger a, BigInteger b)
            {
                if (a < 0) a = -a;
                if (b < 0) b = -b;
                while (a != 0)
                {
                    var tmp = b % a;
                    b = a;
                    a = tmp;
                }
                return b;
            }

            public BigInteger Num;
            public BigInteger Denom;

            public static Rational operator +(Rational a, Rational b) => new Rational(a.Num * b.Denom + a.Denom * b.Num, a.Denom * b.Denom);
        }
    }
}

```

Takes values of `n` as command-line arguments, or if run without arguments times itself up to `n=10`. Compiling as "Release" in VS 2017 and running on an Intel Core i7-6700 I calculate `n=9` in 1.2 seconds, and `n=10` in 13.6 seconds. `n=11` is just over 2 minutes.

FWIW:

```
n    a(n)
9    10408
10   45244
11   160248
12   762554

```

# Answer
> 0 votes
# Rust

\\$\color{red}{\text{I was trying to rewrite @Peter Taylor's C# answer in Rust. But the Rust code here has some mistakes.}}\\$

Any help would be appreciated.

### `src/main.rs`

```
use std::time::Instant;
use num_bigint::BigInt;
use num_traits::Zero;
use num_traits::One;
use num_traits::Signed;
use num_traits::ToPrimitive;

#[derive(Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}

#[derive(Clone)]
struct Rational {
    num: BigInt,
    denom: BigInt,
}

impl Rational {
    fn new(num: BigInt, denom: BigInt) -> Self {
        let g = gcd(num.clone(), denom.clone());
        Rational { num: num / g.clone(), denom: denom / g }
    }
}

impl std::ops::Add for Rational {
    type Output = Rational;

    fn add(self, other: Rational) -> Rational {
        let self_denom_clone = self.denom.clone();
        Rational::new(self.num.clone() * other.denom.clone() + self_denom_clone * other.num.clone(),
            self.denom * other.denom.clone())
    }

}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() > 1 {
        for arg in &args[1..] {
            let n = arg.parse::<i32>().unwrap();
            println!("{}", count_valid_perms(n));
        }
    } else {
        let small_values = vec![1, 1, 2, 4, 18, 48];
        for n in 0..small_values.len() {
            let observed = count_valid_perms(n as i32);
            let expected = small_values[n];
            if observed == expected {
                println!("{}: Ok", n);
            } else {
                println!("{}: expected {}, observed {}, error {}", n, expected, observed, observed - expected);
            }
        }
        for n in small_values.len()..13 {
            let start = Instant::now();
            println!("{}: {} in {}ms", n, count_valid_perms(n as i32), start.elapsed().as_millis());
        }
    }
}

fn gcd(a: BigInt, b: BigInt) -> BigInt {
    let mut a = a;
    let mut b = b;
    while !a.is_zero() {
        let tmp = b.clone() % a.clone();
        b = a;
        a = tmp;
    }
    b.abs()
}

fn count_valid_perms(n: i32) -> i64 {
    let unused = (1 << n) - 1;
    let mut excluded = vec![0; n as usize];
    let mut perm = vec![0; n as usize];
    if n > 1 { excluded[0] = (1 << n) - (1 << ((n + 1) / 2)); }
    let mut count: i64 = 0;
    count_valid_perms_recursive(&mut count, &mut perm, 0, unused, &mut excluded);
    count
}

// fn count_valid_perms_recursive(count: &mut i64, perm: &mut Vec<i32>, off: i32, mut unused: i32, excluded: &mut Vec<i32>) {
fn count_valid_perms_recursive(count: &mut i64, perm: &mut Vec<i32>, off: i32, unused: i32, excluded: &mut Vec<i32>) {

    let n = perm.len();
    if off == n as i32 {
        *count += count_symmetries(perm);
        return;
    }
    let mut completely_excluded = excluded[off as usize];
    for i in (off + 1)..n as i32 {
        if (unused & !excluded[i as usize]) == 0 { return; }
        completely_excluded &= excluded[i as usize];
    }
    if (unused & completely_excluded) != 0 { return; }
    let mut candidates = unused & !excluded[off as usize];
    for val in 0.. {
        if candidates > 0 {
            candidates >>= 1;
            if (candidates & 1) == 0 { continue; }
            perm[off as usize] = val;
            let next_unused = unused & !(1 << val);
            let mut next_excluded = excluded.clone();
            if off < n as i32 - 1 && off > 0 {
                let mut points = vec![Point { x: 0, y: 0 }; (off + 1) as usize];
                let mut denoms = vec![BigInt::one(); (off + 1) as usize];
                points[0] = Point { x: off, y: perm[off as usize] };
                extend_exclusions(perm, off, 0, &mut points, 1, &mut denoms, &mut next_excluded);
            }
            if off == 0 && n > 1 {
                next_excluded[n - 1] |= (1 << n) - (2 << (n - 1 - (val as usize)));
                next_excluded[n - 1] |= (2 << val) - 1;
            }
            count_valid_perms_recursive(count, perm, off + 1, next_unused, &mut next_excluded);
        } else {
            break;
        }
    }
}

fn extend_exclusions(perm: &mut Vec<i32>, off: i32, idx: i32, points: &mut Vec<Point>, num_points: usize, denoms: &mut Vec<BigInt>, excluded: &mut Vec<i32>) {
    if idx == off { return; }
    extend_exclusions(perm, off, idx + 1, points, num_points, denoms, excluded);
    points[num_points] = Point { x: idx, y: perm[idx as usize] };
    let denoms_clone = denoms.clone();
    denoms[num_points] = BigInt::one();
    for s in 0..num_points {
        denoms[s] *= BigInt::from(points[s].x - points[num_points].x);
        denoms[num_points] *= BigInt::from(points[num_points].x - points[s].x);
    }
    let num_points = num_points + 1;
    for target in ((off + 1) as usize)..excluded.len() {
        let mut prod = BigInt::one();
        for t in 0..num_points {
            prod *= BigInt::from(target as i32 - points[t].x);
        }
        let mut sum = Rational { num: BigInt::zero(), denom: BigInt::one() };
        for s in 0..num_points {
            let prod_s = prod.clone() / BigInt::from(target as i32 - points[s].x) * BigInt::from(points[s].y);
            sum = sum + Rational::new(prod_s, denoms_clone[s].clone());
        }
        if sum.denom == BigInt::one() && sum.num >= BigInt::zero() && sum.num.to_usize().unwrap() < excluded.len() {
            excluded[target as usize] |= 1 << sum.num.to_usize().unwrap();
        }
    }
    extend_exclusions(perm, off, idx + 1, points, num_points, denoms, excluded);
}

fn count_symmetries(perm: &Vec<i32>) -> i64 {
    if perm.len() < 2 { return 1; }
    let mut cmp = 0;
    let (mut i, mut j) = (0, perm.len() - 1);
    while i <= j {
        cmp = perm.len() as i32 - 1 - perm[i] - perm[j];
        if cmp != 0 { break; }
        i += 1; j -= 1;
    }
    match cmp {
        cmp if cmp > 0 => 4,
        cmp if cmp == 0 => 2,
        _ => 0,
    }
}

```

### `Cargo.toml`

```
[package]
name = "rust_hello"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
num-bigint = "0.4.2"
num-traits = "0.2.14"

```

### Build and running

# win10 environment

$ cargo build
$ target\debug\rust_hello.exe
0: Ok
1: expected 1, observed 0, error -1
2: expected 2, observed 0, error -2
3: expected 4, observed 8, error 4
4: expected 18, observed 36, error 18
5: expected 48, observed 124, error 76
6: 1008 in 100ms
7: 5024 in 1864ms
8: 64224 in 57079ms
```

---
Tags: math, sequence, combinatorics, fastest-code
---


title: Output the n-th Bell Number

text:
# Question
Title: Output the n-th Bell Number
A *Bell number* (OEIS A000110) is the number of ways to partition a set of n labeled (distinct) elements. The 0th Bell number is defined as 1.

Let's look at some examples (I use brackets to denote the subsets and braces for the partitions):

```
1: {1}
2: {[1,2]}, {[1],[2]}
3: {[1,2,3]}, {[1,2],[3]}, {[1,3],[2]}, {[2,3],[1]}, {[1],[2],[3]}

```

There are many ways to compute Bell numbers, and you are free to use any of them. One way will be described here:

The easiest way to compute Bell numbers is to use a number triangle resembling Pascal's triangle for the binomial coefficients. The Bell numbers appear on the edges of the triangle. Starting with 1, each new row in the triangle is constructed by taking the last entry in the previous row as the first entry, and then setting each new entry to its left neighbor plus its upper left neighbor:

```
1
1    2
2    3    5
5    7   10   15
15  20   27   37   52

```

You may use 0-indexing or 1-indexing. If you use 0-indexing, an input of `3` should output `5`, but should output `2` if you use 1-indexing.

Your program must work up to the 15th Bell number, outputting `1382958545`. In theory, your program should be able to handle larger numbers (in other words, don't hardcode the solutions). **EDIT: You are not required to handle an input of 0 (for 0-indexing) or 1(for 1-indexing) because it is not computed by the triangle method.**

Test cases (assuming 0-indexing):

```
0 ->  1 (OPTIONAL)
1 ->  1
2 ->  2
3 ->  5
4 ->  15
5 ->  52
6 ->  203
7 ->  877
8 ->  4140
9 ->  21147
10 -> 115975
11 -> 678570
12 -> 4213597
13 -> 27644437
14 -> 190899322
15 -> 1382958545

```

Answers using a built-in method (such as BellB\[n\] in the Wolfram Language) that directly produces Bell numbers will be noncompetitive.

Shortest code (in bytes) wins.

# Answer
> 2 votes
# Jelly, 9 bytes

```
ṖµṀcæ.ß€‘

```

This uses the formula

which is closed whenever **n \< 2**.

Try it online!

### How it works

```
ṖµṀcæ.ß€‘  Main link. Argument: n

Ṗ          Pop; yield A := [1, ..., n-1].
 µ         Begin a new, monadic chain with argument A.
  Ṁ        Maximum; yield n-1.
   c       Combinatons; compute (n-1)C(k) for each k in A.
      ß€   Recursively map the main link over A.
    æ.     Take the dot product of the results to both sides.
        ‘  Increment; add 1 to the result.

```

# Answer
> 8 votes
## JavaScript (ES6), 47 bytes

```
f=(n,a=[b=1])=>n--?f(n,[b,...a.map(e=>b+=e)]):b
f=(n,a=[b=1])=>--n?f(n,[b,...a.map(e=>b+=e)]):b

```

First one is 0-indexed, second is 1-indexed.

# Answer
> 8 votes
## Haskell, 36 bytes

```
head.(iterate(last>>=scanl(+))[1]!!)

```

Uses the triangle method, correctly handles 0, 0-based.

# Answer
> 5 votes
# , 31 bytes

```
sum(gmp::Stirling2.all(scan()))

```

uses the Stirling Number of the Second Kind formula and calculates those numbers with the gmp package; reads from stdin and returns the value as a Big Integer; fails for 0; 1-indexed.

# Answer
> 4 votes
# Mathematica , 24 bytes

```
Sum[k^#/k!,{k,0,∞}]/E&

```

-13 bytes from @Kelly Lowder!

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

```
ṫ0;⁸+\
1Ç¡Ḣ

```

Try it online!

Didn't exactly hit the strong points of Jelly with ~~dynamic input to `¡`,~~  always modifying the array and the lack of a prepending atom (one-byte `;@` or reverse-).

# Answer
> 3 votes
## CJam (19 bytes)

```
Xa{X\{X+:X}%+}qi*0=

```

Online demo

### Dissection

```
Xa         e# Start with an array [1]
{          e# Repeat...
  X\       e#   Put a copy of X under the current row
  {X+:X}%  e#   Map over x in row: push (X+=x)
  +        e#   Prepend that copy of last element of the previous row to get the next row
}
qi*        e# ... input() times
0=         e# Select the first element

```

# Answer
> 3 votes
# MATL, 14 bytes

```
:dtEw1Zh1Ze/Yo

```

Input is 0-based. Try it online!

### Explanation

This uses the formula

where *p* *F**q* (*a*1, ..., *a**p*; *b*1, ..., *b**q*; *x*) is the generalized hypergeometric function.

```
:      % Implictly input n. Push array [1 2 ... n]
d      % Consecutive differences: array [1 ... 1] (n-1 entries)
tE     % Duplicate, multiply by 2: array [2 ... 2] (n-1 entries)
w      % Swap
1      % Push 1
Zh     % Hypergeometric function
1Ze    % Push number e
/      % Divide
Yo     % Round (to prevent numerical precision issues). Implicitly display

```

# Answer
> 3 votes
# Python, 42 bytes

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

```

Try it online!

The recursive formula comes from placing `n` elements into partitions. For each element in turn, we decide whether to place it:

* Into an existing partition, of which there are `k` choices
* To start a new partition, which increases the number of choices `k` for future elements

Either way decreases the remaining number `n` of elements to place. So, we have the recursive formula `f(n,k)=k*f(n-1,k)+f(n-1,k+1)` and `f(0,k)=1`, with `f(n,0)` the n-th Bell number.

# Answer
> 2 votes
# Python 2, 91 bytes

```
s=lambda n,k:n*k and k*s(n-1,k)+s(n-1,k-1)or n==k
B=lambda n:sum(s(n,k)for k in range(n+1))

```

Try it online!

B(n) calculated as a sum of Stirling numbers of the second kind.

# Answer
> 2 votes
# MATLAB, ~~128~~ 103 bytes

```
function q(z)
r(1,1)=1;for x=2:z
r(x,1)=r(x-1,x-1);for y=2:x
r(x,y)=r(x,y-1)+r(x-1,y-1);end
end
r(z,z)

```

Pretty self explanatory. Omitting a semicolon at the end of a line prints the result.

25 bytes saved thanks to Luis Mendo.

# Answer
> 2 votes
# MATL, ~~19~~ 18 bytes

```
1i:"t@q@:qXn*sh]0)

```

Uses 0-based input. Based on the recurrence relation

Try it online!

# Answer
> 2 votes
# , 46 bytes

```
r=1;for(i in 1:scan())r=cumsum(c(r[i],r));r[1]

```

Try it online!

# Answer
> 2 votes
# Ohm, 15 bytes

```
2°M^┼ⁿ^!/Σ;αê/≈

```

Try it online!

Uses Dobinski's forumla (even works for B(0) *yay*).

### Explanation

```
2°M^┼ⁿ^!/Σ;αê/≈
2°        ;     # Push 100
  M             # Do 100 times...
   ^             # Push index of current iteration
    ┼ⁿ           # Take that to the power of the user input
      ^!         # Push index factorial
        /        # Divide
         Σ       # Sum stack together
           αê   # Push e (2.718...)
             /  # Divide
              ≈ # Round to nearest integer (Srsly why doesn't 05AB1E have this???)

```

# Answer
> 2 votes
## Python (79 bytes)

```
B=lambda n,r=[1]:n and B(n-1,[r[-1]+sum(r[:i])for i in range(len(r)+1)])or r[0]

```

Online demo in Python 2, but it also works in Python 3.

This builds Aitken's triangle using a recursive lambda for a golfy loop.

# Answer
> 2 votes
# Haskell, 35 bytes

```
(%0)
n%k|n<1=1|m<-n-1=k*m%k+m%(k+1)

```

Try it online!

Formula explained in my Python answer.

# Answer
> 1 votes
# PHP, 72 bytes

recursive function 1-indexed

```
function f($r,$c=0){return$r?$c?f($r-1,$c-1)+f($r,$c-1):f($r-1,$r-2):1;}

```

Try it online!

# PHP, 86 bytes

0-indexed

```
for(;$r++<$argn;)for($c=~0;++$c<$r;)$l=$t[$r][$c]=$c?$l+$t[$r-1][$c-1]:($l?:1);echo$l;

```

Try it online!

# PHP, 89 bytes

recursive function 0-indexed

```
function f($r,$s=NULL){$c=$s??$r-1;return$r>1?$c?f($r-1,$c-1)+f($r,$c-1):f($r-1,$r-2):1;}

```

Try it online!

# Answer
> 1 votes
# J, 17 bytes

```
0{]_1&({+/\@,])1:

```

Uses the triangle calculation method.

Try it online!

## Explanation

```
0{]_1&({+/\@,])1:  Input: integer n
               1:  The constant 1
  ]                Identity function, get n
   _1&(       )    Call this verb with a fixed left argument of -1 n times
                   on itself starting with a right argument [1]
             ]       Get right argument
       {             Select at index -1 (the last item)
            ,        Join
        +/\@         Find the cumulative sums
0{                 Select at index 0 (the first item)

```

# Answer
> 1 votes
# Python 3, 78 bytes

```
from math import*
f=lambda n:ceil(sum(k**n/e/factorial(k)for k in range(2*n)))

```

I decided to try and go a different route for calculation. This uses Dobinski's formula, 0-indexed, doesn't work for 0.

Try it online!

# Answer
> 1 votes
# Python 3, ~~68~~ 60 bytes

Simple recursive construction of the triangle, but it's wildly inefficient for practical purposes. Calculating up to the 15th Bell number causes TIO to time out, but it works on my machine.

This uses 1-indexing, and returns `True` instead of 1.

```
f=lambda r,c=0:r<1or c<1and f(r-1,r-1)or f(r-1,c-1)+f(r,c-1)

```

Try it online!

---

**Thanks to @FelipeNardiBatista for saving 8 bytes!**

# Answer
> 1 votes
# Pari/GP, 36 bytes

```
n->n!*Vec(exp(exp(x+O(x^n++))-1))[n]

```

Try it online!

# Answer
> 1 votes
# Alice, 22 bytes

```
/oi
\1@/t&wq]&w.q,+k2:

```

Try it online!

This uses the triangle method. For n=0, this calculates B(1) instead, which is conveniently equal to B(0).

### Explanation

This is a standard template for programs that take input in ordinal mode, process it in cardinal mode, and output the result in ordinal mode. A `1` has been added to the template to put that value on the stack below the input.

The program uses the stack as an expanding circular queue to calculate each row of the triangle. During each iteration past the first, one implicit zero below the stack becomes an explicit zero.

```
1     Append 1 to the implicit empty string on top of the stack
i     Get input n
t&w   Repeat outer loop that many times (push return address n-1 times)
q     Get tape position (initially zero)
]     Move right on tape
&w    On iteration k, push this return address k-1 times
      The following inner loop is run once for each entry in the next row
.     Duplicate top of stack (the last number calculated so far)
q,    Move the entry k spaces down to the top of the stack: this is the appropriate entry
      in the previous row, or (usually) an implicit zero if we're in the first column
+     Add these two numbers
k     Return to pushed address: this statement serves as the end of two loops simultaneously
2:    Divide by two: see below
o     Output as string
@     Terminate

```

The first iteration effectively assumes an initial stack depth of zero, despite the required 1 at the top of the stack. As a result, the 1 ends up getting added to itself, and the entire triangle is multiplied by 2. Dividing the final result by 2 gives the correct answer.

# Answer
> 0 votes
# Mathematica, 5 bytes

Definitely, Mathematica has built-in.

Try it online!

```
BellB

```

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


title: Zzub Zzif (reverse Fizz Buzz)

text:
# Question
Title: Zzub Zzif (reverse Fizz Buzz)
Given a snippet of ***fizz buzz*** output with all numbers removed, fill in the correct numbers with the lowest possible values such that the ***fizz buzz*** snippet is correct. For the purposes of this challenge, `fizz` and `buzz` have their usual values of 3 and 5, respectively.

If the input is an invalid sequence of `fizz`, `buzz` and empty lines, then instead output just `zzubzzif` (with or without newlines).

Input and output may be newline separated lines, or whatever array-of-strings format is convenient to your language.

You may ignore or do whatever you like with capitalisation.

You will need to choose to handle one or more of these: `fizzbuzz`, `fizz buzz`, `buzz fizz`, etc, but you must choose at least one of these formats.

You may assume that all input is some sequence of `fizz`, `buzz` and empty lines.

# Examples

Input:
```

fizz

```
Output:
```
2
fizz
4

```
Input:
```
buzz
fizz

```
Output:
```
buzz
fizz
7

```
Input:
```

fizzbuzz

```
Output:
```
13
14
fizzbuzz
16
17

```
Input:
```

```
Output:
```
1

```
Input:
```
fizz
fizz

```
Output:
```
zzubzzif

```
Input:
```

```
Output:
```
zzubzzif

```

# Answer
> 17 votes
# Java, 205 bytes

```
s->{o:for(int i=0,j,h=s.length;++i<16;){for(j=h;j-->0;)if(s[j].contains("fizz")^(i+j)%3<1||s[j].contains("buzz")^(i+j)%5<1)continue o;String z=i+"";for(j=1;j<h;)z+="\n"+(i+j++);return z;}return"zzubzzif";}

```

Takes a `String[]` as input and returns a `String`.

Expanded, runnable code:

```
public class C {

    static final java.util.function.Function<String[], String> f = s -> {
        o:
        for (int i = 0, j, h = s.length; ++i < 16;) {
            for (j = h; j --> 0;) {
                if (s[j].contains("fizz") ^ (i + j) % 3 < 1 ||
                    s[j].contains("buzz") ^ (i + j) % 5 < 1) {
                    continue o;
                }
            }
            String z = i + "";
            for (j = 1; j < h;) {
                z += "\n" + (i + j++);
            }
            return z;
        }
        return "zzubzzif";
    };

    public static void main(String[] args) {
        System.out.print(f.apply(new String[]{"fizz", "", "buzz"}));
    }
}

```

# Answer
> 8 votes
# C#, 212 bytes

I did the unthinkable. I used a `goto` statement to break out of a loop!

```
string[]R(string[]a){for(int i,l=a.Length,n=0;n++<15;){for(i=l;i-->0;)if(((n+i)%3<1?"fizz":"")+((n+i)%5<1?"buzz":"")!=a[i])goto z;for(i=l;i-->0;)a[i]=a[i]==""?""+(n+i):a[i];return a;z:;}return new[]{"zzubzzif"};}

```

This takes advantage of the fact that the sequence must start within the first 15 elements.

Indentation and new lines for readability:

```
string[]R(string[]a){
    for(int i,l=a.Length,n=0;n++<15;){
        for(i=l;i-->0;)
            if(((n+i)%3<1?"fizz":"")+((n+i)%5<1?"buzz":"")!=a[i])
                goto z;
        for(i=l;i-->0;)
            a[i]=a[i]==""?""+(n+i):a[i];
        return a;
    z:;
    }
    return new[]{"zzubzzif"};
}

```

# Answer
> 4 votes
# CJam, 72 bytes

```
"zzubzzif":MaqN/:Q,_F+{)_[Z5]f%:!MW%4/.*s\e|}%ew{:sQ1$A,sff&:s.e|=}=N*o;

```

The program will exit with an error if it has to print **zzubzzif**.

Using the Java interpreter, STDERR can be closed to suppress an eventual error message. If you try the program in the CJam interpreter, ignore all output after the first line.

### How it works

```
"zzubzzif" e# Push that string.
:Ma        e# Save it in M and wrap in in an array.
qN/:Q      e# Split the input into lines and save in Q.
,_F+       e# Count the lines and add 15 to a copy of the result.
{          e# For each integer I between 0 and lines+14:
  )_       e#   Increment I and push a copy.
  [Z5]     e#   Push [3 5].
  f%       e#   Map % to push [(I+1)%3 (I+1)%5].
  :!       e#   Apply logical NOT to each remainder.
  MW%4/    e#   Push ["fizz" "buzz"].
  .*       e#   Vectorized string repetition.
  s\       e#   Flatten the result and swap it with I+1.
  e|       e#   Logical OR; if `s' pushed an empty string, replace it with I+1.
}%         e#
ew         e# Push the overlapping slices of length "lines".
{          e# Find; for each slice:
  :s       e#   Cast its elements to string (e.g., 1 -> "1").
  Q1$      e#   Push the input and a copy of the slice.
  A,s      e#   Push "0123456789".
  ff&      e#   Intersect the slice's strings' characters with that string.
  :s       e#   Cast the results to string. This replaces "fizz", "buzz"
           e#   and "fizzbuzz" with empty strings.
  .e|      e#   Vectorized logical OR; replace empty lines of the input
           e#   with the corresponding elements of the slice.
  =        e#   Check the original slice and the modified input for equality.
}=         e# Push the first match or nothing.
           e# We now have ["zzubzzif"] and possibly a solution on the stack.
N*         e# Join the topmost stack item, separating by linefeeds.
o          e# Print the result.
;          e# Discard the remaining stack item, if any.

```

# Answer
> 1 votes
# Python, 176 Bytes

Could probably do a lot better, but first attempt at Golf. Tips appreciated :)

Shrunk

```
def f(a):l=len(a);g=lambda n:'fizz'*(n%3<1)+'buzz'*(n%5<1);r=range;return next(([g(x)or x for x in r(i%15,i%15+l)]for i in r(1,16)if all(g(i+x)==a[x]for x in r(l))),g(0)[::-1])

```

Original

```
def f(a):
  l = len(a)
  g = lambda n: 'fizz'*(n%3<1)+'buzz'*(n%5<1)
  r = range
  return next(
    (
      [g(x) or x for x in r(i % 15,i % 15 + l)]
      for i in r(1,16)
      if all(
        g(i + x) == a[x] for x in r(l)
      )
    ),
    g(0)[::-1]
  )

```

# Answer
> 1 votes
# Perl, 140 bytes

```
$f=fizz;$b=buzz;@a=<>;@x=map{s!\d!!gr.$/}@s=map{$_%15?$_%3?$_%5?$_:$b:$f:$f.$b}(++$c..$c+$#a)while$c<15&&"@x"ne"@a";print$c<15?"@s":zzubzzif

```

**Explanation**

1. `@a` is the array of input lines
2. Inside the `while` loop,
3. `@s` has the generated fizz-buzz sequence
4. `@x` is the same as `@s` but with numbers replaced with empty strings and a new line appened to every element (to match with `@a`)
5. `$c` is a counter from 1 to 15
6. The loop runs till `@x` becomes the same as the input `@a`
7. Outside the loop, the output is `@s` or zzufzzib based on whether `$c` was in its limits or not

# Answer
> 1 votes
# JavaScript (Node.js), 127 bytes

```
f=(n,j=1)=>j<99?(M=n.map((e,i)=>e?e:j+i)).some((e,i)=>e!=((J=j+i)%3?J%5?J:'buzz':'fizz'+(J%5?'':'buzz')))?f(n,j+1):M:'zzubzzif'

```

Try it online!

I came across this challenge by accident after clicking on one of the answerers' profiles. Expects an array of lowercase strings.

## How?

FizzBuzz loops every 15 lines, which means that we can reasonably expect that by the time the start counter reaches 99, we will have looped through fizzbuzz a few times, hence allowing us to stop the recursion and instead output "zzubzzif".

If the counter is still less than 99, then we first fill in the falsy lines (empty strings) with their numbers, and check if it makes a valid FizzBuzz snippet using `some`. If one doesn't fit in, then recall the function with `j+1`. Otherwise return `M`.

# Answer
> 1 votes
# Python 2, 173 bytes

```
import re
def f(u,i=0,s=""):
 exec"s+=`i%3/2*'Fizz'+i%5/4*'Buzz'or-~i`+' ';i+=1;"*100;s=s.replace("'","");return re.findall(' '.join(['\d+'if not x else x for x in u]),s)[0]

```

Try it online!

# Answer
> 1 votes
# Vyxal, 200 bitsv2, 25 bytes

```
L:↵ƛ₍₃₅kF½ɽ*∑∴;l'vSǍ?⁼;h:[|kF⇩Ṙ

```

Try it Online!

Modern golfing languages with fractional byte encodings amiright.

I got this down from 27.something bytes to 25 bytes in drafts through a lot of fiddling with element ordering.

## Explained

```
L:↵ƛ₍₃₅kF½ɽ*∑∴;l'vSǍ?⁼;h:[|kF⇩Ṙ
L:↵ƛ₍₃₅kF½ɽ*∑∴;                   # Generate fizzbuzz for the first (10 ** len(input)) numbers using the standard fizzbuzz approach.
               l                  # in windows of len(input)
                '                 # filtered to keep only
                 vSǍ              #   windows where all converted to string with digits removed
                    ?⁼            #   exactly equals the input
                       h:[|kF⇩Ṙ   # if that's an empty list, return the string "zzibzzuf", else the first item.

```

---
Tags: code-golf, sequence, fizzbuzz
---


title: Encode the alphabet cipher

text:
# Question
Title: Encode the alphabet cipher
Given a string that contains only lowercase letters, encode that string with the alphabet cipher.

To encode with the alphabet cipher (I will be using the example `hello`):

1. First, convert each letter in the string to a number depending on its position in the alphabet (`a` = `1`, `b` = `2`, etc.) Example: `8` `5` `12` `12` `15`
2. Pad each number to two characters with `0`s. Example: `08` `05` `12` `12` `15`
3. Join. Example: `0805121215`

## Test cases

```
helloworld -> 08051212152315181204
codegolf -> 0315040507151206
alphabetcipher -> 0112160801020520030916080518
johncena -> 1015081403051401

```

Remember, this is , so the code with the fewest number of bytes wins.

# Answer
> 22 votes
# 05AB1E, ~~11~~ 6 bytes

**Code:**

```
Ç4+€¦J

```

**Explanation:**

First, we convert the string to their ASCII values. `codegolf` would become:

```
[99, 111, 100, 101, 103, 111, 108, 102]

```

To get to the indices of the alphabet, you subtract `96`:

```
[3, 15, 4, 5, 7, 15, 12, 6]

```

To pad with zeros, add `100` to each element and remove the first character of each int. For the above example, `+100` would be:

```
[103, 115, 104, 105, 107, 115, 112, 106]

```

And removing the first character of each would lead to:

```
[03, 15, 04, 05, 07, 15, 12, 06]

```

We can merge both steps above (the `-96` and the `+100`) part to just `+4`. For the code:

```
Ç       # Convert to an array of ASCII code points
 4+     # Add four to each element in the array
   €¦   # Remove the first character of each element
     J  # Join to a single string

```

Try it online!

# Answer
> 14 votes
# Python 2, 42 bytes

```
f=lambda s:s and`ord(s[0])+4`[1:]+f(s[1:])

```

Test it on Ideone.

# Answer
> 9 votes
# C, ~~55~~ 43 bytes

```
f(char*c){for(;*c;)printf("%02d",*c++-96);}

```

ideone

# Answer
> 9 votes
# Pyth, ~~11~~ 10 bytes

```
FNwpt`+4CN

```

Try it! My first go at Pyth.

```
FNwpt`+4CN
FNw         # For N in w (w is input, N will be single char)
   p        # Print without newline
        CN  # Int with code point `N`
      +4CN  # Add 4 to int with code point N
     `+4CN  # representation of above (basically to string)
    t`+4CN  # Tail (All but first character)

```

Python equivalent:

```
for N in input():
    print(repr(ord(N) + 4)[1:], end='')

```

# Answer
> 7 votes
# Python, 46 bytes

```
lambda x:"".join("%02i"%(ord(j)-96)for j in x)

```

Pretty straightforward. **Try it on repl.it!**

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

```
O+4ṾḊ$€

```

**TryItOnline**

### How?

```
O+4ṾḊ$€ - Main link: s                                e.g. hello
O       - cast to ordinals                            e.g. [ 104,  101,  108,  108,  111]
 +4     - add 4                                       e.g. [  108,  109,  112,  112,  115]
     $€ - last two links as a monad for €ach
   Ṿ    -    uneval, effectively converts to strings  e.g. ["108","109","112","112","115"]
    Ḋ   -    dequeue, remove the leading '1'          e.g. [ "08", "09", "12", "12", "15"]
        - implicit print                              e.g. "0809121215"

```

# Answer
> 4 votes
# Haskell, ~~fortyfour 30~~ 28 bytes

```
(>>=tail.show.(+4).fromEnum)

```

Using the `+4` approach from Adnan's answer saves 14 bytes.

Try it on Ideone. Usage:

```
> (>>=tail.show.(+4).fromEnum)"codegolf"
"0315040507151206"

```

Two bytes off thanks to xnor. Old version:

```
f a=['0'|a<'k']++(show$fromEnum a-96)
(f=<<)

```

# Answer
> 3 votes
# JavaScript (ES6), ~~52~~ 49 bytes

```
f=s=>s&&(s.charCodeAt()+4+f(s.slice(1))).slice(1)

```

Recursion turned out to be 3 bytes shorter than `.replace`:

```
s=>s.replace(/./g,s=>(s.charCodeAt()+4+"").slice(1))

```

`parseInt(s,36)` is slightly longer for each approach, because you have to change `4` to `91`:

```
s=>s.replace(/./g,s=>(parseInt(s,36)+91+"").slice(1))
f=s=>s&&(parseInt(s[0],36)+91+f(s.slice(1))).slice(1)

```

# Answer
> 3 votes
## Perl, 29 bytes

28 bytes of code + `-n` flag.

```
printf"%02s",-96+ord for/./g

```

Run with :

```
perl -ne 'printf"%02s",-96+ord for/./g' <<< "helloworld"

```

# Answer
> 3 votes
# Japt, 10 bytes

```
¡4+Xc)s s1

```

Probably doesn't get shorter than this...

**Test it online!**

## Explanation

```
¡           // Map each char X in the input by this function:
 4+Xc)      //   Take 4 + the char code of X.
      s s1  //   Convert to a string, then remove the first char.
            // Implicit: output last expression

```

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

*1 byte saved thanks to @Luis*

```
4+!V4LZ)!le

```

**Try it Online**

# Answer
> 3 votes
# Java 7,60 bytes

```
void f(char[]s){for(int i:s)System.out.printf("%02d",i-96);}

```

# Answer
> 3 votes
# Hexagony, 33 bytes

```
10}{'a({=!{{\.@29$\,<.-":!\>Oct\%

```

Try it Online!

Mm.. got a few no-ops in the Hexagon so I put today's date in.

## Expanded Form with date replaced by no-ops

```
   1 0 } {
  ' a ( { =
 ! { { \ . @
. . $ \ , < .
 - " : ! \ >
  . . . \ %
   . . . .

```
1. Initialise a `10` and move Memory Pointer to somewhere...
2. `$` skips the mirror and `,` reads a byte. `<` branches:
3. If end of string (`-1` which is non-positive) it goes to `@` and terminates the program.
4. Otherwise it subtracts `95` (decremented `a`), and then we print `result / 10` (integer division) and `result % 10` and loop again.

# Answer
> 3 votes
# Stax, 5 bytes

```
öÇIªÆ

```

Run and debug it

For each character

* add 4 to the codepoint e.g. `108`
* convert to string e.g. `"108"`
* drop the first character e.g. `"08"`

# Answer
> 3 votes
# APL (Dyalog Unicode), ~~19~~ 12 bytes SBCS

```
        ⎕UCS  ⍝ Convert the argument (string) into an array of codepoints.
      4+      ⍝ and add 4 to each of those codepoints.
     ¨        ⍝ Now, for each of those numbers
    ⍕         ⍝ turn it into a string
   ∘          ⍝ and
 1↓           ⍝ drop its first character.
∊             ⍝ Finally enlist the strings into a single string (as in, join them together)

```

Thanks @Bubbler for saving 7 bytes

## my original 19 bytes

```
{,/{1↓⍕⍵}¨4+⎕UCS ⍵}

```

Try it online!

```
{                   } ⍝ Define a function taking a string as argument.
             ⎕UCS ⍵  ⍝ Convert the argument (string) into an array of codepoints.
           4+         ⍝ and add 4 to each of those codepoints.
   {     }¨           ⍝ For each number in the array,
      ⍕⍵             ⍝ convert it to a string
    1↓                ⍝ and drop the first character (the 1).
 ,/                   ⍝ Finally join everything and return.

```

# Answer
> 3 votes
# Vyxal `s`, 6 bytes

```
C4+ƛSḢ

```

*-1 byte thanks to @Steffan*

Try it Online!

Explanation:

```
C       # Convert to ASCII codes
 4+     # Add 4
   ƛ    # On each number:
    S   #   Stringify
     Ḣ  #   Remove first char

```

# Answer
> 2 votes
# Vim, 60 keystrokes

```
:s/./\=char2nr(submatch(0))-96."\r"/g
:%s/\<\d\n/0&
V{gJ

```

An *almost* entirely regex based solution. As usual, using the eval register makes it obscenely long.

# Answer
> 2 votes
## Batch, ~~256~~ ~~239~~ 237 bytes

```
@echo off
set/ps=
set r=
set a=abcdefghijklmnopqrstuvwxyz
:g
set c=%a%
for /l %%i in (101,1,126)do call:l %%i
set s=%s:~1%
if not "%s%"=="" goto g
echo %r%
exit/b
:l
set i=%1
if %c:~,1%==%s:~,1% set r=%r%%i:~1%
set c=%c:~1%

```

Takes input on STDIN.

# Answer
> 2 votes
# PHP, 58 Bytes

```
foreach(str_split($argv[1])as$c)printf("%02d",ord($c)%32);

```

# Answer
> 2 votes
## PowerShell v2+, 44 bytes

```
-join([char[]]$args[0]|%{"{0:D2}"-f($_%32)})

```

Takes input `$args[0]`, casts it as a `char`-array, feeds into a loop. Each iteration, we take the current character `$_` modulo `32`, which implicitly casts as the ASCII value. Conveniently ;-), this lines up so `a = 1, b = 2`, etc. That fed into the `-f`ormat operator, operating on string `"{0:D2}"`, which specifies a two digit minimum (i.e., it prepends a leading zero if required). Those strings of digits are encapsulated in parens, `-join`ed together into one string, and left on the pipeline. Output via implicit `Write-Output` happens at program conclusion.

```
PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'hello'
0805121215

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'helloworld'
08051212152315181204

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'codegolf'
0315040507151206

PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'johncena'
1015081403051401

```

# Answer
> 2 votes
# Perl, 24 bytes

Includes +1 for `-p`

Give input on STDIN:

```
encode.pl <<< hello

```

`encode.pl`

```
#!/usr/bin/perl -p
s/./substr 4+ord$&,1/eg

```

# Answer
> 2 votes
# DASH, 27 bytes

```
@><""(->@rstr["."""]+4#0)#0

```

Example usage:

```
(@><""(->@rstr["."""]+4#0)#0)"helloworld"

```

# Explanation

```
@ (                         #. take input through a lambda
  join "" (                 #. join with newlines the following:
    (map                    #. result of mapping
      @ (                   #. this lambda
        rstr ["." ; ""] (     #. replace first char w/ empty string:
          + 4 #0               #. mapped item's codepoint + 4
        )
      )
    ) #0                    #. over the argument
  )
)

```

# Answer
> 2 votes
# IBM PC DOS 8088 Assembly, ~~33~~ ~~28~~ 27 bytes

Assembled binary:

```
00000000: be82 00ac 2c60 7812 d40a 0530 3092 86f2  ....,`x....00...
00000010: b402 cd21 86f2 cd21 ebe9 c3              ...!...!...

```

Unassembled:

```
BE 0082     MOV  SI, 82H        ; point SI to command line string
        CH_LOOP:
AC          LODSB               ; load next char into AL
2C 60       SUB  AL, 'a'-1      ; convert ASCII to a=1,b=2...z=26
78 12       JS   DONE           ; if char is terminator or not valid, exit
D4 0A       AAM                 ; convert binary to BCD
05 3030     ADD  AX, '00'       ; convert BCD to ASCII
92          XCHG DX, AX         ; save AX to DX for display
86 F2       XCHG DH, DL         ; reverse bytes
B4 02       MOV  AH, 2          ; DOS display char function
CD 21       INT  21H            ; write first digit
86 F2       XCHG DH, DL         ; reverse bytes back
CD 21       INT  21H            ; write second digit
EB E9       JMP  CH_LOOP        ; restart loop
        DONE:
C3          RET                 ; return to DOS

```

Standalone PC DOS executable. Input string from command line, output to console.

I/O:

# Answer
> 2 votes
# Piet \+ ascii-piet, 44 bytes (2×22=44 codels)

```
tuuuumknnfbkqmkcalrmu_sajs?daltdddbfckkkkk ?

```

Try Piet online!

Input the string with the sentinel value `_`.

### Pseudocode

```
while true:
  S = character input
  n = (codepoint of S) - 96
  if n+1 == 0:
    exit
  else:
    print(floor(n/10))
    print(n modulo 10)

```

# Answer
> 2 votes
# BQN, 16 bytes

```
∾·(1↓•Fmt)¨4+-⟜@

```

Try it at BQN online!

### Explanation

Same approach, independently derived, as RGS's APL answer and tybocopperkettle's Vyxal `s` answer.

```
∾·(1↓•Fmt)¨4+-⟜@
             -⟜@  Subtract null byte from each character, giving its ASCII value
           4+      Add 4 (a = 101, z = 126)
  (      )¨        Map this function to each number:
     •Fmt            Format as string
   1↓                Drop first character
∾·                Join together into a single string

```

# Answer
> 2 votes
# , 25 22 15 bytes

```
[:,4}.@":@+3&u:

```

Try it online!

*-7 bytes thanks to ngn's K approach*

# Answer
> 2 votes
# K (ngn/k), 8 bytes

```
,/1_'$4+

```

Try it online!

`4+` add 4 to (the ASCII codes of) the argument - this turns `a` into 101, `b` into 102, etc

`$` format numbers as strings

`1_'` drop one digit from each

`,/` concatenate

# Answer
> 2 votes
# Knight, ~~45~~ 41 bytes

*-4 thanks Aiden*

```
;=xP W<1Lx;O++*'0'-2L=a-Ax 96a'\'=xSxF1""

```

Try it online!

# Answer
> 1 votes
# MATL, 11 bytes

```
96-OH&YA!1e

```

Try it online!

```
         % Implicit input
96-      % Subtract 96. So 'a' becomes 1, 'b' becomes 2 etc
OH&YA    % Convert each number to 2 decimal digits. Gives a 2-column matrix
!1e      % Transpose and linearize into a row
         % Implicit display

```

# Answer
> 1 votes
## Ruby, ~~53~~ 46 bytes

~~`->s{s.chars.map{|c|(c.ord-96).to_s.rjust(2,?0)}.join}`~~

`->s{s.chars.map{|c|(c.ord+4).to_s[1..2]}.join}`

# Answer
> 1 votes
# R, ~~71~~ 51 bytes

Saved 20 bytes thanks to Billywob. Takes input from stdin and outputs to stdout.

```
cat(sprintf("%02d",utf8ToInt(scan(,""))-96),sep="")

```

Examples:

> helloworld -\> 08051212152315181204
>
> codegolf -\> 0315040507151206
>
> alphabetcipher -\> 0112160801020520030916080518
>
> johncena -\> 1015081403051401

# Answer
> 1 votes
# Labyrinth, 40 bytes

```
      ,")@
!{_10%! (
/       _
01_}:-69"

```

# Answer
> 1 votes
# Actually, 10 bytes

Using the neat algorithm in Adnan's 05AB1E answer. Golfing suggestions welcome. Try it online!

```
O4+`$pX`MΣ

```

**Ungolfing**

```
         Implicit input s.
O        ord() every char in s.
4+       Add 4 to every ord in s.
`...`M   Map the following function over s. Variable m.
  $        Push str(m).
  pX       Discard the first char of str(m).
           Invariably this is a `1` and we get our ciphered m.
Σ        sum() everything to get one string.
         Implicit return.

```

# Answer
> 1 votes
# Python 2, ~~51~~ ~~49~~ ~~45~~ 42 bytes

```
lambda x:"".join(`ord(i)+4`[1:]for i in x)

```

Try it online!

*Golfed to 49 bytes because .join will accept generators too*

*Golfed to 45 bytes because of lambdas*

*Golfed to 42 bytes because of switching to Python 2 and using ```` (repr)*

**EXPLANATION:**

Uses the trick in the 05AB1E answer.

```
lambda x:                               Declare a lambda accepting the string
    "".join(                            Join by the empty string
         `                              Repr (string representation)...
             ord(                       Unicode codepoint (A -> 65, a -> 97)
                 i                      The iterator in the for loop
             )
             + 4                        Added by 4
         `
         [1:]                           With the first character removed
    ) for i in x                        While a char i is in the string x

```

# Answer
> 1 votes
# Powershell, ~~39~~ 33 bytes

*Inspired by AdmBorkBork's answer.*

-6 bytes thanks @Julian

```
-join($args|%{'{0:D2}'-f($_-96)})

```

Try it online!

# Answer
> 1 votes
# Python 3, 47 bytes

```
f=lambda x:"".join(f"{ord(j)-96:02}"for j in x)

```

Try it online!

# Answer
> 1 votes
# Whitespace, 84 bytes

```
[N
S S N
_Create_Label_LOOP][S S S N
_Push_0][S N
S _Dupe_0][T    N
T   S _Read_STDIN_as_char][T    T   T   _Retrieve_input][S S S T    T   S S S S S N
_Push_96][T S S T   _Subtract][S N
S _Dupe][S S S T    S T S N
_Push_10][T S S T   _Subtract][N
T   T   S N
_If_neg_jump_to_Label_PRINT_0][N
S S T   N
_Create_Label_DONE_WITH_PRINT_0][T  N
S T _Print_as_integer][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_0][S S S N
_Push_0][T  N
S T _Print_as_integer][N
S N
T   N
_Jump_to_Label_DONE_WITH_PRINT_0]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Start LOOP:
  Integer c = STDIN as character
  c = c - 96
  If(c < 10):
    Print 0 as integer to STDOUT
  Print c as integer to STDOUT
  Go to next iteration of LOOP

```

# Answer
> 1 votes
# K (oK), 13 bytes

**Solution:**

```
,//$3 10\'96!

```

Try it online!

**Explanation:**

```
,//$3 10\'96! / the solution
          96! / input modulo 96
    3 10\'    / convert to base 30ish
   $          / convert to string
,//           / flatten (,/) over (/)

```

# Answer
> 1 votes
# Google Sheets, 76 bytes

```
=ArrayFormula(Join(,Text(Code(Mid(A1,Row(Indirect("1:"&Len(A1))),1))-96,"00"

```

Sheets will automatically add three closing parentheses when you exit the cell.
Input is in cell `A1`

`Indirect("1:"&Len(A1))` returns a range as tall as the input is long.
`Row(Indirect(~))` returns the row numbers, so it's a list of numbers from 1 to the input length.
`Mid(A1,Row(~),1)` returns each character from the input, one at a time.
`Code(Mid(~))-96` returns the ASCII code for each character, down-shifted so `a` = `1`.
`Text(Code(~),"00")` pads the result above to two digits.
`Join(,Text(~))` joins all those padded results without a delimiter.
`ArrayFormula(Join(~))` makes all the stuff above operate on arrays. Without, the result would just be the first padded alphabet code: `helloworld` would return `08`.

# Answer
> 1 votes
# Labyrinth, 27 bytes

```
 ,_9 @
%! 6-:
0    _
1_!/01

```

Try it online!

### How it works

```
        Start at the first valid instruction, going right
,_96-:  Push a char, subtract 96, duplicate
@       If it's negative (EOF), turn left and terminate
        Otherwise it is positive. Turn right and follow the cycle
_10/!   Integer-divide by 10, pop and print as integer
_10%!   Modulo 10, pop and print as integer
        Re-enter the start of the program, looping until EOF

```

# Answer
> 1 votes
# K (ngn/k), ~~31~~ 29 bytes

```
,/{$[1=#$x;"0",$x;$x]}'-96+0+

```

Try it online!

Another function-less answer.

Explanation:

```
,/{$[1=#$x;"0",$x;$x]}'-96+0+       Main function.
                           0+       Convert each character to ASCII value.
                       -96+         Add with -96 for each of them
                      '             For each of the numbers
  {                  }              Execute a function that
   $[               ]               If
        $x                          The number converted to string
       #                            Length
     1=                             Is equal to 1
          ;"0",$x                   Then, pad "0" before the number
                 ;$x                Else, return the number converted to string
,/                                  Join

```

# Answer
> 1 votes
# Alice, 40 bytes

```
wi.hn$@'`-v
v o0'v$:a.<
v    <
>/ \K
  o

```

Try it online!

# Flattened

```
wi.hn$@'`-.a:$v'0o>/o\K  Full solution
              >   ^      (additional redirections)

wi.hn$@               K  Where there are characters to read on the input
       '`-               Get the letter position in the alphabet
          .a:$v'0o       If it is less than 10, print a leading 0
                    o    Then print the number

```

# Answer
> 1 votes
# Nibbles, 5.5 bytes (11 nibbles)

```
+.$>>`p+4o

```

Another port of Adnan's 05AB1E answer.
(Converting to base-10 digits and dropping the first one comes-out half-a-byte (1 nibble) longer: `+.$>>`@~+4o`).

```
 .$             # map over each character in the input:
   >>           #  drop the first element of
     `P         #  the string representation of
         o      #  the ASCII value
       +4       #  plus 4
+               # and finally concatenate it all

```

# Answer
> 0 votes
# Groovy, 51 Bytes

```
{it.collect{(((int)it-96)+"").padLeft(2,"0")}.join()}

```

# Answer
> 0 votes
## Pyke, 7 bytes

```
F.oOO`t

```

Try it here!

```
F       -  for i in input:
 .o     -       ord(i)
   OO   -      ^ + 4
     `  -     str(^)
      t -    ^[1:]
        - sum(^)

```

# Answer
> 0 votes
# Groovy - 31 bytes

Groovy conversion of NumberKnot's solution in java:

```
{it.each{printf("%02d",it-96)}}
```

Example here using various options:

http://ideone.com/vd0dTX

# Answer
> 0 votes
# Befunge-98, 19 bytes

```
#@~'`-:a/'0+,a%'0+,

```

# Answer
> 0 votes
# Swift 3, 51

Dependency: `Foundation` for `String(format:_:)`

`{$0.utf8.map{String(format:"%02d",$0-96)}.joined()}` // where `$0` is `String`

## Usage:

Test

`"codegolf".utf8.map{String(format:"%02d",$0-96)}.joined()`

or

`{$0.utf8.map{String(format:"%02d",$0-96)}.joined()}("codegolf")`

# Answer
> 0 votes
## C#, 54 bytes

```
s=>String.Join("",s.Select(n=>(n<106?"0":"")+(n-96)));

```

# Answer
> 0 votes
# MATLAB / Octave, ~~32~~ 24 bytes

```
@(s)sprintf('%02d',s-96)

```

## Explanation

1. `@(s)` denotes an anonymous function whose input is expected to be a string and stored in the variable `s`.
2. The ASCII code for the letter `a` is 97. Therefore, subtracting the input string by 96 coalesces the string so that it becomes an array transforming the string into an array of numbers enumerated from 1 to 26, so we're now at `input('','s')-96`.
3. Using `sprintf` with the formatting specifier `%02d` takes the numbers in the array and ensures that there are 2 digits to output for each number. The numbers are thus combined to a single string and we output a single string. We will also pad the first digit with a 0 in case there is only 1 digit in an array.

## Examples

```
>> f=@(s)sprintf('%02d',s-96)
>> f('helloworld')

ans =

08051212152315181204

>> f('codegolf')

ans =

0315040507151206

>> f('alphabetcipher')

ans =

0112160801020520030916080518

>> f('johncena')

ans =

1015081403051401

```

## Try it online!

Try it here with ideone.

# Answer
> 0 votes
## GolfSharp, 37 bytes

```
s=>s.s(n=>(n<106?"0":"")+(n-96)).j();

```

# Answer
> 0 votes
# Dart, 58 bytes

```
f(s)=>s.runes.map((t)=>'${t-96}'.padLeft(2,'0')).join('');

```

Try it online!

Other 58 bytes solution :

```
f(s)=>s.runes.map((t)=>(t>106?'0':'')+'${t-96}').join('');

```

Try it online!

# Answer
> 0 votes
# Rust, 197 191 181 bytes

```
|t:&String|->Option<String>{let a="abcdefghijklmnopqrstuvwxyz";let mut o=String::new();for c in t.chars(){let n=a.find(c)?+1;if n<10{o.push('0');}o.push_str(&n.to_string());}Some(o)

```

Reduced number of bytes thanks to Jonathan Fretch. Code should be runnable at https://repl.it/repls/RightMiniFunctions

Reduced number of bytes again thanks to ASCII-only.

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 43 bytes

```
n=>string.Concat(n.Select(c=>$"{c%32:D2}"))

```

Try it online!

# Alternative taking in a `List<char>`, 36 bytes

```
n=>n.ForEach(c=>Write($"{c%32:D2}"))

```

Try it online!

# Answer
> 0 votes
# Japt `-m`, 8 bytes

```
c +4 s Å

```

Run it online

# Answer
> 0 votes
## MBASIC, 112 bytes

I could save 8 bytes on line 2 if STR$() didn't insist on including a leading space.

```
1 INPUT S$:FOR I=1 TO LEN(S$):A=ASC(MID$(S$,I,1))-96:IF A<10 THEN O$=O$+"0"
2 O$=O$+MID$(STR$(A),2):NEXT:PRINT O$

```

Sample output

```
? alphabetcipher
0112160801020520030916080518

```

# Answer
> 0 votes
# GolfScript, 10 bytes

In GolfScript converting to a character is unneccecary because strings are character arrays.

```
{4+''+1>}%

```

Try it online!

## Explanation

```
{       }% # Foreach over the implicit codepoint list
 4+        # Add 4 to every item of the list
   ''+     # Convert to a string
      1>   # Filter out all characters after the 1st character,
           # Including the 1st character

```

# Answer
> 0 votes
# Erlang (escript), 39 bytes

The usual +4 approach.

```
f(X)->[tl(integer_to_list(I+4))||I<-X].

```

Try it online!

# Answer
> 0 votes
# PowerShell, 99 bytes

```
([char[]]"$args"|%{"0$((@(65..90|%{[char]$_})-join'').indexof($_.tostring().toupper())+1)"})-join''

```

Try it online!

# Answer
> 0 votes
# *Acc!!*, 55 bytes

```
N-6
Count i while _/5 {
Write _/10+39
Write _%10+48
N-6

```

Try it online!

### Explanation

```
# Read a character, subtract 6 from its charcode, and store in the accumulator
N-6
# Loop while the character was not newline (i.e. the accumulator is >= 5)
Count i while _/5 {
  # Subtract 90 from the accumulator, divide by 10, and output as a digit
  Write (_-90)/10+48
  # Output the accumulator mod 10 as a digit
  Write _%10+48
  # Read the next character
  N-6
}

```

# Answer
> 0 votes
# Knight, 49 bytes

```
;;;;=y""=xP=i 0W>+1Lx=i+1i=y+yG+4A Gx-i 1 1 1 2Oy

```

Try it online!

What a mess.

Ungolfed:

```
; = y ""
; = x PROMPT
; = i 0
; WHILE (> (+ 1 LENGTH (x)) (= i (+ 1 i))
    = y (+ y (GET (+ 4 (ASCII (GET x (- i 1) 1))) 1 2))
: OUTPUT y

```

# Answer
> 0 votes
# brev, 57 bytes

```
(over(display(pop(number->string(+(char->integer x)4)))))

```

Everyone came up with the +4 ♀

# Answer
> 0 votes
# CJam, 9 bytes

```
{i4+s1>}%

```

Try it online!

A function taking a string as input. Port of many other answers.

# Explanation

```
{      }% # for each value in the input
 i        # convert it into a number
  4+      # add 4 to it
    s     # convert it to a string
     1>   # drop the first character

```

A version which isn't a port, for fun:

# CJam, 11 bytes

```
{'`-sYTe[}%

```

Try it online!

# Explanation

```
{        }% # map the following across the input
 '`-        # subtract the codepoint of '`', 96, from each value
    s       # convert to a string
       e[   # and pad the left with
      T     # 0s to length
     Y      # 2

```

# Answer
> 0 votes
# Thunno 2 `JB`, 5 bytes

```
4+ıṘḣ

```

Attempt This Online!

Port of Adnan's 05AB1E answer.

#### Explanation

```
4+ıṘḣ  # Implicit input
       # Convert to codepoints
4+     # Add four
  ı    # Map:
   Ṙ   #  Convert to string
    ḣ  #  Remove the first item
       # Join the list
       # Implicit output

```

---
Tags: code-golf, string, number, alphabet, cipher
---