Generate Pascal's triangle

35

6

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

Peter Olson

Posted 2011-10-20T18:16:53.283

Reputation: 7 412

@PeterOlson Will there ever be an accepted answer to this question? – Gaffi – 2012-06-08T03:59:54.027

4@Gaffi Probably not, accepting an answer makes me feel like I'm ending the contest and discouraging new and possibly better answers. – Peter Olson – 2012-06-08T04:05:46.117

NB In a sense this is a simplified version of Distributing the balls

– Peter Taylor – 2011-10-21T11:03:31.367

@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 – 2011-10-21T20:57:51.890

@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 – 2011-10-21T21:32:00.443

@Peter Olson: Thanks for the clarification. What about Tomas T's assumption that n is defined already? – Steven Rumbalski – 2011-10-21T21:50:14.837

Answers

30

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|+-+--+||||||  |||
|| ||| ||| ||  || ||!|{:|||||||  |||
|| ||| ||| ||  || |+-+--+||||||  |||
|| ||| ||| ||  |+-+------+|||||  |||
|| ||| ||| |+--+----------+||||  |||
|| ||| ||+-+---------------+|||  |||
|| ||| |+-------------------+||  |||
|| ||+-+---------------------+|  |||
|| |+-------------------------+--+||
|+-+------------------------------+|
+----------------------------------+

ephemient

Posted 2011-10-20T18:16:53.283

Reputation: 1 601

@JB Isn't ! means factorial here? Also we can get rid of @ at the right. – defhlt – 2012-08-15T14:35:17.793

@ArtemIce Monadic ! means factorial; dyadic ! counts combinations. The final @ in ":@(!{:)\@i. is just there to make this a stand-alone verb. – ephemient – 2012-08-15T14:38:40.493

1J beats GolfScript? Interesting. I would like to see an explanation for this code, if you have time. – Mr.Wizard – 2011-10-26T09:31:59.797

4It'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 – 2011-11-02T14:51:54.147

18

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]

primo

Posted 2011-10-20T18:16:53.283

Reputation: 181

1+1 Clever way to use exec avoid a for loop. – Steven Rumbalski – 2011-11-23T18:00:58.873

15

Python, 94 91 88 70 63 characters

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

Steven Rumbalski

Posted 2011-10-20T18:16:53.283

Reputation: 1 353

14

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

Mr.Wizard

Posted 2011-10-20T18:16:53.283

Reputation: 2 481

14

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

walpen

Posted 2011-10-20T18:16:53.283

Reputation: 3 237

4I 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 – 2012-06-06T16:11:13.853

2It was fun to write. That's generally what I come to codegolf for. – walpen – 2012-06-06T21:03:28.453

1Clever :) Have an upvote. Maybe not a winner candidate but a creative one! – Accatyyc – 2012-08-10T13:02:33.373

11

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
;

Peter Taylor

Posted 2011-10-20T18:16:53.283

Reputation: 41 901

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. – Rob – 2012-08-10T02:50:10.517

Thank you for the detailed explanation and excellent answer (+1), but I'm even more confused now. The logic (process) isn't sitting right. – Rob – 2012-08-10T19:03:29.840

@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 – 2012-08-10T19:23:12.630

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)? – Rob – 2012-08-11T02:40:06.193

@MikeDtrick, top-down. The uncommented .p at the end of the loop prints the line that was just generated. – Peter Taylor – 2012-08-11T07:52:53.357

You might want to try http://golf.shinh.org/p.rb?pascal+triangle

– Nabb – 2011-10-22T03:31:42.137

7

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]

hammar

Posted 2011-10-20T18:16:53.283

Reputation: 4 011

You can save a character by using mapM instead of mapM_. – dfeuer – 2019-02-25T04:23:17.637

7

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

Luigi Plinge

Posted 2011-10-20T18:16:53.283

Reputation: 631

The last version should be used carefully for huge values of readInt, like 50. ;) – user unknown – 2012-05-31T22:16:07.447

@userunknown presumably that's why the question specifies an upper limit of 25... – Luigi Plinge – 2012-05-31T22:25:03.197

It wasn't meant as critique, just as a warning for the curious. – user unknown – 2012-05-31T22:41:34.733

>

  • 1 for shameless copying!
  • < – Steven Rumbalski – 2011-10-25T21:23:30.050

    6

    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!

    manatwork

    Posted 2011-10-20T18:16:53.283

    Reputation: 17 865

    1you can save 2 chars with p.map!{|i|(v=n)+n=i} – jsvnm – 2012-08-10T11:21:34.983

    Great one, @jsvnm! Man, how long I combined to shorten that part. Thanks. – manatwork – 2012-08-10T11:44:23.977

    1Maybe a little late, but: why use the variable v? – G B – 2017-12-15T08:08:24.347

    Good catch, @GB! That left behind from 1st revision, where… where… doh. Where was also kind of useless. I guess it comes from an earlier attempt when used .map. Thank you.

    – manatwork – 2017-12-15T09:07:55.833

    5

    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

    mellamokb

    Posted 2011-10-20T18:16:53.283

    Reputation: 5 544

    Nice! You can save one more character by changing "s=s..." to "s=..." – Derek Kurth – 2011-10-25T19:41:43.340

    @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 – 2011-10-25T19:49:23.983

    Hmm, I tried it as s*=... in the jsfiddle and it seemed to work. Maybe I did something wrong, though. – Derek Kurth – 2011-10-25T20:16:00.710

    1@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 – 2011-10-25T21:47:25.740

    Ah, that makes sense! – Derek Kurth – 2011-10-25T22:10:13.860

    5

    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)
    

    Tomas

    Posted 2011-10-20T18:16:53.283

    Reputation: 2 333

    3You're missing one of the requirements: "Given an input n (provided however is most convenient in your chosen language)" – Steven Rumbalski – 2011-10-21T20:59:06.647

    @Steven, "Given an input n"... so may I assume the n is given? I corrected the code. Is this now OK? – Tomas – 2011-10-21T21:38:46.567

    I'm asked Peter Olson to clarify. – Steven Rumbalski – 2011-10-21T21:52:42.400

    @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 – 2011-10-22T00:04:48.740

    @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 – 2011-10-22T10:08:21.673

    @TomasT. I don't care how you get the input, as long is n is provided by input somehow. – Peter Olson – 2011-10-22T22:56:05.660

    @PeterOlson, what does it mean "provided by input"? – Tomas – 2011-10-22T23:22:19.247

    1Basically, the n must be supplied from an external source at run time and the apparatus for capturing it is included in your program. Typically, that means by command line argument, or stdin, or file. By file is almost never used because it's invariably longer than the other two options. – Steven Rumbalski – 2011-10-24T13:01:35.663

    5

    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
    

    sinedcm

    Posted 2011-10-20T18:16:53.283

    Reputation: 410

    Or alternatively, 20 characters t:{(x-1){0+':x,0}\1} – skeevey – 2012-03-08T20:35:15.427

    Nice, shorter than the GolfScript solution now. – sinedcm – 2012-03-09T12:10:28.367

    4

    Keg, 40 bytes

    1®n1¿1.
    ,(|(©n|:©n$@MCƒℤ. ,⑨)©n⑨®n_01.
    ,
    

    Explained

    Pen Highlighted

    Lyxal

    Posted 2011-10-20T18:16:53.283

    Reputation: 5 253

    4

    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.

    flesk

    Posted 2011-10-20T18:16:53.283

    Reputation: 161

    4

    Perl, 52, 49 characters

    Edit: using say instead of print

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

    Toto

    Posted 2011-10-20T18:16:53.283

    Reputation: 909

    4

    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
    

    Dan Andreatta

    Posted 2011-10-20T18:16:53.283

    Reputation: 211

    3

    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
    

    PhiNotPi

    Posted 2011-10-20T18:16:53.283

    Reputation: 26 739

    3

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

    saeedn

    Posted 2011-10-20T18:16:53.283

    Reputation: 1 241

    3

    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 
    

    manatwork

    Posted 2011-10-20T18:16:53.283

    Reputation: 17 865

    3

    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
    

    Luis Mendo

    Posted 2011-10-20T18:16:53.283

    Reputation: 87 464

    non-competing but a holy disaster, none from previous submissions (even J) succeeded to reduce it up to how much Matl did !!! – Abr001am – 2016-05-21T09:09:09.653

    I'm pretty sure Jelly or 05AB1E would be shorter though :-) – Luis Mendo – 2016-05-21T10:34:34.990

    2

    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
    

    Magic Octopus Urn

    Posted 2011-10-20T18:16:53.283

    Reputation: 19 422

    2

    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:

    Output

    Engineer Toast

    Posted 2011-10-20T18:16:53.283

    Reputation: 5 769

    Very cool answer, but you can golf this quite a bit. Converting Function p(r) to Sub p(r) since you have no function output value, removing the space from debug.? c(n,k); and converting the multiline if-then-else statement to a single line (If k Then c=c(n-1,k-1)*n/k Else c=1) brings the byte-count down to 130 by my count – Taylor Scott – 2017-03-28T21:43:29.333

    @TaylorScott Thanks! I'm pretty new at golfing and only slightly less new to programming in general. I counted 142 because of the line breaks. From what I could find, those are supposed to count.

    – Engineer Toast – 2017-03-29T12:08:16.517

    Ah, you are right, I did forget to count my newlines, and as it turns out, at least one other golfing trick For n=0 To... can be condensed to For n=0To... bringing my version of the code to Sub p(r):For n=0To r-1:For k=0To n:Debug.?c(n,k);:Next:Debug.?:Next:End Sub Function c(n,k):If k Then c=1 Else c=c(n-1,k-1)*n/k [char(10)] End Function with a byte count of 139 – Taylor Scott – 2017-03-30T02:44:22.857

    A second look at this suggests that if you break it down into an immediate window function with a helper function, you can get it down to 112 Bytes (Immediate Window Function: For n=0To[A1-1]:For k=0To n:?c(n,k);:Next:?:Next Helper Function: Function c(n,k) If k Then c=c(n-1,k-1)*n/k Else c=1 End Function) – Taylor Scott – 2017-09-18T01:57:12.577

    @TaylorScott I found an even shorter way using the immediate window. I had not previously considered the basic formula approach but it turned out to be way shorter. – Engineer Toast – 2017-09-18T13:29:21.960

    since you moved over to a cell based response you can optimize this by removing the copy and instead always deleting [A:A] and [1:1] instead yielding [B2].Resize([A1],[A1])="=IF(COLUMN()>ROW(),"""",IFERROR(A1+B1,1))":[1:1].Delete:[A:A].Delete for 92 Bytes - I tried golfing down the delete statements and I am convinced that there is a way to do it, but for now I cannot seem to condense them – Taylor Scott – 2017-09-19T16:04:11.990

    1@TaylorScott What about just dropping them entirely? With a change in the formula, it works just fine. I think that output starting at B2 instead of A1 is acceptable. – Engineer Toast – 2017-09-20T12:23:20.827

    2

    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.

    Volatility

    Posted 2011-10-20T18:16:53.283

    Reputation: 3 206

    2

    05AB1E, 8 bytes

    <ÝεDÝc}»
    

    Try it online!

    Emigna

    Posted 2011-10-20T18:16:53.283

    Reputation: 50 798

    I... you... I.... what?! – Magic Octopus Urn – 2018-02-14T18:37:32.540

    1¸=©sF®NF®«ü+®ì}®«=... I'm ashamed tbh lol. nCr, never seen it used until this answer. – Magic Octopus Urn – 2018-02-14T18:43:18.190

    @MagicOctopusUrn: I have used it before, but I can't remember in what/which answer(s). Sometimes I wish I had a searchable version of all answers that I could check when I feel like I've done something similar (and maybe better) in the past. – Emigna – 2018-02-14T18:49:38.553

    Maybe a search for all answers by user:## then extract all indented code blocks that follow a line starting with #[05AB1E] using the SE API :P? – Magic Octopus Urn – 2018-02-14T18:54:57.230

    I wanted to do that to find all questions with more than 1 05AB1E answer on it. – Magic Octopus Urn – 2018-02-14T18:55:36.080

    17 bytes by using a ranged loop without }. – Kevin Cruijssen – 2019-09-25T11:17:40.403

    2

    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>

    Shaggy

    Posted 2011-10-20T18:16:53.283

    Reputation: 24 623

    2

    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

    ratchet freak

    Posted 2011-10-20T18:16:53.283

    Reputation: 1 334

    2

    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
    

    Gareth

    Posted 2011-10-20T18:16:53.283

    Reputation: 11 678

    What's with all those 0s :-)? – mellamokb – 2011-10-20T22:23:39.763

    @mellamokb Bit of re-arranging made them go away and shortened the code. :-) – Gareth – 2011-10-20T22:28:20.957

    2

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

    lochok

    Posted 2011-10-20T18:16:53.283

    Reputation: 3 139

    2

    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
    

    Gaffi

    Posted 2011-10-20T18:16:53.283

    Reputation: 3 411

    2

    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]
    

    Geoff Reedy

    Posted 2011-10-20T18:16:53.283

    Reputation: 2 828

    2

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

    DavidC

    Posted 2011-10-20T18:16:53.283

    Reputation: 24 524

    2

    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
    

    DSkoog

    Posted 2011-10-20T18:16:53.283

    Reputation: 560

    1

    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.

    Erik the Outgolfer

    Posted 2011-10-20T18:16:53.283

    Reputation: 38 134

    1

    R, 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')
    

    Giuseppe

    Posted 2011-10-20T18:16:53.283

    Reputation: 21 077

    I think you output one line too many every time (though neat solution indeed). – plannapus – 2017-12-15T08:59:41.767

    1

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

    DLosc

    Posted 2011-10-20T18:16:53.283

    Reputation: 21 213

    1

    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.

    Titus

    Posted 2011-10-20T18:16:53.283

    Reputation: 13 814

    1

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

    Kevin Cruijssen

    Posted 2011-10-20T18:16:53.283

    Reputation: 67 575

    1

    Perl, 37 bytes

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

    Try it online!

    Ton Hospel

    Posted 2011-10-20T18:16:53.283

    Reputation: 14 114

    1

    K (ngn/k), 16 15 bytes

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

    Try it online!

    scrawl

    Posted 2011-10-20T18:16:53.283

    Reputation: 1 079

    1

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

    enter image description here

    Krzysztof Szewczyk

    Posted 2011-10-20T18:16:53.283

    Reputation: 3 819

    1

    Python 3, 68 Bytes

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

    Legorhin

    Posted 2011-10-20T18:16:53.283

    Reputation: 131

    1

    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

    AZTECCO

    Posted 2011-10-20T18:16:53.283

    Reputation: 2 441

    1ä+T will work here, too. – Shaggy – 2019-11-26T22:07:41.627

    1

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

    Alchymist

    Posted 2011-10-20T18:16:53.283

    Reputation: 544

    1

    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
    )
    

    Korvin Szanto

    Posted 2011-10-20T18:16:53.283

    Reputation: 121

    nice one, though predefined variables are no valid input method. – Titus – 2017-12-15T13:07:10.980

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

    Derek Kurth

    Posted 2011-10-20T18:16:53.283

    Reputation: 111

    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
    

    Rushil Paul

    Posted 2011-10-20T18:16:53.283

    Reputation: 251

    2You can spare 4 characters with list slice: replace B.insert(0,1) with B[:0]=[1]. – manatwork – 2012-05-23T17:51:56.060

    Yeah! I'm not a very advanced python programmer. And I've changed both of them. – Rushil Paul – 2012-05-23T19:31:43.953

    0

    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
    

    RosLuP

    Posted 2011-10-20T18:16:53.283

    Reputation: 3 036

    0

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

    Khaled.K

    Posted 2011-10-20T18:16:53.283

    Reputation: 1 435

    0

    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.

    ბიმო

    Posted 2011-10-20T18:16:53.283

    Reputation: 15 345

    0

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

    mudkip201

    Posted 2011-10-20T18:16:53.283

    Reputation: 833

    0

    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)
    

    hakr14

    Posted 2011-10-20T18:16:53.283

    Reputation: 1 295

    -1

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

    T. Salim

    Posted 2011-10-20T18:16:53.283

    Reputation: 575

    1You can use a shorter function name to save some bytes. – mbomb007 – 2019-08-04T20:16:19.580

    I renamed the function to r. Thanks. – T. Salim – 2019-08-04T20:19:50.273

    1Extra whitespace, long variable names, unecessary parentheses, lists can be declared outside the function to remove the static int, first memset is not needed, 100s can be 99, the puts can be combined with the printf, second o[0]=1; can be removed – Jo King – 2019-08-04T22:36:52.617

    Got rid of the first memset and unnecessary puts. I don't know what you mean by replacing 100 with 99 because if n == 25 and since sizeof(int)==4, then I think it should remain a 100. – T. Salim – 2019-08-04T22:42:13.560

    You don't need to reset the last element since you don't need to support the 26th iteration. Why did you put the lists back in the input? The question only specifies n as input, and you aren't using them as output? You still have the long variable names and the extra o[0]=1 – Jo King – 2019-08-04T23:14:37.667

    Your complete version of the code does not work – Jo King – 2019-11-26T12:20:26.167