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
-
\$\begingroup\$ NB In a sense this is a simplified version of Distributing the balls \$\endgroup\$Peter Taylor– Peter Taylor2011年10月21日 11:03:31 +00:00Commented 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\$Steven Rumbalski– Steven Rumbalski2011年10月21日 20:57:51 +00:00Commented 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\$Peter Olson– Peter Olson2011年10月21日 21:32:00 +00:00Commented 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\$Steven Rumbalski– Steven Rumbalski2011年10月21日 21:50:14 +00:00Commented 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\$Peter Olson– Peter Olson2012年06月08日 04:05:46 +00:00Commented Jun 8, 2012 at 4:05
73 Answers 73
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|+-+--+|||||| |||
|| ||| ||| || || ||!|{:||||||| |||
|| ||| ||| || || |+-+--+|||||| |||
|| ||| ||| || |+-+------+||||| |||
|| ||| ||| |+--+----------+|||| |||
|| ||| ||+-+---------------+||| |||
|| ||| |+-------------------+|| |||
|| ||+-+---------------------+| |||
|| |+-------------------------+--+||
|+-+------------------------------+|
+----------------------------------+
-
3\$\begingroup\$ J beats GolfScript? Interesting. I would like to see an explanation for this code, if you have time. \$\endgroup\$Mr.Wizard– Mr.Wizard2011年10月26日 09:31:59 +00:00Commented Oct 26, 2011 at 9:31
-
6\$\begingroup\$ It's already split down, but here's a line by line if you'd like additional english. Line 1
i.5returns the first five naturals. Line 2 adds{:"Tail" (return last). Line 3 combines them with!"Out Of" (number of combinations). Line 4(!{:)i.5is 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. \$\endgroup\$J B– J B2011年11月02日 14:51:54 +00:00Commented Nov 2, 2011 at 14:51 -
\$\begingroup\$ @JB Isn't ! means factorial here? Also we can get rid of @ at the right. \$\endgroup\$Art– Art2012年08月15日 14:35:17 +00:00Commented Aug 15, 2012 at 14:35
-
1\$\begingroup\$ @ArtemIce Monadic
!means factorial; dyadic!counts combinations. The final@in":@(!{:)\@i.is just there to make this a stand-alone verb. \$\endgroup\$ephemient– ephemient2012年08月15日 14:38:40 +00:00Commented Aug 15, 2012 at 14:38
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]
C, 522 bytes
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; }
-
8\$\begingroup\$ 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). \$\endgroup\$Peter Taylor– Peter Taylor2012年06月06日 16:11:13 +00:00Commented Jun 6, 2012 at 16:11
-
3\$\begingroup\$ It was fun to write. That's generally what I come to codegolf for. \$\endgroup\$walpen– walpen2012年06月06日 21:03:28 +00:00Commented Jun 6, 2012 at 21:03
-
2\$\begingroup\$ Clever :) Have an upvote. Maybe not a winner candidate but a creative one! \$\endgroup\$Accatyyc– Accatyyc2012年08月10日 13:02:33 +00:00Commented Aug 10, 2012 at 13:02
Python, (削除) 94 (削除ここまで) (削除) 91 (削除ここまで) (削除) 88 (削除ここまで) (削除) 70 (削除ここまで) 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
;
-
\$\begingroup\$ You might want to try golf.shinh.org/p.rb?pascal+triangle \$\endgroup\$Nabb– Nabb2011年10月22日 03:31:42 +00:00Commented Oct 22, 2011 at 3:31
-
\$\begingroup\$ 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. \$\endgroup\$anon– anon2012年08月10日 02:50:10 +00:00Commented Aug 10, 2012 at 2:50
-
\$\begingroup\$ Thank you for the detailed explanation and excellent answer (+1), but I'm even more confused now. The logic (process) isn't sitting right. \$\endgroup\$anon– anon2012年08月10日 19:03:29 +00:00Commented Aug 10, 2012 at 19:03
-
\$\begingroup\$ @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. \$\endgroup\$Peter Taylor– Peter Taylor2012年08月10日 19:23:12 +00:00Commented Aug 10, 2012 at 19:23
-
\$\begingroup\$ 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)? \$\endgroup\$anon– anon2012年08月11日 02:40:06 +00:00Commented Aug 11, 2012 at 2:40
convey, 39 bytes
convey is a new 2d esolang I made. It is based on conveyor belts that move values around in a factory. v<^> are explicit belt directions, other connections are inferred, as each function has a fixed number of inputs and outputs. For example, + takes 2 values in and returns 1 value.
v<<<.~/.]
v>,v}"!{
"/&v}11
\v>+/^
,ドル^
_
A row enters the main part from the top left. Two tiles in, the row gets " copied down and right. The right part prepends a _, which is a so called 'default value'. The actual value of _ depends on the function it enters. It works like the neutral element, thus _ + 3 = 3, 4 * _ = 4.
To understand the next part we have to take a look at port order. For example, , will join two paths, favoring the main input port. The order is as follows (lower takes precedence):
For input: For output:
0 3
v ^
1>f<3 2<f>0
^ v
2 1
So the upper , will favor inputs from the left, and the lower , will favor inputs from the top. In the animation the arrow heads are drawn a bit thicker to indicate main ports.
On / (rising flank) whenever a new list enters the tile, _ gets pushed to the side port. _ and the row then get joined, whereas the _ comes from the main port and thus has right of way.
The bottom part appends a _ by similar means: \ (falling flank) pushes the length of the list to the side port, that will be set $ to _.
Finally, _ 1 2 1 and 1 2 1 _ get added in + and we get the next row 1 3 3 1! We print a newline /} (_ in } prints newlines) and then copy the row into the output "}. To prevent a row colliding with the next row when they get longer, we batch ~. the lists: we first let 1 element through, then 2, then 3 ... by getting the indices /. of an list of n 1s ({!1}), that get discarded in a sink ].
-
\$\begingroup\$ unrelated question: how did you get the λ.land domain? \$\endgroup\$Razetime– Razetime2020年12月07日 04:44:24 +00:00Commented Dec 7, 2020 at 4:44
-
\$\begingroup\$ @Razetime most generic TLDs support non-latin letters/IDNs which are rarely taken because realistically you have to use the puny code variant (xn--wxa.land) most of the time. My more fun domain ꙮ.world f.e. lies in the extended Cyrillic UTF-8 block. \$\endgroup\$xash– xash2020年12月07日 08:49:40 +00:00Commented Dec 7, 2020 at 8:49
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]
-
1\$\begingroup\$ you can save 2 chars with
p.map!{|i|(v=n)+n=i}\$\endgroup\$jsvnm– jsvnm2012年08月10日 11:21:34 +00:00Commented Aug 10, 2012 at 11:21 -
\$\begingroup\$ Great one, @jsvnm! Man, how long I combined to shorten that part. Thanks. \$\endgroup\$manatwork– manatwork2012年08月10日 11:44:23 +00:00Commented Aug 10, 2012 at 11:44
-
1\$\begingroup\$ Maybe a little late, but: why use the variable v? \$\endgroup\$G B– G B2017年12月15日 08:08:24 +00:00Commented Dec 15, 2017 at 8:08
-
\$\begingroup\$ 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. \$\endgroup\$manatwork– manatwork2017年12月15日 09:07:55 +00:00Commented Dec 15, 2017 at 9:07
Keg, (削除) 40 (削除ここまで) 33 bytes
1:&¿1.
,(|((8)|:(8)$@MCƒZ. ,9)(6)_01.
,
Old Program Explained
Pen Highlighted
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)))
-
\$\begingroup\$ + 1 for shameless copying! \$\endgroup\$Steven Rumbalski– Steven Rumbalski2011年10月25日 21:23:30 +00:00Commented Oct 25, 2011 at 21:23
-
\$\begingroup\$ The last version should be used carefully for huge values of readInt, like 50. ;) \$\endgroup\$user unknown– user unknown2012年05月31日 22:16:07 +00:00Commented May 31, 2012 at 22:16
-
\$\begingroup\$ @userunknown presumably that's why the question specifies an upper limit of 25... \$\endgroup\$Luigi Plinge– Luigi Plinge2012年05月31日 22:25:03 +00:00Commented May 31, 2012 at 22:25
-
\$\begingroup\$ It wasn't meant as critique, just as a warning for the curious. \$\endgroup\$user unknown– user unknown2012年05月31日 22:41:34 +00:00Commented May 31, 2012 at 22:41
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]
-
\$\begingroup\$ You can save a character by using
mapMinstead ofmapM_. \$\endgroup\$dfeuer– dfeuer2019年02月25日 04:23:17 +00:00Commented Feb 25, 2019 at 4:23
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)
-
4\$\begingroup\$ You're missing one of the requirements: "Given an input n (provided however is most convenient in your chosen language)" \$\endgroup\$Steven Rumbalski– Steven Rumbalski2011年10月21日 20:59:06 +00:00Commented Oct 21, 2011 at 20:59
-
\$\begingroup\$ @Steven, "Given an input n"... so may I assume the
nis given? I corrected the code. Is this now OK? \$\endgroup\$Tomas– Tomas2011年10月21日 21:38:46 +00:00Commented Oct 21, 2011 at 21:38 -
\$\begingroup\$ I'm asked Peter Olson to clarify. \$\endgroup\$Steven Rumbalski– Steven Rumbalski2011年10月21日 21:52:42 +00:00Commented Oct 21, 2011 at 21:52
-
\$\begingroup\$ @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. \$\endgroup\$Peter Olson– Peter Olson2011年10月22日 00:04:48 +00:00Commented Oct 22, 2011 at 0:04
-
1\$\begingroup\$ Basically, the
nmust 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. \$\endgroup\$Steven Rumbalski– Steven Rumbalski2011年10月24日 13:01:35 +00:00Commented Oct 24, 2011 at 13:01
Husk, (削除) 13 (削除ここまで) 10 bytes
-3 bytes thanks to Zgarb
mw↑¡Sż+Θ;1
Explanation
Based on the same idea as my Pip answer: generate each row from the last one by tacking a 0 to the front of the row and adding it to itself element-wise. The Husk version creates the entire triangle as an infinite lazy list and then takes however many rows we need.
;1 Start with [1]
¡ Iterate this function:
S S-combinator: Sfgx is fx(gx) (aka f(x,g(x)) in C-style syntax)
ż+ f: add a list itemwise to another list, keeping the extra value at
the end of the longer list unchanged
Θ g: prepend a falsey value (given a list of integers, prepend 0)
The result of Sż+Θ is a 1-argument function that prepends a 0 to its
argument and adds that itemwise to another copy of the argument
↑ From the infinite list of results, take N (where N is the input)
mw Join each sublist on spaces (which means the main list gets
autojoined on newlines)
-
2\$\begingroup\$ Nice first Husk answer! A couple of hints.
Θprepends a default falsy value, which is 0 for the number type. You can avoid creating a helper function withS.Sfgis equivalent to callingfg¹from a separate line. \$\endgroup\$Zgarb– Zgarb2020年10月05日 06:21:34 +00:00Commented Oct 5, 2020 at 6:21
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
-
\$\begingroup\$ Nice! You can save one more character by changing "s=s*..." to "s*=..." \$\endgroup\$Derek Kurth– Derek Kurth2011年10月25日 19:41:43 +00:00Commented Oct 25, 2011 at 19:41
-
\$\begingroup\$ @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, nots*((i-j)/j). \$\endgroup\$mellamokb– mellamokb2011年10月25日 19:49:23 +00:00Commented Oct 25, 2011 at 19:49 -
\$\begingroup\$ Hmm, I tried it as s*=... in the jsfiddle and it seemed to work. Maybe I did something wrong, though. \$\endgroup\$Derek Kurth– Derek Kurth2011年10月25日 20:16:00 +00:00Commented Oct 25, 2011 at 20:16
-
1\$\begingroup\$ @DerekKurth: Technically it is the same, but the idea is that if you multiply by
(i-j)before dividing byj, 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 aboutn>11, and you'll see decimal values in the output, i.e.,1 11 55 165 330 461.99999999999994 461.99999999999994...\$\endgroup\$mellamokb– mellamokb2011年10月25日 21:47:25 +00:00Commented Oct 25, 2011 at 21:47 -
\$\begingroup\$ Ah, that makes sense! \$\endgroup\$Derek Kurth– Derek Kurth2011年10月25日 22:10:13 +00:00Commented Oct 25, 2011 at 22:10
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
-
\$\begingroup\$ Or alternatively, 20 characters
t:{(x-1){0+':x,0}1円}\$\endgroup\$skeevey– skeevey2012年03月08日 20:35:15 +00:00Commented Mar 8, 2012 at 20:35 -
\$\begingroup\$ Nice, shorter than the GolfScript solution now. \$\endgroup\$sinedcm– sinedcm2012年03月09日 12:10:28 +00:00Commented Mar 9, 2012 at 12: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
Perl, (削除) 52 (削除ここまで), 49 characters
Edit: using say instead of print
map{@_=(1,map$_[$_-1]+$_[$_],1..@_);say"@_"}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⍵-1inclusive, where⍵is the right argument to the function.⍳⍵+1generates all numbers from 0 to⍵{⍵!⍨⍳⍵+1}generates⍵choosekfor every elementkin⍳⍵+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 thë(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⍳⍵+1with an index origin of 0.
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.
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
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);}
MATL, 10 bytes
Language created after this challenge
1iq:"tTTY+
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
-
\$\begingroup\$ non-competing but a holy disaster, none from previous submissions (even J) succeeded to reduce it up to how much Matl did !!! \$\endgroup\$Abr001am– Abr001am2016年05月21日 09:09:09 +00:00Commented May 21, 2016 at 9:09
-
\$\begingroup\$ I'm pretty sure Jelly or 05AB1E would be shorter though :-) \$\endgroup\$Luis Mendo– Luis Mendo2016年05月21日 10:34:34 +00:00Commented May 21, 2016 at 10:34
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>
Pip -s, (削除) 14 (削除ここまで) 11 bytes
LaPl+:lPE!l
Explanation
Each row of the triangle, represented as a list, can be obtained by adding two copies of the previous row with an offset:
[1 2 1]
+ [1 2 1]
----------
[1 3 3 1]
Pip's default behavior when adding two lists is almost perfect: it matches up the elements and adds them pairwise, and if one list is longer, the extra numbers in that list are retained unchanged. So all we have to do is offset one list by prepending a 0:
[1 2 1]
+[0 1 2 1]
----------
[1 3 3 1]
Here's the version I started with before golfing:
Y[1]La{Pyy+:yPE0}
a is command-line argument (implicit)
Y[1] Yank list representing the first row into y
La{ } Loop a times:
Py Print the current row (space-separated, thanks to -s flag)
yPE0 Construct a list which is y with 0 prepended
y+: Add that to y and assign the result back to y
My original golfed version applied a few tricks:
- Using this tip,
[1]→^1. - We can save the curly braces if the loop body is one statement, which we can accomplish by printing
yin the expression that updatesy:y+:(Py)PE0. - We can then save the parentheses by changing
yPE0(ywith0prepended) to0ALy(0with the listyappended;0gets promoted to a singleton list[0]first). This leaves us withy+:0AL(Py), but sincePis unary we can drop the parentheses (though we still need a space between the operators):y+:0AL Py.
The resulting solution is 14 bytes:
Y^1Lay+:0AL Py
But we can do better!
- It would be nice to save the space before
P; also, the initializationY^1is rather expensive. - If we could start from an empty list (as the "0th" row) and print each row after it is updated, we could solve both problems: we could use
l(which is preinitialized to the empty list) instead ofy, and thePwould come immediately after the loop header and therefore not require a separator. - The problem is that our update logic, "prepend a 0 and add," doesn't work for the first row: it gives
[] + [0] = [0], when we need[1]. - But, if we can prepend a 1 on the first iteration and a 0 every other time, we'll be golden. On the first iteration,
lis empty (falsey); on every other iteration,lis nonempty (truthy). So we can simply prepend!l.
This approach gives us our 11-byte solution:
LaPl+:lPE!l
La Loop a times:
!l 1 if l is empty, 0 otherwise
lPE Construct a list which is l with that value prepended
l+: Add that to l and assign the result back to l
P Print (space-separated: -s flag)
-
\$\begingroup\$ I knew mine wasn't the shortest, but not by this much. What a clean solution. \$\endgroup\$Razetime– Razetime2020年10月04日 03:10:03 +00:00Commented Oct 4, 2020 at 3:10
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
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
-
\$\begingroup\$ What's with all those
0s :-)? \$\endgroup\$mellamokb– mellamokb2011年10月20日 22:23:39 +00:00Commented Oct 20, 2011 at 22:23 -
\$\begingroup\$ @mellamokb Bit of re-arranging made them go away and shortened the code. :-) \$\endgroup\$Gareth– Gareth2011年10月20日 22:28:20 +00:00Commented Oct 20, 2011 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")
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