# 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
-
 NB In a sense this is a simplified version of Distributing the balls – Peter Taylor Oct 21 '11 at 11:03 @Peter Olson: What's your opinion of ratchet freak's interpretation of "you may format it however you like"? If I followed his interpretation I could shave 18 characters. – Steven Rumbalski Oct 21 '11 at 20:57 @StevenRumbalski He's fine. There's a newline between each row, and there is a space between each number, so it meets the criteria. – Peter Olson Oct 21 '11 at 21:32 @Peter Olson: Thanks for the clarification. What about Tomas T's assumption that n is defined already? – Steven Rumbalski Oct 21 '11 at 21:50 @PeterOlson Will there ever be an accepted answer to this question? – Gaffi Jun 8 '12 at 3:59
show 1 more comment

## J, 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|+-+--+||||||  |||
|| ||| ||| ||  || ||!|{:|||||||  |||
|| ||| ||| ||  || |+-+--+||||||  |||
|| ||| ||| ||  |+-+------+|||||  |||
|| ||| ||| |+--+----------+||||  |||
|| ||| ||+-+---------------+|||  |||
|| ||| |+-------------------+||  |||
|| ||+-+---------------------+|  |||
|| |+-------------------------+--+||
|+-+------------------------------+|
+----------------------------------+
-
J beats GolfScript? Interesting. I would like to see an explanation for this code, if you have time. – Mr.Wizard Oct 26 '11 at 9:31
It's already split down, but here's a line by line if you'd like additional english. Line 1 i.5 returns the first five naturals. Line 2 adds {: "Tail" (return last). Line 3 combines them with ! "Out Of" (number of combinations). Line 4 (!{:)i.5 is the same. factoring the hook out. So (!:) is an operation that transforms the first n naturals to the nth line of Pascal's triangle. Line 5 applies it to all Prefixes (backslash) of 0..4, but J fills in the unused spots with 0, so the operation is combined (@) with the string formatting operation ":. Very cool J, upvoted. – J B Nov 2 '11 at 14:51
@JB Isn't ! means factorial here? Also we can get rid of @ at the right. – Artem Ice Aug 15 '12 at 14:35
@ArtemIce Monadic ! means factorial; dyadic ! counts combinations. The final @ in ":@(!{:)\@i. is just there to make this a stand-alone verb. – ephemient Aug 15 '12 at 14:38

## Python, 94918870 63 characters

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

## 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
-

### 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
;
-
 You might want to try golf.shinh.org/p.rb?pascal+triangle – Nabb Oct 22 '11 at 3:31 Could you please provide some pseudo-code or explanation? I kind of understand what's going on, but I'm not entirely understanding the swapping part. – Mike Dtrick Aug 10 '12 at 2:50 Thank you for the detailed explanation and excellent answer (+1), but I'm even more confused now. The logic (process) isn't sitting right. – Mike Dtrick Aug 10 '12 at 19:03 @MikeDtrick, there was a slight error in the explanation. There's also a subtle point which needed explaining, but which I'd missed because it's so long since I wrote the code. – Peter Taylor Aug 10 '12 at 19:23 Okay, it's starting to make sense. My final question be does the printing and executing process work from the top down or the bottom up (1, 1 1, 1 2 1: top down, 1 2 1, 1 1, 1: bottom up)? – Mike Dtrick Aug 11 '12 at 2:40
show 1 more comment

## Scala, 817872 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:

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)))
-
 + 1 for shameless copying! – Steven Rumbalski Oct 25 '11 at 21:23 The last version should be used carefully for huge values of readInt, like 50. ;) – user unknown May 31 '12 at 22:16 @userunknown presumably that's why the question specifies an upper limit of 25... – Luigi Plinge May 31 '12 at 22:25 It wasn't meant as critique, just as a warning for the curious. – user unknown May 31 '12 at 22:41

# 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]
-
 +1 Clever way to use exec avoid a for loop. – Steven Rumbalski Nov 23 '11 at 18:00

## JavaScript (908583 81)

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

-
Nice! You can save one more character by changing "s=s*..." to "s*=..." – Derek Kurth Oct 25 '11 at 19:41
@DerekKurth: I had thought that when I was first doing optimizations, but that would mess up the logic because it needs to be s*(i-j)/j, not s*((i-j)/j). – mellamokb Oct 25 '11 at 19:49
Hmm, I tried it as s*=... in the jsfiddle and it seemed to work. Maybe I did something wrong, though. – Derek Kurth Oct 25 '11 at 20:16
@DerekKurth: Technically it is the same, but the idea is that if you multiply by (i-j) before dividing by j, then there is no need for floating point arithmetic because the results should always be an integer. If you do ((i-j)/j) first, this will result in decimal values which can be a source of error, and at the very least will require extra code for rounding/truncating. You don't begin to see this until you get to about n>11, and you'll see decimal values in the output, i.e., 1 11 55 165 330 461.99999999999994 461.99999999999994... – mellamokb Oct 25 '11 at 21:47
Ah, that makes sense! – Derek Kurth Oct 25 '11 at 22:10

# 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)
-
You're missing one of the requirements: "Given an input n (provided however is most convenient in your chosen language)" – Steven Rumbalski Oct 21 '11 at 20:59
@Steven, "Given an input n"... so may I assume the n is given? I corrected the code. Is this now OK? – Tomas Oct 21 '11 at 21:38
I'm asked Peter Olson to clarify. – Steven Rumbalski Oct 21 '11 at 21:52
@StevenRumbalski I don't think that's valid unless it takes input. I don't know R, so maybe the compiler makes it so that undefined variables prompt an input, so it might be ok, but if it's like most other languages in that regard, I don't think it is. – Peter Olson Oct 22 '11 at 0:04
@PeterOlson, so you require to read it from console? That's clumsy and it spoils the solutions... then I would have to use scan() instead of n and have 5 characters more... Please confirm and I'll modify my solution. – Tomas Oct 22 '11 at 10:08

f=[1]:[zipWith(+)(0:x)x++[1]|x<-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]

Output:

[1]
[1,1]
[1,2,1]
[1,3,3,1]
-

## 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
-
 Or alternatively, 20 characters t:{(x-1){0+':x,0}\1} – slackwear Mar 8 '12 at 20:35 Nice, shorter than the GolfScript solution now. – sinedcm Mar 9 '12 at 12:10

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.

-

## Perl, 52, 49 characters

Edit: using say instead of print

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

## 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
-

## 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);}
-

# 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
-

## 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; }
-
 I can't help but feel that this misses the point of code golf. (I also can't help pointing out that the extra character is in the \binom{5}{4} position). – Peter Taylor Jun 6 '12 at 16:11 It was fun to write. That's generally what I come to codegolf for. – walpen Jun 6 '12 at 21:03 Clever :) Have an upvote. Maybe not a winner candidate but a creative one! – Accatyyc Aug 10 '12 at 13:02

# Ruby: 51 49 characters

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

Sample run:

bash-4.2\$ ruby -ne 'p=[];\$_.to_i.times{n=0;p p.map!{|i|(v=n)+n=i}<<1}' <<< 1
[1]

bash-4.2\$ ruby -ne 'p=[];\$_.to_i.times{n=0;p p.map!{|i|(v=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]
-
you can save 2 chars with p.map!{|i|(v=n)+n=i} – jsvnm Aug 10 '12 at 11:21
Great one, @jsvnm! Man, how long I combined to shorten that part. Thanks. – manatwork Aug 10 '12 at 11:44

## D 134 128 chars

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

-

## 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
-
 What's with all those 0s :-)? – mellamokb Oct 20 '11 at 22:23 @mellamokb Bit of re-arranging made them go away and shortened the code. :-) – Gareth Oct 20 '11 at 22:28

## 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")
-

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]
-

## 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++];}
}
-

## 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
)
-

# Pascal: 216 characters

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

var p:array[0..1,1..25]of Integer;i,j,n,u:Word;s:string;begin
Readln(s);Val(s,n,i);u:=0;for i:=1 to n do begin
p[1,1]:=1;for j:=1 to 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
-

## 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
-
You can spare 4 characters with list slice: replace B.insert(0,1) with B[:0]=[1]. – manatwork May 23 '12 at 17:51
Yeah! I'm not a very advanced python programmer. And I've changed both of them. – Rushil May 23 '12 at 19:31

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
-

# 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}}
-

## 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.