Générer le triangle de Pascal

35

Le triangle de Pascal est généré en commençant par un 1 sur la première ligne. Sur les lignes suivantes, le nombre est déterminé par la somme des deux nombres situés directement au-dessus, à gauche et à droite.

Pour démontrer, voici les 5 premières lignes du triangle de Pascal:

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

Le défi

Étant donné une entrée n (à condition toutefois que cela soit plus pratique dans la langue de votre choix), générez les n premières lignes du triangle de Pascal. Vous pouvez supposer que n est un entier compris entre 1 et 25. Il doit y avoir un saut de ligne entre chaque ligne et un espace entre chaque nombre, mais en dehors de cela, vous pouvez le formater à votre guise.

C'est du code-golf , donc la solution la plus courte gagne.

Exemple 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
la source
NB: En un sens, il s'agit d'une version simplifiée de Distributing the balls
Peter Taylor
@ Peter Olson: Quelle est votre opinion sur l'interprétation de Ratchet Freak selon laquelle "vous pouvez le formater comme bon vous semble"? Si je suivais son interprétation, je pourrais raser 18 personnages.
Steven Rumbalski
@StevenRumbalski Il va bien. Il y a une nouvelle ligne entre chaque ligne et un espace entre chaque numéro, ce qui correspond aux critères.
Peter Olson
@ Peter Olson: Merci pour la clarification. Qu'en est-il de l'hypothèse de Tomas T selon laquelle n est déjà défini?
Steven Rumbalski
4
@ Gaffi Probablement pas, accepter une réponse me donne l'impression de mettre fin au concours et de décourager de nouvelles réponses, voire de meilleures réponses.
Peter Olson

Réponses:

30

J , 12 caractères

":@(!{:)\@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 | + - + - + |||||| |||
|| ||| ||| || || ||! | {: ||||||| |||
|| ||| ||| || || | + - + - + |||||| |||
|| ||| ||| || | + - + ------ + ||||| |||
|| ||| ||| | + - + ---------- + |||| |||
|| ||| || + - + --------------- + ||| |||
|| ||| | + ------------------- + || |||
|| || + - + --------------------- + | |||
|| | + ------------------------- + - + ||
| + - + ------------------------------ + |
+ ---------------------------------- +
éphémère
la source
1
J bat GolfScript? Intéressant. Je voudrais voir une explication pour ce code, si vous avez le temps.
Mr.Wizard
4
Il est déjà divisé, mais voici une ligne par ligne si vous souhaitez davantage d’anglais. La ligne 1 i.5renvoie les cinq premiers produits naturels. La ligne 2 ajoute {:"Tail" (retour le dernier). La ligne 3 les combine avec !"Out Of" (nombre de combinaisons). La ligne 4 (!{:)i.5est la même. en tenant compte du crochet. Il en (!:)va de même pour une opération qui transforme les n premiers naturels en la nième ligne du triangle de Pascal. La ligne 5 l’applique à tous les préfixes (barres obliques inverses) de 0..4, mais J remplit les points inutilisés avec 0; l’opération est donc combinée ( @) avec l’opération de formatage de chaîne ":. Très cool J, upvoted.
JB
@JB n'est pas! signifie factoriel ici? Nous pouvons aussi nous débarrasser de @ à droite.
defhlt
@ArtemIce Monadic !signifie factorial; !nombre de combinaisons dyadiques . La finale @in ":@(!{:)\@i.est juste là pour en faire un verbe autonome.
éphémère
18

Python, 56 octets

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

Exemple d'utilisation:

echo 9 | python filename.py

Produit:

[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
la source
1
+1 Manière astucieuse d' execéviter une forboucle.
Steven Rumbalski
15

Python, 94 91 88 70 63 caractères

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

Mathematica: 36 (41?)


Mathematica a la Binomialfonction, mais cela enlève du plaisir à cela. Je propose:

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

La ligne ci-dessus rendra un tableau fragmenté tel que:

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

Comme il s’agit d’un format de base dans Mathematica, j’ai pensé que ce serait acceptable, mais j’ai lu les règles à nouveau, je pense que ce n’est peut-être pas le cas. L’ajout Grid@produira une sortie parfaitement acceptable, pour un total de 41 caractères:

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
la source
14

C, 522

Une réponse auto-démonstrative en C Ne pourrait pas être plus clair! Points bonus pour trouver le personnage supplémentaire.

#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
la source
4
Je ne peux pas m'empêcher de penser que cela manque le but du code golf. (Je ne peux également m'empêcher de souligner que le caractère supplémentaire est dans la position \ binom {5} {4}).
Peter Taylor
2
C'était amusant d'écrire. C'est généralement ce pour quoi je viens à codegolf.
walpen
1
Clever :) Avoir un vote positif. Peut-être pas un candidat gagnant mais un créateur!
Accatyyc
11

Golfscript (21 caractères)

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

Depuis qu'une explication a été demandée:

# 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
la source
Vous voudrez peut-être essayer golf.shinh.org/p.rb?pascal+triangle
Nabb
Pourriez-vous s'il vous plaît fournir un pseudo-code ou une explication? Je comprends un peu ce qui se passe, mais je ne comprends pas tout à fait l’échange.
Rob
Merci pour l'explication détaillée et l'excellente réponse (+1), mais je suis encore plus confus maintenant. La logique (processus) ne repose pas bien.
Rob
@ MikeDtrick, il y avait une légère erreur dans l'explication. Il y a aussi un point subtil qui doit être expliqué, mais que j'avais raté car il y a si longtemps que je n'ai pas écrit le code.
Peter Taylor
Ok, ça commence à avoir un sens. Ma dernière question est la suivante: le processus d’impression et d’exécution fonctionne-t-il de haut en bas ou de bas en haut (1, 1 1, 1 2 1: de haut en bas, 1 2 1, 1 1, 1: de bas en haut)?
Rob
7

Haskell, 94 92

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

Sortie:

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

Une version à 71 caractères qui n'imprime pas d'espace entre chaque numéro:

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

Sortie:

[1]
[1,1]
[1,2,1]
[1,3,3,1]
hammar
la source
Vous pouvez enregistrer un personnage en utilisant à la mapMplace de mapM_.
dfeuer
7

Scala, 81 78 72 70 caractères

81 caractères: première tentative, copiée sans vergogne depuis la version Python :)

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

Exécutez-le en tant que script ou directement dans le REPL.

Couper à 70 caractères avec quelque chose de étonnamment lisible et idiomatique:

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

Ou 72 70 caractères avec une méthode totalement différente:

0 to(readInt-1)map(i=>println(0 to i map(1 to i combinations(_)size)))
Luigi Plinge
la source
+ 1 pour la copie sans vergogne!
Steven Rumbalski
La dernière version doit être utilisée avec précaution pour les valeurs énormes de readInt, comme 50.;)
utilisateur inconnu
@userunknown c'est sans doute pour cette raison que la question précise une limite supérieure de 25 ...
Luigi Plinge
Ce n'était pas une critique, mais un avertissement pour les curieux.
utilisateur inconnu
6

Ruby: 51 49 46 caractères

(Code de 45 caractères + option de ligne de commande de 1 caractère)

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

Grâce à:

  • jsvnm for suggesting an alternative for the value switching (2 characters)
  • Go pour repérer une variable non utilisée après une amélioration précédente (4 caractères)

Échantillon échantillon:

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]

Essayez-le en ligne!

manatwork
la source
1
you can save 2 chars with p.map!{|i|(v=n)+n=i}
jsvnm
Great one, @jsvnm! Man, how long I combined to shorten that part. Thanks.
manatwork
1
Maybe a little late, but: why use the variable v?
G B
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
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
la source
Nice! You can save one more character by changing "s=s*..." to "s*=..."
Derek Kurth
@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
Hmm, I tried it as s*=... in the jsfiddle and it seemed to work. Maybe I did something wrong, though.
Derek Kurth
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
Ah, that makes sense!
Derek Kurth
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
la source
3
You're missing one of the requirements: "Given an input n (provided however is most convenient in your chosen language)"
Steven Rumbalski
@Steven, "Given an input n"... so may I assume the n is given? I corrected the code. Is this now OK?
Tomas
I'm asked Peter Olson to clarify.
Steven Rumbalski
@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
1
Basically, 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
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
la source
Or alternatively, 20 characters t:{(x-1){0+':x,0}\1}
skeevey
Nice, shorter than the GolfScript solution now.
sinedcm
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
la source
4

Perl, 52, 49 characters

Edit: using say instead of print

map{@_=(1,map$_[$_-1]+$_[$_],1..@_);say"@_"}1..<>
Toto
la source
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
la source
4

Keg, 40 bytes

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

Explained

Pen Highlighted

Jono 2906
la source
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
la source
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
la source
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
la source
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
la source
non-competing but a holy disaster, none from previous submissions (even J) succeeded to reduce it up to how much Matl did !!!
Abr001am
I'm pretty sure Jelly or 05AB1E would be shorter though :-)
Luis Mendo
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
la source
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
la source
What's with all those 0s :-)?
mellamokb
@mellamokb Bit of re-arranging made them go away and shortened the code. :-)
Gareth
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
la source
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
la source
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
la source
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
la source
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
la source
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
la source
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
la source
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
@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
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
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
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