# Question
Title: Convert a string of binary characters to the ASCII equivalents
Take a string of binary characters separated by a space, and convert it to an ASCII string.

For example...

```
1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100

```

Would convert to...

```
Hello World

```

**This is a code-golf challenge so the shortest solution wins.**

# Answer
# JavaScript (ES6) 49 ~~55 56 64~~

```
s.replace(/\d+./g,x=>String.fromCharCode('0b'+x))

```

**Edit** Accepting @bebe suggestion - thanks
**Edit2** Didn't know about binary numeric literal - thanks @kapep
**Edit3** Wow 6 ~~not 4~~ bytes saved thx @ETHproductions

**Explanation** as requested in comments

`String.replace` can take 2 arguments:

* regular expression `/\d+./g` : one or more digits followed by one different character - the g flag specify to search the pattern more than once
* a function, here specified in arrow format, where the argument (x) wil be the found string (the sequence of digits eventually followed by a space) and the value of the function is what is replaced (in this case, the single character from the code).

It's worth noting that the at the end of the string the regexp matches the sequence of digits without a trailing space, in this case the dot matches the last digit. Try '123'.match(/(\d+)./) to verify.

(Still) one of the more verbose pieces of javascript ever...
(Assignment to string s not counted)

```
var s='1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100'
var x=
s.replace(/\d+./g,x=>String.fromCharCode('0b'+x))

console.log(x)
```
> 12 votes

# Answer
# Ruby, ~~36~~ 32

```
s.split.map{|x|x.to_i(2).chr}*""

```

## Or 31

```
s.gsub(/\w+ ?/){$&.to_i(2).chr}

```

Optimizations thanks to Chron
> 10 votes

# Answer
# Bash+common linux utils, 25 bytes

```
dc<<<2i$s[Pz0\<m]dsmx|rev

```

### dc explanation

* push 2 to the stack; pop and use as input radix
* push input string to stack (all values at once)
* Define recursive macro `m` to:
    + pop, then print value as ASCII
    + push stack depth to stack
    + push 0 to stack
    + pop top 2 stack values; compare and call `m` macro if stack non-empty
* duplicate top of stack (macro definition)
* pop and save macro to `m` register
* pop and execute macro

Because we push the whole binary string to the stack first, when we pop each value, we end up with the string reversed. So we use the `rev` utility to correct that.

### Example usage:

```
$ s="1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100"
$ dc<<<2i$s[Pz0\<m]dsmx|rev
Hello World
$

```
> 8 votes

# Answer
## PowerShell, 49

```
-join(-split$s|%{[char][convert]::toint32($_,2)})

```

EDIT: Didn't see the other PowerShell answer. But there is essentially only one way of solving this.
> 7 votes

# Answer
# C - ~~57~~ ~~43~~ 38/31

38 Byte version:

```
for(int*x=s;putchar(strtol(x,&x,2)););

```

Or only 31 bytes if s is a pointer:

```
while(putchar(strtol(s,&s,2)));

```

I don't think this is exactly how for and while loop are supposed to be used... but it works.
> 7 votes

# Answer
## Mathematica, 52 bytes

Ah, Mathematica's lovely function names

```
f=FromCharacterCode[#~FromDigits~2&/@StringSplit@#]&

```
> 6 votes

# Answer
## Powershell (52 49)

```
-join(-split$s|%{[char][convert]::ToInt16($_,2)})

```

Simple loop over binary string in $s. Having to include the \[convert\] kills my score though.

EDIT: There really is only one way of pulling this off in Powershell, wowie. Joey and I both got pretty much the same answer working independently!

Input:

```
1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100

```

Output:

```
Hello World

```
> 6 votes

# Answer
# Pyth, 12

```
smCv+"0b"dPZ

```

Note that s is not a legal variable in Pyth, so I used Z instead.

Explanation:

```
        print(
s             sum(
m                 map(lambda d:
C                     chr(
v                         eval(
+"0b"d                         "0b"+d)),
P                     split(
Z                           Z))))

```

Example:

```
=Z"<the binary string from above>"smCv+"0b"dPZ
Hello World

```
> 6 votes

# Answer
## x86 machine code on DOS - 22 bytes

```
00000000  30 d2 b4 08 cd 21 2c 30  72 06 d0 e2 08 c2 eb f2  |0....!,0r.......|
00000010  b4 02 cd 21 eb ea                                 |...!..|

```

Since there are no real string variables in machine code (and in particular, no variables named "`s`") I settled for stdin as input.

NASM input:

```
    org 100h

section .text

start:
    xor dl,dl
loop:
    mov ah,8
    int 21h
    sub al,'0'
    jb print
    shl dl,1
    or dl,al
    jmp loop
print:
    mov ah,2
    int 21h
    jmp start

```
> 6 votes

# Answer
## Perl 33 32

Edit: Updated solution, 32.

```
say$s=~s/\d+ ?/chr oct"0b$&"/rge

```

Previous solution (33):

```
$_=$s;say map{chr oct"0b$_"}split

```

or

```
say map{chr oct"0b$_"}split/ /,$s

```

Test:

```
perl -E '$s="1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100";$_=$s;say map{chr oct"0b$_"}split'

```
> 5 votes

# Answer
## J (23)

```
u:;(#.@:("."0))&.>cut s

```

Test:

```
   s=:'1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100'
   u:;(#.@:("."0))&.>cut s
Hello World

```

Explanation:

```
                  cut s    NB. split S on spaces
   (          )&.>         NB. for each element
        ("."0)             NB. evaluate each character
      @:                   NB. and
    #.                     NB. convert bitstring to number
  ;                        NB. unbox each number
u:                         NB. convert to ASCII

```
> 5 votes

# Answer
## Python shell  44  40 chars

```
''.join(chr(int(x,2))for x in s.split())

```

Thanks for the help Griffin.
> 4 votes

# Answer
# Golfscript - 21

```
' '/{1/{~}%2base}%''+

```

You can test it here.
> 4 votes

# Answer
## APL (15)

```
⎕UCS{2⊥⍎¨⍕⍵}¨⍎s

```

Test:

```
      s←'1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100'
      ⎕UCS{2⊥⍎¨⍕⍵}¨⍎s
Hello World

```

Explanation:

* `⍎s`: evaluate `s`, turning it into an array of integers. Arrays are written as numbers separated by spaces, so this splits `s`.
* `{`...: for each element:
    + `⍕⍵`: turn the number back into a string
    + `⍎¨`: evaluate each individual digit, giving a bitstring
    + `2⊥`: base-2 decode, giving the numbers
* `⎕UCS`: get the character for each number
> 4 votes

# Answer
# PHP (61)

```
<?=join(array_map('chr',array_map('bindec',explode(' ',$s))))

```
> 4 votes

# Answer
## Bacchus, 25 bytes

```
S,' 'j:A=(Ö,2,10b:c),A¨

```

Explanation:

`S,' 'j` split the String S by the empty space and converts it to a block (some sort of array).

`:A=` get the previous Block and assing it to A variable.

`(),A¨` for Each element in A

`Ö,2,10b` Read the current element (represent by `Ö`) in base 2 and transform it to base 10.

`:c` get the previous value and print as char
> 4 votes

# Answer
## GolfScript 23

```
' '/{[{49=}/]2base}%''+

```

Online test here.
> 3 votes

# Answer
# C - 63

since C has no base 2 converter in standard library: test here
edit: there is, i'm just too stupid to know about it

```
r;f(char*s){for(;*s;(*s|32)-32||(putchar(r),r=0))r=2*r|*s++&1;}

```
> 3 votes

# Answer
# Run Length Encoded Brainfuck, 49 bytes

Since there are no variables in Brainfuck, I just used standard input and output instead.

The code `32+` should be interpreted as 32 `+`s by the interpreter. Just replace them manually if your interpreter doesn't support RLE.

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

```

Expanded (non-RLE) version: (91 bytes)

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

```

The code assumes that EOF is encoded as 0.

## Explanation

The following layout is used:

```
+---+---+------+
| x | a | flag |
+---+---+------+

```

Where `x` is the ASCII byte to be printed, `a` is the a character from standard input and `flag` is 1 if `a` was a space.

```
>,            Read a character a into the second cell
[             While not EOF:
  32-           Decrease a by 32 (a -= ' ')
  >+<           Set the flag to 1
  [             If a was not a space:
    16-           Decrease by 16 more ('0' == 32+16)
    <[>++<-]      a += 2*x
    >[<+>-]       Move it back (x = a)
    >-<           Reset the flag, it was not a space.
  ]>
  [             If a was a space (flag == 1):
    <<.[-]        Print and reset x
    >>-           Reset the flag
  ]
  <,            Read the next caracter a
]
<.            Print the last character x

```
> 3 votes

# Answer
# Java 8 : 60 bytes

Using lambdas in Java 8 (75 bytes):

```
Arrays.stream(s.split(" ")).reduce("",(a,b)->a+(char)Byte.parseByte(b,2));

```

And if you allow static imports (which some here used) it is (61 bytes):

```
stream(s.split(" ")).reduce("",(a,b)->a+(char)parseInt(b,2))

```

A tiny bit shorter version using for loop (60 bytes):

```
for(String n:s.split(" ")){out.print((char)parseInt(n,2));}

```
> 3 votes

# Answer
# Clojure 63 (or 57)

The all-Clojure impl:

```
(apply str(map #(char(read-string(str"2r"%)))(re-seq #"\d+"s)))

```

With Java interop:

```
(apply str(map #(char(Long/parseLong % 2))(.split s" ")))

```

REPL session:

```
golf> (def s "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100")
#'golf/s
golf> (apply str(map #(char(read-string(str"2r"%)))(re-seq #"\d+"s)))
"Hello World"
golf> (apply str(map #(char(Long/parseLong % 2))(.split s" ")))
"Hello World"

```
> 3 votes

# Answer
# QBasic, 103

```
s$=s$+" ":FOR i=1 TO LEN(s$):c$=MID$(s$,i,1):IF c$=" "THEN n=0:r$=r$+CHR$(n)ELSE n=n*2+VAL(c$)
NEXT:?r$

```

What? We have no fancy binary-to-decimal functions here. Do it yourself!

I'm counting the newline (which I think is necessary to get the if-then-else without an `END IF`) as one byte, per this meta post. I don't know whether QB64 on Windows would accept a code file that way or not. Probably doesn't much matter.
> 3 votes

# Answer
# Haskell -- 48 (+13 imports (?))

Here's my first golf attempt in Haskell.

```
map(chr.foldl1((+).(*2)).map digitToInt)$words s

```

You need to import Data.Char

usage (in ghci):

```
Prelude> :m +Data.Char
Prelude Data.Char> let s = "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100"
Prelude Data.Char> map(chr.foldl1((+).(*2)).map digitToInt)$words s
"Hello World"

```

Explanation:

```
map(chr.foldl1((+).(*2)).map digitToInt)$words s
                                        $words s -- split s on spaces into a list
                         map digitToInt          -- convert each digit in input string to int
              ((+).(*2))                         -- a function that multiplies its first
-- argument by 2, then adds the second argument
        foldl1((+).(*2)).map digitToInt          -- fold the above over the list of ints:
-- in other words this is a function that reads strings as binary and gives the value as int
   (chr.foldl1((+).(*2)).map digitToInt)         -- cast to character
map(chr.foldl1((+).(*2)).map digitToInt)$words s -- map our function over the list of words

```
> 2 votes

# Answer
**NodeJS****62**

```
Buffer(s.split(' ').map(function(a){return parseInt(a,2)}))+''

```

**PHP****75**

```
array_reduce(explode(' ', $b),function($a,$b){return $a.chr(bindec($b));});

```
> 2 votes

# Answer
# JavaScript 111

This does the number conversion without parseInt or eval. Reading the string backwards and counting bits it set's bit x if it's a one. When a space is found a the number is converted to a char and a new 0 number is started for setting bits.

```
x=n=0,w='',s=' '+s
for(i=s.length;i--;){m=s[i]
if(m==1)n|=1<<x
x++
if(m==' ')w=String.fromCharCode(n)+w,n=x=0
}

```
> 2 votes

# Answer
# Groovy 64

```
{it.split(" ").collect{Integer.parseInt(it,2) as char}.join("")}

```
> 2 votes

# Answer
# CJam, 11 bytes

```
NS/{:~2bc}/

```

**s** isn't a legal variable name in CJam, so I chose **N** instead.

Try it online.

### Example run

```
$ cjam <(echo '
> "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100"
> :N;
> NS/{:~2bc}/
> '); echo
Hello World

```

### How it works

```
NS/            " Split N at spaces.                            ";
   {     }/    " For each chunk:                               ";
    :~         "   Evaluate each character ('0' ↦ 0, '1' ↦ 1). ";
      2b       "   Convert from base 2 array to integer.       ";
        c      "   Cast to character.                          ";

```
> 2 votes

# Answer
# Zsh, ~~27 26~~ 22 bytes

*-1 from roblogic, -4 from a new strategy using an array and `${a/b/c}` replacement.*

```
printf %s ${(#)@/#/2#}

```

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

The `(#)` flag causes arithmetic expansion to be done to the contents of the parameter. Flags are parsed *after* the replacement. `#` matches the start of a string when at the start of a `${ / / }` pattern. So each parameter is `#` prefixed with `2#`, which Zsh recognizes as a base 2 number when `(#)` arithmetic expansion is done.

---

This relies on flexible I/O, each group of bits in its own parameter. This is what the pure bash answer does as well. To parse a single string, **+4 bytes** are needed: (Example)

```
printf %s ${(#)${=1}/#/2#}

```
> 2 votes

# Answer
# Vyxal `s`, 3 bytes

```
vBC

```

Try it Online!

## How?

```
vBC
vB   # Vectorized convert to decimal
  C  # Convert character codes to list of characters
     # S flag concatenates result

```

## If we *have* to receive input separated by spaces, then:

# Vyxal `s`, 4 bytes

```
⌈vBC

```

Try it Online!
> 2 votes

# Answer
# 05AB1E, 4 bytes

Saved 3 bytes thanks to @Emigna

```
#CçJ

```

Try it online!
> 1 votes

# Answer
# GNU Sed, 19 bytes

Inspired by an excellent @Digital Trauma answer.

**Golfed**

```
s/\w*/dc -e2i&P;/eg

```

**Test**

```
echo 1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100|\
sed 's/\w*/dc -e2i&P;/eg'

Hello World

```
> 1 votes

# Answer
# Pyth, 7 bytes

```
smCid2c

```

Takes input as string.

Try it!
> 1 votes

# Answer
# 05AB1E (legacy), 4 bytes

```
#CçJ

```

Try it online!

## Explanation:

```
#CçJ
#   : Split implicit input at spaces
 C  : Convert every element to int
  ç : chr(n)
   J: Join elements, push it to the stack for printing

```

**Edit:** I noticed I perfectly duplicated a previous answer by my own, but keep it.
> 1 votes

# Answer
# K4, 18 bytes

**Solution:**

```
"c"$2/:'"1"=" "\:s

```

**Example:**

```
q)s:"1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100"
q)k)"c"$2/:'"1"=" "\:s
"Hello World"

```

**Explanation:**

```
"c"$2/:'"1"=" "\:s / the solution
                 s / the input
            " "\:  / split (\:) on " "
        "1"=       / equal to "1" ?
    2/:'           / join (/:) each (') from base-2
"c"$               / cast to characters

```
> 1 votes

# Answer
# K (ngn/k), ~~15~~ 11 bytes

**Solution:**

```
`c$2/10\. s

```

Try it online!

**Explanation:**

```
`c$2/10\. s / the solution
          s / input s
        .   / value "1100" => 1100
     10\    / convert to base 10
   2/       / convert from base 2
`c$         / cast to character

```
* **-4 bytes** thanks to ngn!
> 1 votes

# Answer
# Python 3, 33 bytes

```
bytes(int(c,2)for c in s.split())

```

Try it online!

This solution outputs a byte string in Python. If it is required to return a regular Python string:

# Python 3, 42 bytes

```
bytes(int(c,2)for c in s.split()).decode()

```

Try it online!
> 1 votes

# Answer
# brainfuck, ~~74~~ 61 bytes

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

```

Try it online!

**Explanation:**

```
[tape: char, 'input, 16, 16]
[      else]

,[                      for each input
  >++++[>++++<-]>           set const 16
  [<+<-->>-]                decrement input by 32
  <<[                       if not input = space
    >[<->-]                     decrement input by 16
    <<[>++<-]                   add double of char to input
  ]
  <[                        else
    .                           print character
    [-]                         delete character
  ]
  >>>,                      input next character
]
<.                      print last character

```
> 1 votes

# Answer
# Python 3, 43 bytes

```
for i in s.split():print(end=chr(int(i,2)))

```

fixed a blunder! Thanks to @caird-coinheringaahing XD

Try it online!
> 1 votes

# Answer
# Perl 5 `-a`, 24 bytes

```
say map chr oct"0b$_",@F

```

Try it online!
> 1 votes

# Answer
# Pip, 10 bytes

```
C*FB*(a^s)

```

Sadly can't use the `-s` flag here.

Try it online!
> 1 votes

# Answer
# Scala 2.12, 47 bytes

```
_ split " "map(_./:(0)(_*2+_-48)toChar)mkString

```

Try it online!

Splits on spaces, maps each string representing a binary number to an integer, turns into a `Char`, and then joins all those characters together. Scala 2.12 is required because of postfix operators.
> 1 votes

# Answer
# , 32 bytes

```
{&a.@#.@(-&48)@(a.&i.);._2@,&' '

```

Try it online!
> 1 votes

# Answer
# Factor, 30 bytes

```
[ " "split [ bin> ] ""map-as ]

```

Try it online!
> 1 votes

# Answer
# Excel Insider Beta v2203+, 41 Bytes

Worksheet function that takes input from range `A1` and outputs to the calling cell.

Makes use of the `TextSplit(...)` function, one of many text and array functions added in Excel Insider Beta Version 2203.

```
=Concat(Char(Bin2Dec(TextSplit(A1," "))))

```
> 1 votes

# Answer
# Lua, 59 bytes

```
for k in s:gmatch'%d+'do io.write(s.char(tonumber(k,2)))end

```
> 0 votes

# Answer
# Erlang, 45 Bytes

```
[binary_to_integer(X,2)||X<-re:split(S," ")].

```

Strings are represented as a list of integers in Erlang. This returns a list of ASCII codes which, when printed, will be represented as a string if all ASCII codes are printable characters.
> 0 votes

# Answer
# REXX, 56 bytes (or 15)

```
o=
do w=1 to words(s)
  o=o||x2c(b2x(word(s,w)))
  end
say o

```

Alternatively, if the input values are an even 8 bits instead of varying in length as in the example, this may be shortened to just one line:

```
say x2c(b2x(s))

```
> 0 votes

# Answer
# AHK, 115 bytes

```
Loop,Parse,s," "
{x:=D(A_LoopField)
Send % Chr(x)
}
D(x){
Return (StrLen(x)>1?D(SubStr(x,1,-1))<<1:0)|SubStr(x,0)
}

```

The loop parses the string using a space as the delimeter.
The function `D(x)` converts `x` from binary to decimal.
The `Chr` function returns the ASCII character with the value `x`.
> 0 votes

# Answer
# Tcl, 46 bytes

```
proc B s {binary f B* [regsub -all " " $s ""]}

```

Try it online!

~~Tcl, 51 bytes
```
proc B s {binary format B* [regsub -all " " $s ""]}

```
Try it online!<br>~~
> 0 votes

# Answer
# q/kdb+, 22 bytes

**Solution:**

```
10h$0b sv'"1"=-8$" "vs

```

**Example:**

```
q)10h$0b sv'"1"=-8$" "vs"1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100"
"Hello World"

```

**Explanation:**

Split string on `" "`, left-pad each to 8 characters, return boolean list where each string is equal to `"1"`, convert each 8-bit list to a byte and then cast to a string:

```
10h$0b sv'"1"=-8$" "vs / the solution
                 " "vs / split (vs) on " "
              -8$      / pad ($) to 8-long, negative means left-pad
          "1"=         / is item in each list equal to 1, returns true (1) or false (0) for each
    0b sv'             / convert each (') from boolean list to bytes
10h$                   / cast ($) to character type (10h)

```
> 0 votes

# Answer
# Deorst, 11 bytes

```
o k`]mxmcE;

```

Try it online!

## How it works

Example input: `1001000 1100101`

```
o<space>    - Push a  space;    STACK = [' ', '1001000 1100101']
  k         - Turn off sort;    STACK = [' ', '1001000 1100101']
   `        - Split;            STACK = [['1001000', '1100101']]
    ]       - Flatten;          STACK = ['1001000', '1100101']
     mx     - Map from binary;  STACK = [72, 101]
       mc   - Map to character; STACK = ['H', 'e']
         E; - Concatenate;      STACK = ['H', 'e', 'He']

```
> 0 votes

# Answer
# Perl, 27 bytes

```
say pack"(B8)*",split' ',$s

```
> 0 votes

# Answer
# Julia 1.0, 40 bytes

```
join(Char.(parse.(Int,split(s),base=2)))

```

Try it online!
> 0 votes

# Answer
# Gol\>\<\>, ~~27~~ 24 bytes

```
IWaSD$|rlF2LX*}|lR+oiE;~

```

Try it online!

Explanation:

```
I                         //Read the next number as integer
 W                        //Loop to extract single digits
  aSD                     //  Perform a mod & div by 10 on the current number
     $|                   //  Repeat until the number is 0
       r                  //Reverse the stack to go from LSB to MSB
        lF                //Loop over all single bits and replace all 1's with their corresponding value
          2LX             //  Push 2^x where x is the number of the current bit -> value of topmost bit
             *            //  Multiply the value of the topmost bit with the bit itself
              }|          //  Shift right to get the next bit
                lR+       //Add all values on the stack together
                   o      //Output the decimal value as a char
                    iE;~  //Check for EOF if true terminate

```
> 0 votes

# Answer
# Common Lisp, 79 bytes

```
(map'string'code-char(let((*read-base* 2))(read-from-string(format()"(~a)"s))))

```

Try it online!
> 0 votes

# Answer
# Powershell, 48 bytes

*Inspired by Joey's and fuandon's answers.*

```
-join(-split$s|%{[char][convert]::ToByte($_,2)})

```
> 0 votes

# Answer
# Perl 6, 24 bytes

```
*.words>>.&{:2($_)}.chrs

```

Try it online!

Anonymous Whatever lambda that takes a string and returns a string.

### Explanation

```
*.words                   # Split by spaces
       >>.&{      }       # Map each word to
            :2($_)        # Parsing it as binary
                   .chrs  # Convert to characters

```
> 0 votes

# Answer
# Bash (Pure): 54

Pure **and** no fork!

```
f(){ for a;do printf -vv \\%o $[2#$a];printf $v;done;}

f 1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100
Hello World

```

### Explanation

* `f()` declare function f
* `for a;do ... done` take each argument successively and attrib them to variable `a` in loop
* `$[2#$a]` convert binary to decimal
* `printf -vv \\%o $...` convert decimal to octal, preceded by backslash `\` for next printf and attribute this to variable `v`.
* `printf $v` will render character.
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 61 bytes

```
s.Split(" ").Aggregate("",(a,b)=>a+(char)Convert.ToByte(b,2))

```

Splits the binary string, and adds each byte into the string. You need to have the seed for aggregate, or else the first byte won't be parsed.

Try it online!
> 0 votes

# Answer
# Japt `-P`, 4 bytes

```
¸®Íd

```

Try it

```
¸®Íd     :Implicit input of string
¸        :Split on spaces
 ®       :Map
  Í      :  Convert from binary string to integer
   d     :  Get character at that codepoint
         :Implicitly join & output

```
> 0 votes

# Answer
# Julia 1.0, 44 bytes

```
prod(Char.(parse.(Int,split(s," "),base=2)))

```

Try it online!
> 0 votes

# Answer
# Python 3, 55 bytes

```
lambda s:"".join(map(lambda b:chr(int(b,2)),s.split()))

```

Try it online!

Or 46 bytes if we return an iterator instead of a string:

```
lambda s:map(lambda b:chr(int(b,2)),s.split())

```

Try it online!
> 0 votes

# Answer
# TECO, 35 bytes

```
Z+1<0A"DQn*2#(0A-48)Un|QnI^[0Un'1:D>

```

`^[` stands for `esc`.

## Explanation

```
I1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100^[
! insert input string to the buffer !
J     ! reset to zero point !
Z+1<  ! loop over all chars !
0A"D  ! if the current char is a digit !
Qn*2#(0A-48)Un ! append the bit to register n !
D     ! remove current char !
|     ! else !
QnI^[ ! insert value of register n as ASCII !
0Un   ! clear n !
1:D   ! delete one char without signaling error !
'     ! end if !
>     ! end loop !
HT    ! type out result !

```
> 0 votes

# Answer
# JavaScript, 64 bytes

```
s=>s.replace(/\d+./g,c=>eval(`'\\x${('0b'+c|0).toString(16)}'`))

```

Try it online!

Trying something different to this JS answer, not sure if it can be shorter.
> 0 votes

# Answer
# Python 3, 48 44 bytes

```
[print(end=chr(int(i,2)))for i in s.split()]

```

Try it online!

previous answer,

```
[print(end=chr(eval('0b'+i)))for i in s.split()]

```

Try it online!

Learnt the `print(end=...)` trick in the "Scream the loudest" challenge. Pretty neat.

As far as I know, there is no direct conversion to ascii from binary string, so we have to suffer the `'0b'` in the `eval`.

Thanks to this python answer for giving `int(i,2)`
> 0 votes

# Answer
# Python 3, 53 bytes

```
lambda x:[print(end=chr(int(i,2)))for i in x.split()]

```

Try it online!

Used the `int(i,2)` to convert number from base 2 to 10. In-built functions for the win.
> 0 votes

# Answer
# Octave, 30 bytes

Nothing too fancy, but it's relatively short

```
@(x)['',bin2dec(strsplit(x))']

```

Try it online!

```
@(x)                            % Take x as input
@(x)            strsplit(x)     % split string at spaces and create a cell array
@(x)    bin2dec(strsplit(x))    % Convert each row to integers
@(x)    bin2dec(strsplit(x))'   % Transpose into column vector
@(x)['',bin2dec(strsplit(x))']  % Concatenate with the empty string to cast to chars

```
> 0 votes

# Answer
# Thunno 2 `J`, 3 bytes

```
OḂC

```

Attempt This Online!

But, if a list of strings was an allowed input format:

### Thunno 2 `J`, 2 bytes

```
ḂC

```

Attempt This Online!

#### Explanation

```
OḂC  # Implicit input
O    # Split on spaces
 Ḃ   # Convert from binary
  C  # Convert to characters
     # Implicit output

```
> 0 votes

# Answer
# Python, 46 bytes

```
''.join(map(lambda x:chr(int(x,2)),s.split()))

```
> -1 votes

---
Tags: code-golf, string, binary
---


title: Generate Pascal's triangle

text:
# Question
Title: Generate Pascal's triangle
Pascal's triangle is generated by starting with a 1 on the first row. On subsequent rows, the number is determined by the sum of the two numbers directly above it to the left and right.

To demonstrate, here are the first 5 rows of Pascal's triangle:

```
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

```

## The Challenge

Given an input *n* (provided however is most convenient in your chosen language), generate the first *n* rows of Pascal's triangle. You may assume that *n* is an integer inclusively between 1 and 25. There must be a line break between each row and a space between each number, but aside from that, you may format it however you like.

This is **code-golf**, so the shortest solution wins.

## Example I/O

```
> 1
1
> 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1

```

# Answer
## , 12 characters

```
":@(!{:)\@i.

```

---

```
   i.5
0 1 2 3 4
   {:i.5
4
   (i.5)!{:i.5
1 4 6 4 1
   (!{:)i.5
1 4 6 4 1
   (!{:)\i.5
1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1
   ":@(!{:)\i.5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
   (":@(!{:)\@i.)`''
+----------------------------------+
|+-+------------------------------+|
||@|+-------------------------+--+||
|| ||+-+---------------------+|i.|||
|| |||\|+-------------------+||  |||
|| ||| ||+-+---------------+|||  |||
|| ||| |||@|+--+----------+||||  |||
|| ||| ||| ||":|+-+------+|||||  |||
|| ||| ||| ||  ||2|+-+--+||||||  |||
|| ||| ||| ||  || ||!|{:|||||||  |||
|| ||| ||| ||  || |+-+--+||||||  |||
|| ||| ||| ||  |+-+------+|||||  |||
|| ||| ||| |+--+----------+||||  |||
|| ||| ||+-+---------------+|||  |||
|| ||| |+-------------------+||  |||
|| ||+-+---------------------+|  |||
|| |+-------------------------+--+||
|+-+------------------------------+|
+----------------------------------+

```
> 35 votes

# Answer
# Python, 56 Bytes

```
a=[1];exec"print a;a=map(sum,zip([0]+a,a+[0]));"*input()

```

Sample usage:

```
echo 9 | python filename.py

```

Produces:

```
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]

```
> 24 votes

# Answer
# C, 522

A self demonstrating C answer. Couldn't be clearer! Bonus points for finding the extra character.

```
#define returns return 0
#define fr for
#define twentyonechexpressis0 0
                                                                                i
                                                                               , x
                                                                              [ 52 ]
                                                                            [ 52] ,j, y
                                                                       ; main (c){fr (;i< c
                                                                    ; i++){ x[i][i]=x[ i][0]= 1
                                                         ; }for(i =2;i<c;i++){for (j=1;j<i;j++){x [i][j] =
                                    1 +x[i][j ]+x[i-1][j-1]+x[i-1] [j]+1-1+1-1+1-1+1-1+1-1+111-11- twentyonechexpressis0 -100-1; }
} ;for(i=0 ;i<c;i++){for(j=0;j<=i;j++){ printf("%3d%c",x[i][j],(1+1+1+1)*(1+1+1+1+1+1+1+1)) ;}putchar(1+1+(1<<1+1)+1+1+1+1+1+111111-111111-1);} /*thiscomment_takes28chars*/ returns; }

```
> 19 votes

# Answer
## Mathematica: 36 (41?)

Mathematica has the `Binomial` function, but that takes the fun out of this. I propose:

```
NestList[{0,##}+{##,0}&@@#&,{1},n-1]

```

The line above will render a ragged array such as:

```
{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1},
 {1, 5, 10, 10, 5, 1}, {1, 6, 15, 20, 15, 6, 1}}

```

Since this is a basic format in Mathematica I thought it would be acceptable, but as I read the rules again, I think it may not be. Adding `Grid@` will produce unequivocally acceptable output, for a total of **41** characters:

```
Grid@NestList[{0,##}+{##,0}&@@#&,{1},n-1]

```

`n = 6`:

```
1
1   1
1   2   1
1   3   3   1
1   4   6   4   1
1   5   10  10  5   1
1   6   15  20  15  6   1

```
> 16 votes

# Answer
## Python, 94 91 88 70 63 characters

```
x=[1]
for i in input()*x:
 print x
 x=map(sum,zip([0]+x,x+[0]))

```
> 16 votes

# Answer
### Golfscript (21 chars)

```
~]({0\{.@+\}/;1].p}*;

```

Since an explanation was requested:

```
# Stack contains 'n'
~](
# Stack: [] n
{
    # prev_row is [\binom{i,0} ... \binom{i,i}]
    # We loop to generate almost all of the next row as
    #     [(\binom{i,-1} + \binom{i,0}) ... (\binom{i,i-1} + \binom{i,i})]
    # \binom{i,-1} is, of course, 0
    # Stack: prev_row
    0\
    # Stack: 0 prev_row
    {
        # Stack: ... \binom{i,j-1} \binom{i,j}
        .@+\
        # Stack: ... (\binom{i,j-1} + \binom{i,j}) \binom{i,j}
    }/
    # Stack: \binom{i+1,0} ... \binom{i+1,i} \binom{i,i}
    # unless it's the first time round, when we still have 0
    # so we need to pop and then push a 1 for \binom{i+1,i+1}
    ;1]
    # next_row
    .p
}*
# final_row
;

```
> 14 votes

# Answer
# convey, 39 bytes

convey is a new 2d esolang I made. It is based on conveyor belts that move values around in a factory. `v<^>` are explicit belt directions, other connections are inferred, as each function has a fixed number of inputs and outputs. For example, `+` takes 2 values in and returns 1 value.

```
v<<<.~/.]
v>,v}"!{
"/&v}11
\v>+/^
$,^
_

```

Try it online!

A row enters the main part from the top left. Two tiles in, the row gets `"` copied down and right. The right part prepends a `_`, which is a so called 'default value'. The actual value of `_` depends on the function it enters. It works like the neutral element, thus `_ + 3 = 3`, `4 * _ = 4`.

To understand the next part we have to take a look at port order. For example, `,` will join two paths, favoring the main input port. The order is as follows (lower takes precedence):

```
For input:     For output:

   0                3
   v                ^
 1>f<3            2<f>0
   ^                v
   2                1

```

So the upper `,` will favor inputs from the left, and the lower `,` will favor inputs from the top. In the animation the arrow heads are drawn a bit thicker to indicate main ports.

On `/` (rising flank) whenever a new list enters the tile, `_` gets pushed to the side port. `_` and the row then get joined, whereas the `_` comes from the main port and thus has right of way. The bottom part appends a `_` by similar means: `\` (falling flank) pushes the length of the list to the side port, that will be set `$` to `_`.

Finally, `_ 1 2 1` and `1 2 1 _` get added in `+` and we get the next row `1 3 3 1`! We print a newline `/}` (`_` in `}` prints newlines) and then copy the row into the output `"}`. To prevent a row colliding with the next row when they get longer, we batch `~.` the lists: we first let 1 element through, then 2, then 3 … by getting the indices `/.` of an list of `n` 1s (`{!1`}), that get discarded in a sink `]`.
> 12 votes

# Answer
# Ruby: ~~51~~ ~~49~~ 46 characters

(45 characters code + 1 character command line option)

```
p=[];$_.to_i.times{n=0;p p.map!{|i|n+n=i}<<1}

```

Thanks to:

* jsvnm for suggesting an alternative for the value switching (2 characters)
* G B for spotting out a variable unused after previous improvement (4 characters)

Sample run:

```
bash-4.4$ ruby -ne 'p=[];$_.to_i.times{n=0;p p.map!{|i|n+n=i}<<1}' <<< 1
[1]

bash-4.4$ ruby -ne 'p=[];$_.to_i.times{n=0;p p.map!{|i|n+n=i}<<1}' <<< 9
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]

```

Try it online!
> 10 votes

# Answer
## Scala, ~~81~~ ~~78~~ ~~72~~ 70 characters

81 chars: first attempt, shamelessly copied from the Python version :)

```
var x=Seq(1)
for(i<-1 to args(0).toInt){println(x)
x=(0+:x,x:+0).zipped.map(_+_)}

```

Run it as a script, or directly in the REPL.

Cut to 70 chars with something surprisingly readable and idiomatic:

```
Seq.iterate(Seq(1),readInt)(a=>(0+:a,a:+0).zipped.map(_+_))map println

```

Or ~~72~~ 70 characters with a totally different method:

```
0 to(readInt-1)map(i=>println(0 to i map(1 to i combinations(_)size)))

```
> 9 votes

# Answer
# Keg, ~~40~~ 33 bytes

```
1:&¿1.
,(|(⑻|:⑻$@MCƒℤ. ,⑨)⑹_01.
,

```

Try it online!

## Old Program Explained
> 9 votes

# Answer
# Haskell, ~~94~~ 92

```
f=[1]:[zipWith(+)(0:x)x++[1]|x<-f]
main=readLn>>=mapM_(putStrLn.unwords.map show).(`take`f)

```

Output:

```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

```

A 71 character version which does not print a space between each number:

```
f=[1]:[zipWith(+)(0:x)x++[1]|x<-f]
main=readLn>>=mapM_ print.(`take`f)

```

Output:

```
[1]
[1,1]
[1,2,1]
[1,3,3,1]

```
> 8 votes

# Answer
# R, 39 chars

R seems to be the very right tool for this task :-)

```
x=1;for(i in 1:n)x=c(print(x),0)+c(0,x)

```
> 7 votes

# Answer
# Husk, ~~13~~ 10 bytes

*-3 bytes thanks to Zgarb*

```
mw↑¡Sż+Θ;1

```

Try it online!

### Explanation

Based on the same idea as my Pip answer: generate each row from the last one by tacking a 0 to the front of the row and adding it to itself element-wise. The Husk version creates the entire triangle as an infinite lazy list and then takes however many rows we need.

```
        ;1  Start with [1]
   ¡        Iterate this function:
    S        S-combinator: Sfgx is fx(gx) (aka f(x,g(x)) in C-style syntax)
     ż+       f: add a list itemwise to another list, keeping the extra value at
               the end of the longer list unchanged
       Θ      g: prepend a falsey value (given a list of integers, prepend 0)
             The result of Sż+Θ is a 1-argument function that prepends a 0 to its
              argument and adds that itemwise to another copy of the argument
  ↑         From the infinite list of results, take N (where N is the input)
mw          Join each sublist on spaces (which means the main list gets
             autojoined on newlines)

```
> 7 votes

# Answer
## JavaScript (90 85 83 81)

```
for(n=prompt(o=i='');i++<n;o+='\n')for(s=j=1;j<=i;s=s*(i-j)/j++)o+=s+' ';alert(o)

```

Demo: http://jsfiddle.net/tcRCS/3/

**NOTE**: Doesn't work well in practice for about n \> 30 because numbers overflow built-in integer data type and become floating-point numbers.

---

**Edit 1**: removed 5 characters by converting `while` to `for` and combining statements

**Edit 2**: move `s=` statement inside `for` and save 2 chars

**Edit 3**: combine `s=1,j=1` initializer into `s=j=1` and save 2 chars
> 6 votes

# Answer
## Perl, 52, 49 characters

Edit: using `say` instead of `print`

```
map{@_=(1,map$_[$_-1]+$_[$_],1..@_);say"@_"}1..<>

```
> 6 votes

# Answer
## in Q (25 characters/20 with shorter version)

```
t:{(x-1) (p:{0+':x,0})\1}

```

Shorter

```
t:{(x-1){0+':x,0}\1}

```

Sample usage:

```
q)t 4
1
1 1
1 2 1
1 3 3 1

```
> 6 votes

# Answer
# awk - 73 chars

fairly straightforward implementation:

```
{for(i=0;i<$1;++i)for(j=i;j>=0;)printf"%d%c",Y[j]+=i?Y[j-1]:1,j--?32:10}

```

sample run:

```
% awk -f pascal.awk <<<10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

```
> 6 votes

# Answer
# Perl, ~~47~~ 54 characters

```
$p=1;map{print"@{[split//,$p]}\n";$p*=11}1..<>

```

It takes a number from the command line, but doesn't perform any error checks.

Just realized it only works up to n=4. It was some old code I had on my hd.

This works though:

```
map{@a=(1,map$a[$_-1]+=$a[$_],1..@a);print"@a\n"}a..n

```

n has to be input into the script though, or it would be one character more.
> 5 votes

# Answer
# Pascal: ~~216~~ 192 characters

(Not a real competitor, just an honorific presence.)

```
var p:array[0..1,0..25]of LongInt;i,j,n,u:Word;begin
Read(n);u:=0;for i:=1to n do begin
p[1,1]:=1;for j:=1to i do begin
p[u,j]:=p[1-u,j-1]+p[1-u,j];Write(p[u,j],' ')end;u:=1-u;Writeln
end
end.

```

Sample run:

```
bash-4.2$ fpc pascal.pas
/usr/bin/ld: warning: link.res contains output sections; did you forget -T?

bash-4.2$ ./pascal <<< 1
1

bash-4.2$ ./pascal <<< 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1

```
> 5 votes

# Answer
## APL, ~~19~~ 15 characters

A bit late to the party, perhaps?

```
{⍪{⍵!⍨⍳⍵+1}¨⍳⍵}

```

It doesn't beat the J entry, though.

This assumes that the index origin (`⎕IO`) is set to `0`. Unfortunately, with an index origin of `1`, we need ~~25~~ 18 characters:

```
{⍪{⍵!⍨0,⍳⍵}¨1-⍨⍳⍵}

```

There are two s in the code to express my frustration.

Demo:

```
      {⍪{⍵!⍨⍳⍵+1}¨⍳⍵}5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

```

---

Explanations

Short version:

* `⍳⍵` (with an index origin of 0) produces an array of the numbers from 0 to `⍵-1` inclusive, where  is the right argument to the function.
* `⍳⍵+1` generates all numbers from 0 to
* `{⍵!⍨⍳⍵+1}` generates  choose `k` for every element `k` in `⍳⍵+1`. The  (commute) operator swaps the arguments to a function around, such that the right hand argument becomes the left, and vice versa.
* `{⍵!⍨⍳⍵+1}¨⍳⍵` passes each element in `⍳⍵` using the `¨` (each) operator. The result is a one dimensional array containing the first  rows of the Pascal's Triangle.
* The one argument form of  takes a one dimensional vector, and makes it a column rather than a row. Each row of the triangle is put on its own line.

Long answer:

* Virtually the same as the other version, except that `1-⍨` is placed before an  to replicate an index origin of 0.
* `0,⍳⍵` with an index origin of 1 replicates `⍳⍵+1` with an index origin of 0.
> 5 votes

# Answer
# Perl, 37 bytes

```
s/\d+/$&+$'/eg,say$_="1 $_"for($a)x<>

```

Try it online!
> 5 votes

# Answer
## Perl, 77 Chars

```
$o[0]=1;for(1..<>){$"=" ";for(1..$_){$n[$_]=$o[$_]+$o[$_-1]}@o=@n;print"@o
"}

```

Example input

```
5

```

Example output

```
 1
 1 1
 1 2 1
 1 3 3 1
 1 4 6 4 1

```
> 4 votes

# Answer
## C, ~~132~~ 127 characters

```
c[25][25],n,i,j;main(){for(scanf("%d",&n);i<n;i++)for(j=0;j<=i;j++)printf("%d%c",c[i][j]=j?c[i-1][j-1]+c[i-1][j]:1,i-j?32:10);}

```
> 4 votes

# Answer
# MATL, 10 bytes

*Language created after this challenge*

```
1iq:"tTTY+

```

**Try it online!**

```
1       % Push a 1. This will be the first row
iq:     % Take input n. Generate range [1,2,...,n-1]
"       % For each (that is, repeat n-1 times)
  t     %   Duplicate latest row
  TT    %   Push [1 1]
  Y+    %   Convolve latest row with [1 1] to produce next row
        % Implicitly end for each
        % Implicitly display stack contents

```
> 4 votes

# Answer
# JavaScript, ~~70~~ 69 bytes

Generating Pascal's Triangle in a golfy manner has always given me brain ache but every time it comes up, I give it another try. Last night, armed with a few beers, I finally cracked it and came up with a *working* solution I was happy with. Fitting, then, that this should be my 500th (undeleted) solution here.

0-indexed and includes a trailing newline and a trailing space on each line.

```
n=>(g=x=>x++>n?``:(h=z=>y>x?``:z+` `+h(z*(x-y)/y++))(y=1)+`
`+g(x))``

```

---

## Try it

```
o.innerText=(f=
n=>(g=x=>x++>n?``:(h=z=>y>x?``:z+` `+h(z*(x-y)/y++))(y=1)+`
`+g(x))``)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i type=number><pre id=o></pre>
```
> 4 votes

# Answer
## D ~~134~~ 128 chars

```
import std.stdio;void main(){int n,m;int[]l,k=[0,1];readf("%d",&n);foreach(i;0..n){writeln(l=k~0);k=[];foreach(e;l)k~=m+(m=e);}}

```

output for 9 is

```
>9
[0, 1, 0]
[0, 1, 1, 0]
[0, 1, 2, 1, 0]
[0, 1, 3, 3, 1, 0]
[0, 1, 4, 6, 4, 1, 0]
[0, 1, 5, 10, 10, 5, 1, 0]
[0, 1, 6, 15, 20, 15, 6, 1, 0]
[0, 1, 7, 21, 35, 35, 21, 7, 1, 0]
[0, 1, 8, 28, 56, 70, 56, 28, 8, 1, 0]

```

taking full advantage of "you may format it however you like"; there is a space between each number and a linebreak

edit repositioned the assignment to `l` to shave of some chars
> 3 votes

# Answer
## Scala, 131 characters

```
object P extends App{var x=List(1)
while(x.size<=args(0).toInt){println(x.mkString(" "))
x=(0+:x:+0).sliding(2).map(_.sum).toList}}

```

Takes the input from the command line.

Output for n=10:

```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

```
> 3 votes

# Answer
## F♯ - 203 characters

My first attempt at a round of code golf, and first attempt at functional programming. There is probably some obvious way to shorten it I haven't quite figured out yet. It complies in VS2010s F♯ compiler (which has the effect of running #light by default unlike earlier versions), and also works in the F♯ interpreter. Accepts input via stdin. Wish there was a better way for the input/output though! Lots of characters!

```
open System
let rec C r m =if r=0||m<=0||m>=r then 1 else C(r-1)m+C(r-1)(m-1)
for j = 0 to Convert.ToInt32(Console.ReadLine ()) do (
 [0..j]|>List.map(C j)|>List.iter(fun k->printf "%i " k)
 printf "\n")

```
> 3 votes

# Answer
*Why is there no accepted answer to this question?*

## VBA - 249 chars

```
Sub t(n)
ReDim a(1 To n,1 To n*2)
a(1,n)=1:y=vbCr:z=" ":d=z & 1 & z & y:For b=2 To n:For c=1 To n*2:x=a(b-1,c)
If c>1 Then a(b,c)=a(b-1,c-1)+x
If c<n*2 Then a(b,c)=a(b-1,c+1)+x
d=IIf(a(b,c)<>0,d & z & a(b,c) & z,d):Next:d=d & y:Next:MsgBox d
End Sub

```
> 3 votes

# Answer
postscript - 59 chars (63 if you count `-dn=` to get the number of rows in)

```
[1]n{dup ==[0 3 2 roll{dup 3 2 roll add exch}forall]}repeat

```

run with

```
gs -q -dn=10 -dBATCH pascal.ps

```

to get

```
[1]
[1 1]
[1 2 1]
[1 3 3 1]
[1 4 6 4 1]
[1 5 10 10 5 1]
[1 6 15 20 15 6 1]
[1 7 21 35 35 21 7 1]
[1 8 28 56 70 56 28 8 1]
[1 9 36 84 126 126 84 36 9 1]

```
> 3 votes

# Answer
# Mathematica 35 chars

Here is the dull and lazy way of slicing Pascal's triangle:

```
Table[n~Binomial~k,{n,0,5},{k,0,n}]

(* out *)
{{1}, {1, 1}, {1, 2, 1}, {1, 3, 3, 1}, {1, 4, 6, 4, 1}, {1, 5, 10, 10,5, 1}}

```
> 3 votes

# Answer
# Maple, 46

```
seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1)

```

Usage:

```
> f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
> f(3)
    1
   1 1
  1 2 1

```
> 3 votes

# Answer
# VBA, ~~162~~ ~~142~~ ~~102~~ 80 bytes

Saved 22 bytes thanks to Taylor Scott.

This is an old question now but I saw a shorter solution for VBA.

```
[B2].Resize([A1],[A1])="=IF(COLUMN()>ROW(),"""",IF(ROW()=2,1,IFERROR(A1+B1,1)))"

```

This is meant to be run in the immediate window. Input is in cell `A1` of the active worksheet. Output is in the active worksheet starting at `B2` and using however many cells are required based on the input. The `COLUMN()>ROW()` check keeps the top right of the triangle blank. The `ROW()=2` check makes the first value `1` to initiate the triangle. I could have shifted the output down and dropped this check, but it introduces a lot of extraneous output before the actual triangle and I didn't feel that it was in the spirit of the challenge.

I originally posted a much more complicated method that calculated every value based on its row and column. All this method does, though, is to use in-cell formulas. I start at `B2` so I can reference the row above it without `#REF!` errors. Then, it copies and pastes the same formula over a block of cells *n* wide and *n* tall. The input and output for `n=25` looks like this:
> 3 votes

# Answer
# PHP, 66+1 bytes

```
for($a[]=1;$k||$argn>=$k=++$i;)echo$a[--$k]+=$a[$k-1],$k?" ":"
";

```

**65+1 bytes in PHP 5.5 or later:**

```
for($a=[1];$k||$argn>=$k=++$i;)echo$a[--$k]+=$a[$k-1],"
"[!$k];

```

Note that the first line has a trailing space!

Run as pipe with `-nR` or try them online.
> 3 votes

# Answer
# K (ngn/k), ~~16~~ 15 bytes

```
{x#x{+':x,0}\1}

```

Try it online!
> 3 votes

# Answer
# Pip `-s`, ~~14~~ 11 bytes

```
LaPl+:lPE!l

```

Try it online!

### Explanation

Each row of the triangle, represented as a list, can be obtained by adding two copies of the previous row with an offset:

```
 [1 2 1]
+  [1 2 1]
----------
 [1 3 3 1]

```

Pip's default behavior when adding two lists is almost perfect: it matches up the elements and adds them pairwise, and if one list is longer, the extra numbers in that list are retained unchanged. So all we have to do is offset one list by prepending a 0:

```
 [1 2 1]
+[0 1 2 1]
----------
 [1 3 3 1]

```

Here's the version I started with before golfing:

```
Y[1]La{Pyy+:yPE0}
                   a is command-line argument (implicit)
Y[1]               Yank list representing the first row into y
    La{         }  Loop a times:
       Py           Print the current row (space-separated, thanks to -s flag)
            yPE0    Construct a list which is y with 0 prepended
         y+:        Add that to y and assign the result back to y

```

My original golfed version applied a few tricks:

* Using this tip, `[1]``^1`.
* We can save the curly braces if the loop body is one statement, which we can accomplish by printing `y` in the expression that updates `y`: `y+:(Py)PE0`.
* We can then save the parentheses by changing `yPE0` (`y` with `0` prepended) to `0ALy` (`0` with the list `y` appended; `0` gets promoted to a singleton list `[0]` first). This leaves us with `y+:0AL(Py)`, but since `P` is unary we can drop the parentheses (though we still need a space between the operators): `y+:0AL Py`.

The resulting solution is 14 bytes:

```
Y^1Lay+:0AL Py

```

*But we can do better!*

* It would be nice to save the space before `P`; also, the initialization `Y^1` is rather expensive.
* If we could start from an empty list (as the "0th" row) and print each row *after* it is updated, we could solve both problems: we could use `l` (which is preinitialized to the empty list) instead of `y`, and the `P` would come immediately after the loop header and therefore not require a separator.
* The problem is that our update logic, "prepend a 0 and add," doesn't work for the first row: it gives `[] + [0] = [0]`, when we need `[1]`.
* *But*, if we can prepend a 1 on the first iteration and a 0 every other time, we'll be golden. On the first iteration, `l` is empty (falsey); on every other iteration, `l` is nonempty (truthy). So we can simply prepend `!l`.

This approach gives us our 11-byte solution:

```
LaPl+:lPE!l
La           Loop a times:
         !l   1 if l is empty, 0 otherwise
      lPE     Construct a list which is l with that value prepended
   l+:        Add that to l and assign the result back to l
  P           Print (space-separated: -s flag)

```
> 3 votes

# Answer
# 05AB1E, 14 bytes

```
FN©>F®Ne})ˆ}¯»

```

Try it online!

---

```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

```
> 2 votes

# Answer
# Jelly, 17 bytes

```
3Bj+2\
1Ç⁸’¤Ð¡K€Y

```

Try it online!

If "provided however is most convenient in your chosen language" means that I can use 0-indexed input instead of 1-indexed, then `’¤` can be removed for -2.
> 2 votes

# Answer
# , 38 bytes

```
for(i in 0:scan())print(choose(i,0:i))

```

Try it online!

The other R answer is good, but this is shorter, and that one still needs a call to `scan()`!

In R, `choose` is vectorized over `k` so this is a neat solution. `print` also prints out the element number at the start of each line, so if that's not valid, I can change this to a 41 byte solution,

```
for(i in 0:scan())cat(choose(i,0:i),'\n')

```
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
<ÝεDÝc}»

```

Try it online!
> 2 votes

# Answer
# Malbolge Unshackled (20-trit rotation variant), 3,2485e7 bytes

Size of this answer exceeds maximum postable program size (eh), so the code is located in my GitHub repository.

It's a slow monstrosity, but I love this one. The digits are being displayed in hexadecimal form.

Btw, the code is compressed using 7Zip and PPMd algorithm, because the program is plain too big to post to Github in it's state of art.

## How to run this?

This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).

The best one I could find is the fixed 20-trit rotation width variant, that performs very well.

To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.

My modified version can run around 6,3% faster.

```
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

```

## It's working (very slowly!)
> 2 votes

# Answer
# Japt `-R`, ~~16~~ 13 bytes

```
_ä+T p1}h[1â]

```

Try it

```
_äÈ+Y}0 p1}      // f = prepend 0 to array and sums each pairs, then appends 1
           h[1â] // run f input times starting with [[1]]

```

saved 3 thanks to @Shaggy
> 2 votes

# Answer
# Pip `-s`, ~~22~~ 21 bytes

```
La{PooMP:_+BoPU1oPB1}

```

Try it online!

This was simpler than trying to map an iterable, and probably shorter.

-1 byte from Dlosc, using the `PU` and `PB` functions.

## Explanation (old)

```
La{Poo:1AL(_+BMPo)AL1} a → input, o → 1(predefined)
La{                  } loop a times
   Po                  print variable o(joined by spaces due to -s)
     o:                assign o to:
          (_+BMPo)     sums of pairs of it's elements
       1AL        AL1  with 1 added on both sides

```
> 2 votes

# Answer
# Forth (gforth), ~~58~~ 53 bytes

```
: P 0 ?do 1 i for dup . i * j i - 1+ / next cr loop ;

```

Try it online!

This is a heavily shortened version of the implementation here, which was in turn, translated from C.

-5 bytes from Bubbler.

The function is called like: `<input> P`.
> 2 votes

# Answer
# Scala, 58 bytes

```
Seq.iterate(Seq(1),_){r=>1+:(r,r.tail).zipped.map(_+_):+1}

```

Try it online!

Somewhat based upon this other Scala answer.

```
Seq.iterate(                 //Make a Seq
  Seq(1),                      //starting with just [1]
  _                            //of length n (_ is shorthand for n=>...n...
){ r =>                      //Function to get next row from previous row r
  (r,r.tail).zipped.map(_+_)    //Add each cell with the one on its right
1+:                         :+1 //Put two 1's around it
}

```

# Scala 3, 54 bytes

```
Seq.iterate(Seq(1),_){r=>1+:r.zip(r.tail).map(_+_):+1}

```

Try it online!
> 2 votes

# Answer
# Google Sheets, 58

Input in arbitrary cell. Assign it named range "N". (+1 count)

Then use

```
=ArrayFormula(IFERROR(COMBIN(SEQUENCE(N,1,),SEQUENCE(1,N,

```
> 2 votes

# Answer
# Vyxal `Mj`, 4 bytes

```
ƛʀƈṄ

```

Try it Online!

-2 bytes thanks to Lyxal
> 2 votes

# Answer
# Raku, 31 bytes

```
{1,{.put;|$_,0 Z+0,|$_}...$_+1}

```

Try it online!
> 2 votes

# Answer
# PHP, ~~105~~ 92 characters

```
for($e=1;$e++<=$i;$n=$a,$a=''){
foreach($n as $k=>$v)$a[]=$v+$n[$k-1];
$a[]=1;print_r($a);}

```

Input: `$i = 9;`

Output:

```
Array
(
    [0] => 1
)
Array
(
    [0] => 1
    [1] => 1
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 1
)
Array
(
    [0] => 1
    [1] => 3
    [2] => 3
    [3] => 1
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 4
    [4] => 1
)
Array
(
    [0] => 1
    [1] => 5
    [2] => 10
    [3] => 10
    [4] => 5
    [5] => 1
)
Array
(
    [0] => 1
    [1] => 6
    [2] => 15
    [3] => 20
    [4] => 15
    [5] => 6
    [6] => 1
)
Array
(
    [0] => 1
    [1] => 7
    [2] => 21
    [3] => 35
    [4] => 35
    [5] => 21
    [6] => 7
    [7] => 1
)
Array
(
    [0] => 1
    [1] => 8
    [2] => 28
    [3] => 56
    [4] => 70
    [5] => 56
    [6] => 28
    [7] => 8
    [8] => 1
)

```
> 1 votes

# Answer
## Python 105 chars

```
A=[1]
for i in range(input()):
    B=[sum(A[j:j+2])for j in range(i)]
    B[:0]=[1]
    B[i+1:]=[1]
    print A
    A=B

```
> 1 votes

# Answer
# C, 108 (126)

Length depends on whether the #include can be omitted, as it is some other C examples. Code uses edk.h as the shortest (Microsoft) standard C header with stdio.h included.

```
#include <edk.h>
int a[25]={1},b,c,d;main(){for(scanf("%d",&d);c++<d;)for(b=c;b--;printf("%d%c",a[b],b?32:10),a[b+1]+=a[b]);}

```
> 1 votes

# Answer
# Prolog (SWI), ~~124~~ ~~118~~ 114 bytes

```
r([A,B|R],[C|S]):-C is A+B,r([B|R],S).
r(L,L).
t(L,I):-I=0;write(L),nl,r([0|L],M),J is I-1,t(M,J).
t(N):-t([1],N).

```

The predicate `t(N)` outputs `N` rows of Pascal's triangle. Try it online!

Note that if you're running this locally, Prolog will probably tell you there's more than one result; if you ask for the next result, it might either output some invalid row(s) or print ever-increasing rows of the triangle till it crashes. I don't think this invalidates the solution, since it behaves exactly as desired on TIO. At any rate, a 4-byte fix is to add a couple of "cuts": insert `,!` before the period at the end of line 1, and again after `I=0` in line 3.

### Ungolfed, with comments

```
% nextRow/2 takes the current row (with a zero prepended) and builds the next row
% Example: nextRow([0, 1, 2, 1], X) gives X = [1, 3, 3, 1]

% Base case: we've gotten down to the final 1, which stays the same in the next row
nextRow([1], [1]).
% Recursive case: an element in the next row is the sum of the two elements
% above it in the current row
nextRow([A, B | Tail], [C | NewTail]) :- C is A+B, nextRow([B | Tail], NewTail).

% triangle/2 takes the current row and the number of rows left and outputs that
% many rows

% Base case: no rows left; we're done
triangle(_, 0) :- !.
% Recursive case: output the current row, build the next row, and recurse with
% decremented number of rows left
triangle(Row, RowsLeft) :-
  write(Row), nl,
  nextRow([0 | Row], NewRow),
  NewRowsLeft is RowsLeft-1,
  triangle(NewRow, NewRowsLeft).

% triangle/1 takes the number of rows N and outputs that many rows starting from [1]

triangle(N) :- triangle([1], N).

```
> 1 votes

# Answer
# Java 10, ~~143~~ 138 bytes

```
r->{var s="";for(int i=0,j;i++<r;s+="\n")for(j=0;j++<i;s+=p(i,j)+" ");return s;}int p(int r,int k){return--r<1|k<2|k>r?1:p(r,k-1)+p(r,k);}

```

-2 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it online.

```
r->{                     // Method with integer parameter and String return-type
  var s="";              //  Result-String, starting empty
  for(int i=0,j;i++<r;   //  Loop `i` in the range [1, `r`]:
      s+="\n")           //    After every iteration: Append a new-line
    for(j=0;j++<i;       //   Inner loop `j` in the range [1, `i`]:
      s+=p(i,j)          //    Append the `j`'th Pascal Triangle number on the `i`'th row
         +" ");          //    and also append a space
  return s;}             //  Return the result-String

// Separated recursive method to get the k'th value of the r'th row in the Pascal Triangle
int p(int r,int k){return--r<1|k<2|k>r?1:p(r,k-1)+p(r,k);}

```
> 1 votes

# Answer
# Pyt, 9 bytes

If the output format was less restrictive, then this could be 8 bytes (just remove '`Á`')

```
řĐř⁻⇹⁻⇹ćÁ

```

Explanation:

```
               Implicit input (n)
ř              Push [1,2,...,n]
 Đ             Duplicate top of stack
  ř            Push [[1],[1,2],[1,2,3],...,[1,2,...,n]]
   ⁻           Decrement element-wise [[0],[0,1],[0,1,2],...,[0,1,...,n-1]]
    ⇹          Swap top two elements on stack
     ⁻         Decrement [0,1,2,...,n-1]
      ⇹        Swap top of stack
       ć       Compute nCr†
        Á      Push contents of array on top of stack to the stack

```

Try it online!

† - This yields \[\[0C0\],\[1C0,1C1\],\[2C0,2C1,2C2\],...,\[(n-1)C0,(n-1)C1,...,(n-1)C(n-1)\]\]
> 1 votes

# Answer
# Python 3, 68 Bytes

```
b=lambda n,a=[1]:n and[print(a),b(n-1,[*map(sum,zip([0]+a,a+[0]))])]

```
> 1 votes

# Answer
# Scala, 97 bytes

```
n=>{var p=Seq(1);for(i<-0 to n-1){println(p mkString " ");p=1+:0.to(i-1).map(j=>p(j)+p(j+1)):+1}}

```

A for loop computes the next line's number sequence from the previous one via simple index-based addition and by concatenating 1's via `+:` and `:+`. Unfortunately this iterative approach is slightly shorter than a "nicer" monadic approach via scanLeft :)

**Edit**: Thanks to all commentors for tips & corrections!

Try it online!
> 1 votes

# Answer
# Julia 0.7, 37 bytes

```
f(x)=@show 1(x<2||[0;F=f(x-1)]+[F;0])

```

Try it online!

It outputs a lot of garbage but it's allowed:

```
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = 1
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 1]
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 2, 1]
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 3, 3, 1]
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 4, 6, 4, 1]

```
> 1 votes

# Answer
# Jelly, 8 bytes

```
ḶcŻ$€K€Y

```

Try it online!

Mmm yes the output format here really do be fun tho - 5 bytes for the triangle generation, and 3 for the formatting.

## Explained

```
ḶcŻ$€K€Y # A monadic chain with argument n. Let the current value be λ
Ḷ        # λ = [0, n)
    €    # over each item in λ:
 cŻ$     #   yield item choose [0, item] (vectorising)
     K€  # join each sublist on spaces
       Y # and join that on newlines

```
> 1 votes

# Answer
# Excel, 48 bytes

Takes input \\$n\\$ from cell `A1` and outputs an \\$n\times n\\$ lower triangular matrix as a spilled array to the calling cell.

```
=IfError(Combin(Sequence(A1),Sequence(1,A1)),"")

```
> 1 votes

# Answer
# Fig, \\$19\log\_{256}(96)\approx\\$ 15.639 bytes

```
#jej/ #GWW1O'+Jx0J0

```

Try it online!
> 1 votes

# Answer
# Thunno 2 `N`, 8 bytes

```
LıDĖ€cðj

```

Attempt This Online!

But, if outputting a nested list was ok:

## Thunno 2, 6 bytes

```
LıDĖ€c

```

Attempt This Online!

#### Explanation

```
LıDĖ€cðj  # Implicit input
Lı        # Map over the range [0..input)
  D       #  Duplicate the current number
   Ė€     #  Map over the range [0..number]
     c    #   Compute the binomial coefficient
      ðj  #  Join the row by spaces
          # Implicit output, joined by newlines

```
> 1 votes

# Answer
# Perl, 111 characters

I know this can be improved on, just a first try:

```
$r=<>;
@p=(1);
while($r--){
    print join(' ',@p)."\n";
    @q=@p;
    unshift @q,0;
    push @p,0;
    $i=0;
    foreach(@p){$_+=$q[$i++];}
}

```
> 0 votes

# Answer
# Axiom 64 bytes

```
p(n)==for j in 0..n-1 repeat output[binomial(j,i) for i in 0..j]

```

results

```
(74) -> p 1
   Compiling function p with type PositiveInteger -> Void
   [1]
                                                               Type: Void
(75) -> p 2
   [1]
   [1,1]
                                                               Type: Void
(76) -> p 9
   [1]
   [1,1]
   [1,2,1]
   [1,3,3,1]
   [1,4,6,4,1]
   [1,5,10,10,5,1]
   [1,6,15,20,15,6,1]
   [1,7,21,35,35,21,7,1]
   [1,8,28,56,70,56,28,8,1]
                                                               Type: Void

```
> 0 votes

# Answer
# C, 178 bytes

```
#define x p[i][j]
p[25][51]={0};i;j;f(n){p[0][25]=1;for(i=1;i<n;i++)for(j=1;j<50;j++)x=p[i-1][j-1]+p[i-1][j+1];for(i=0;i<n;i++,putchar(10))for(j=0;j<51;j++)if(x)printf("%d ",x);}

```

**Uniformly Padded, 244 bytes**

```
#define x p[i][j]
s[25]={1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,5,5,5,5,6,6,6,7,7};p[25][51]={0};i;j;f(n){p[0][25]=1;for(i=1;i<n;i++)for(j=1;j<50;j++)x=p[i-1][j-1]+p[i-1][j+1];for(i=0;i<n;i++,putchar(10))for(j=0;j<51;j++)if(x)printf("%*d ",s[n-1],x);}

```

Live Demo

**Detailed**

```
#include <stdio.h>

int main(void)
{
    int n = 15;
    int s[25]={1,1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4, 5,5,5,5, 6,6,6, 7,7};
    int p[25][25+1+25] = { 0 };
    p[0][25] = 1;

    for(int i = 1; i < n; i++)
    {
        for(int j = 1; j < (25+1+24); j++)
        {
            p[i][j] = p[i-1][j-1] + p[i-1][j+1];
        }
    }

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < (25+1+25); j++)
        {
            if(p[i][j])
            {
                printf("%*d ",s[n-1],p[i][j]);
            }
        }
        printf("\n");
    }

    return 0;
}

```
> 0 votes

# Answer
# Husk, 17 bytes

```
¶↑:;1´o¡ȯmΣ∂Ṫ*´e1

```

Try it online!

### Explanation

Idea is to use polynomial multiplication beginning with `[1,1]` and iterate multiplication, take N elements from the resulting infinite list:

```
¶↑:;1´(¡(mΣ∂Ṫ*))´e1  -- implicit input N
                ´e1  -- duplicate 1 & listify: [1,1]
     ´(        )     -- duplicate [1,1] and apply to:
       ¡(mΣ∂Ṫ*)      --   iterate the function (see below*)
                     -- [[1,1],[1,2,1],[1,3,3,1],…
   ;1                -- listify 1: [1]
  :                  -- prepend: [[1],[1,1],[1,2,1],[1,3,3,1],…
 ↑                   -- take N elements
¶                    -- join with newlines

```

* That function handles the multiplication, as described here.
> 0 votes

# Answer
# Pyth, 6 bytes

```
m.cLdh

```

Try it online!

---

```
Code    |Explanation
--------+------------------------------
m.cLdh  |Full code
m.cLdhdQ|With implicit variables filled
--------+------------------------------
m      Q|For each d in [0, input):
   L hd | For each k in [0, d]:
 .c d   |  dCk
   L    | Collect results in a list
m       |Collect results in a list
        |Print result (implicit)

```
> 0 votes

# Answer
# jq -r, 50 bytes

```
limit(.;[1]|recurse([.[-1,keys[]:][:2]|add]))|@tsv

```

Try it online!
> 0 votes

# Answer
# C, 311 bytes

```
r(int*s,int*o,int n){int h=1;while(h<=n){if(h==2){printf("%d %d\n",1,1);o[0]=1;o[1]=1;}else if(h==1){printf("%d\n",1);o[0]=1;}else{int j=0;int*s_p=s,*o_p=o;*o_p++=1;printf("1 ");while(j<(h-2)){*o_p+=*s_p++;*o_p+++=*s_p;printf("%d ",*(o_p-1));j++;}*o_p=1;printf("1\n");}memcpy(s,o,100);memset(o,0,100);h++;}}

```

The complete, readable version of the program is below:

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void row(int *s,int *o,int n)
{   int h = 1;

    while (h <= n)
    {

    if(h==2){printf("%d %d\n",1,1);o[0]=1;o[1]=1;}

    else if(h==1){printf("%d\n",1);o[0]=1;}

    else
    {
        int j = 0; int *s_p=s,*o_p=o;*o_p++ =1;printf("1 ");

        while(j<(h-2))
        {
            *o_p += *s_p++;

            *o_p++ += *s_p;

            printf("%d ",*(o_p-1));

            j++;
        }

        *o_p=1;printf("1 ");puts("");
    }
        memset(s,0,100);memcpy(s,o,100);memset(o,0,100);h++;

    }

}

int main(int argc,char ** argv)
{
    const int n = strtol(argv[1],0,10);

    row(n);
}

```
> -1 votes

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