45
\$\begingroup\$

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
\$\endgroup\$
6
  • \$\begingroup\$ NB In a sense this is a simplified version of Distributing the balls \$\endgroup\$ Commented Oct 21, 2011 at 11:03
  • \$\begingroup\$ @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. \$\endgroup\$ Commented Oct 21, 2011 at 20:57
  • \$\begingroup\$ @StevenRumbalski He's fine. There's a newline between each row, and there is a space between each number, so it meets the criteria. \$\endgroup\$ Commented Oct 21, 2011 at 21:32
  • \$\begingroup\$ @Peter Olson: Thanks for the clarification. What about Tomas T's assumption that n is defined already? \$\endgroup\$ Commented Oct 21, 2011 at 21:50
  • 4
    \$\begingroup\$ @Gaffi Probably not, accepting an answer makes me feel like I'm ending the contest and discouraging new and possibly better answers. \$\endgroup\$ Commented Jun 8, 2012 at 4:05

69 Answers 69

1 2
3
1
\$\begingroup\$

jq -r, 50 bytes

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

Nibbles, 16 nibbles (8 bytes)

<$`.,1!;:0$\@+

Attempt This Online!

Explanation

<$`.,1!;:0$\@+
    ,1          # Range(1), one-based (i.e. [1])
  `.            # Starting from that value, iterate this function:
      !      +  #  Zip using addition
        :0$     #  the argument with 0 prepended
       ;   \@   #  and that list reversed
<$              # Take the first (input) number of elements

Conveniently, Nibbles' default format for outputting nested lists of integers is exactly what the challenge requires.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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;
}
\$\endgroup\$
0
\$\begingroup\$

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++];}
}
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
-1
\$\begingroup\$

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);
}
\$\endgroup\$
6
  • 1
    \$\begingroup\$ You can use a shorter function name to save some bytes. \$\endgroup\$
    – mbomb007
    Commented Aug 4, 2019 at 20:16
  • \$\begingroup\$ I renamed the function to r. Thanks. \$\endgroup\$
    – T. Salim
    Commented Aug 4, 2019 at 20:19
  • 1
    \$\begingroup\$ Extra 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 \$\endgroup\$
    – Jo King
    Commented Aug 4, 2019 at 22:36
  • \$\begingroup\$ 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. \$\endgroup\$
    – T. Salim
    Commented Aug 4, 2019 at 22:42
  • \$\begingroup\$ 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 \$\endgroup\$
    – Jo King
    Commented Aug 4, 2019 at 23:14
1 2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.