| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | 250117T023834Z | RARE Kpo | |
| 005 | Vyxal 3 j | 250114T192900Z | Ginger |
| 015 | APLNARS | 250111T081042Z | Rosario |
| 014 | Uiua | 250111T173318Z | janMakos |
| 522 | C | 120602T204734Z | walpen |
| 168 | Nibbles | 240525T031408Z | DLosc |
| 008 | Thunno 2 N | 230611T164401Z | The Thon |
| 050 | jq r | 221116T231320Z | pmf |
| 031 | Raku | 221101T030732Z | naffetS |
| nan | Fig | 221012T184100Z | naffetS |
| 048 | Excel | 220225T034945Z | Taylor R |
| 004 | Vyxal Mj | 210707T040539Z | Wasif |
| 008 | Jelly | 210925T031104Z | lyxal |
| 058 | Google Sheets | 201207T181725Z | General |
| 037 | Julia 0.7 | 201207T134629Z | MarcMush |
| 039 | convey | 201206T175459Z | xash |
| 058 | Scala | 201206T190134Z | user |
| 053 | Forth gforth | 201108T110225Z | Razetime |
| 097 | Scala | 201003T133724Z | cubic le |
| 010 | Husk | 201005T040643Z | DLosc |
| 011 | Pip s | 201003T173337Z | DLosc |
| 021 | Pip s | 201001T090622Z | Razetime |
| 033 | Keg | 191123T005747Z | lyxal |
| 013 | Japt R | 191125T080726Z | AZTECCO |
| 068 | Python 3 | 190925T210908Z | Legorhin |
| 015 | K ngn/k | 190925T135543Z | scrawl |
| nan | Malbolge Unshackled 20trit rotation variant | 190925T190249Z | Kamila S |
| 138 | Java 10 | 180207T153521Z | Kevin Cr |
| 311 | C | 190804T194706Z | T. Salim |
| 037 | Perl | 180213T105944Z | Ton Hosp |
| 006 | Pyth | 190804T162821Z | hakr14 |
| 069 | JavaScript | 180208T121834Z | Shaggy |
| 009 | Pyt | 180208T034301Z | mudkip20 |
| 008 | 05AB1E | 180207T175228Z | Emigna |
| 661 | PHP | 171215T131652Z | Titus |
| 046 | Ruby | 120523T153047Z | manatwor |
| 114 | Prolog SWI | 171215T070733Z | DLosc |
| 010 | MATL | 160229T105524Z | Luis Men |
| 017 | Husk | 171215T004554Z | ბიმო |
| 017 | Jelly | 170330T184536Z | Erik the |
| 014 | 05AB1E | 170316T152640Z | Magic Oc |
| 080 | VBA | 170316T180843Z | Engineer |
| 038 | R | 170918T135908Z | Giuseppe |
| 192 | Pascal | 120523T163638Z | manatwor |
| 111 | Perl | 111025T193257Z | Derek Ku |
| 092 | PHP | 111025T193024Z | Korvin S |
| 054 | Perl | 111029T104814Z | flesk |
| nan | C | 140512T094955Z | Alchymis |
| 178 | C | 170329T172152Z | Khaled.K |
| 064 | Axiom | 161202T175152Z | user5898 |
| 046 | Maple | 160729T030236Z | DSkoog |
| 015 | APL | 130515T075942Z | Volatili |
| 035 | Mathematica | 120813T104358Z | DavidC |
| 021 | Golfscript | 111021T111422Z | Peter Ta |
| 059 | postscript | 120608T035343Z | Geoff Re |
| nan | 120531T161943Z | Gaffi | |
| 049 | Perl | 111125T163936Z | Toto |
| 105 | Python | 120523T171645Z | Rushil P |
| 073 | awk | 120523T145044Z | Dan Andr |
| nan | 111020T202825Z | Mr.Wizar | |
| 203 | F♯ | 120321T111002Z | lochok |
| 025 | in Q | 120307T164326Z | sinedcm |
| 127 | C | 111124T131306Z | saeedn |
| 077 | Perl | 111123T205719Z | PhiNotPi |
| 056 | Python | 111123T170147Z | primo |
| 012 | J | 111023T214913Z | ephemien |
| 070 | Scala | 111025T045822Z | Luigi Pl |
| 063 | Python | 111021T203231Z | Steven R |
| 092 | Haskell | 111020T222022Z | hammar |
| 039 | R | 111021T162945Z | Tomas |
| 131 | Scala | 111020T221806Z | Gareth |
| 128 | D | 111020T212843Z | ratchet |
| 081 | JavaScript | 111020T195935Z | mellamok |
awk
jot 24 |
awk '$12 = _12_ += $11 = _11_ += $10 = _10_ += $9 = _9_ += \
$8 = _8_ += $7 = _7_ += $6 = _6_ += $5 = _5_ += \
$4 = _4_ += $3 = _3_ += $2 = _2_ += $1 = 1'
1 1 1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9 10 11 12
1 3 6 10 15 21 28 36 45 55 66 78
1 4 10 20 35 56 84 120 165 220 286 364
1 5 15 35 70 126 210 330 495 715 1001 1365
1 6 21 56 126 252 462 792 1287 2002 3003 4368
1 7 28 84 210 462 924 1716 3003 5005 8008 12376
1 8 36 120 330 792 1716 3432 6435 11440 19448 31824
1 9 45 165 495 1287 3003 6435 12870 24310 43758 75582
1 10 55 220 715 2002 5005 11440 24310 48620 92378 167960
1 11 66 286 1001 3003 8008 19448 43758 92378 184756 352716
1 12 78 364 1365 4368 12376 31824 75582 167960 352716 705432
1 13 91 455 1820 6188 18564 50388 125970 293930 646646 1352078
1 14 105 560 2380 8568 27132 77520 203490 497420 1144066 2496144
1 15 120 680 3060 11628 38760 116280 319770 817190 1961256 4457400
1 16 136 816 3876 15504 54264 170544 490314 1307504 3268760 7726160
1 17 153 969 4845 20349 74613 245157 [ 735471 ] 2042975 5311735 13037895
1 18 171 1140 5985 26334 100947 346104 1081575 3124550 8436285 21474180
1 19 190 1330 7315 33649 134596 480700 1562275 4686825 13123110 34597290
1 20 210 1540 8855 42504 177100 657800 2220075 6906900 20030010 54627300
1 21 231 1771 10626 53130 230230 888030 3108105 10015005 30045015 84672315
1 22 253 2024 12650 65780 296010 1184040 4292145 14307150 44352165 129024480
1 23 276 2300 14950 80730 376740 1560780 5852925 20160075 64512240 193536720
1 24 300 2600 17550 98280 475020 2035800 7888725 28048800 92561040 286097760
The number in square brackets is 24 nCr 8, which you can obtain by going down 2nd column, locating 24.
That is 1.
Then walk diagonally towards upper right like a Bishop or Queen in chess. When the count reaches 8, that is 24 nCr 8, even though that cell says 17 on 2nd column, and 9 on 2nd row. No multiplications, divisions, recursion, or dynamic-programming needed (of course you need those for arbitrary choice of the triangle)
The usual formatting of the Pascal Triangle can be extracted starting from top-left corner down to bottom right.
Vyxal 3 -j, 5 bytes
ʀƛʁℂ„
ʀƛ # for n in [0, input):
ʁ # for r in [0, n]:
ℂ # nCr(n, r) (vectorizing)
„ # join by spaces
# -j joins by newlines
💎
Created with the help of Luminespire.
APL(NARS), 15 chars
⍪{1,⍵!⍨⍳⍵}¨¯1+⍳
It seems that the above is a little short because it use the binomial function. I'm against the use of ⎕IO = 0, if it is used it has to be
in the count of the solution too... But using that ⎕IO = 0, and see the other solution it seems that 12 chars ⍪{⍵!⍨⍳⍵+1}¨⍳ is a solution.
Test:
⍪{1,⍵!⍨⍳⍵}¨¯1+⍳4
1
1 1
1 2 1
1 3 3 1
⍪{1,⍵!⍨⍳⍵}¨¯1+⍳1
1
APL(NARS), 24 chars
⍪{{1⌽1,1,2+/⍵}⍣⍵,1}¨¯1+⍳
This would return Pascal triangle using for each row the row that is just up for build row is down. It could print all the rows without recalculate each row, from one max input; but it will be more chars.
The function repeat ⍣ ⍵ times {1⌽1,1,2+/⍵}, with inital array ,1.
{{1⌽1,1,2+/⍵}⍣0,1} repeat 0 times {1⌽1,1,2+/⍵} with initial input ,1 it seems return ,1.
{{1⌽1,1,2+/⍵}⍣1,1} repeat 1 times {1⌽1,1,2+/⍵} with initial input ,1 it seems return
1 1 ; 1⌽1,1,2+/,1 is 1 1
{{1⌽1,1,2+/⍵}⍣2,1} repeat 2 times {1⌽1,1,2+/⍵} with initial input ,1 it seems calculate array 1 1, and from that array 1 2 1 that it return.
Test:
⍪{{1⌽1,1,2+/⍵}⍣⍵,1}¨¯1+⍳1
1
⍪{{1⌽1,1,2+/⍵}⍣⍵,1}¨¯1+⍳4
1
1 1
1 2 1
1 3 3 1
Uiua, 14 bytes
◌⍥⊃&p⬚0⧈₂/+:¤1
Soon should be 12 bytes, as the ₂/ should be unnecessary, but has not been implemented yet.
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; }
Nibbles, 16 nibbles (8 bytes)
<$`.,1!;:0$\@+
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.
Thunno 2 N, 8 bytes
LıDĖ€cðj
But, if outputting a nested list was ok:
Thunno 2, 6 bytes
LıDĖ€c
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
Excel, 48 bytes
Takes input \$n\$ from cell A1 and outputs an \$n\times n\$ lower triangular matrix as a spilled array to the calling cell.
=IfError(Combin(Sequence(A1),Sequence(1,A1)),"")
Jelly, 8 bytes
ḶcŻ$€K€Y
Mmm yes the output format here really do be fun tho - 5 bytes for the triangle generation, and 3 for the formatting.
Explained
ḶcŻ$€K€Y # A monadic chain with argument n. Let the current value be λ
Ḷ # λ = [0, n)
€ # over each item in λ:
cŻ$ # yield item choose [0, item] (vectorising)
K€ # join each sublist on spaces
Y # and join that on newlines
Google Sheets, 58
Input in arbitrary cell. Assign it named range "N". (+1 count)
Then use
=ArrayFormula(IFERROR(COMBIN(SEQUENCE(N,1,),SEQUENCE(1,N,
Julia 0.7, 37 bytes
f(x)=@show 1(x<2||[0;F=f(x-1)]+[F;0])
It outputs a lot of garbage but it's allowed:
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = 1
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 1]
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 2, 1]
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 3, 3, 1]
1 * (x < 2 || [0; F = f(x - 1)] + [F; 0]) = [1, 4, 6, 4, 1]
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 ].
Scala, 58 bytes
Seq.iterate(Seq(1),_){r=>1+:(r,r.tail).zipped.map(_+_):+1}
Somewhat based upon this other Scala answer.
Seq.iterate( //Make a Seq
Seq(1), //starting with just [1]
_ //of length n (_ is shorthand for n=>...n...
){ r => //Function to get next row from previous row r
(r,r.tail).zipped.map(_+_) //Add each cell with the one on its right
1+: :+1 //Put two 1's around it
}
Scala 3, 54 bytes
Seq.iterate(Seq(1),_){r=>1+:r.zip(r.tail).map(_+_):+1}
Forth (gforth), 58 53 bytes
: P 0 ?do 1 i for dup . i * j i - 1+ / next cr loop ;
This is a heavily shortened version of the implementation here, which was in turn, translated from C.
-5 bytes from Bubbler.
The function is called like: <input> P.
Scala, 97 bytes
n=>{var p=Seq(1);for(i<-0 to n-1){println(p mkString " ");p=1+:0.to(i-1).map(j=>p(j)+p(j+1)):+1}}
A for loop computes the next line's number sequence from the previous one via simple index-based addition and by concatenating 1's via +: and :+. Unfortunately this iterative approach is slightly shorter than a "nicer" monadic approach via scanLeft :)
Edit: Thanks to all commentors for tips & corrections!
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)
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)
Pip -s, 22 21 bytes
La{PooMP:_+BoPU1oPB1}
This was simpler than trying to map an iterable, and probably shorter.
-1 byte from Dlosc, using the PU and PB functions.
Explanation (old)
La{Poo:1AL(_+BMPo)AL1} a → input, o → 1(predefined)
La{ } loop a times
Po print variable o(joined by spaces due to -s)
o: assign o to:
(_+BMPo) sums of pairs of it's elements
1AL AL1 with 1 added on both sides
Japt -R, 16 13 bytes
_ä+T p1}h[1â]
_äÈ+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
Python 3, 68 Bytes
b=lambda n,a=[1]:n and[print(a),b(n-1,[*map(sum,zip([0]+a,a+[0]))])]
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!)
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:
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);}
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);
}
Pyth, 6 bytes
m.cLdh
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)
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>
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
† - This yields [[0C0],[1C0,1C1],[2C0,2C1,2C2],...,[(n-1)C0,(n-1)C1,...,(n-1)C(n-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.
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]
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).
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
Husk, 17 bytes
¶↑:;1´o¡ȯmΣ∂Ṫ*´e1
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.
Jelly, 17 bytes
3Bj+2\
1Ç⁸’¤Ð¡K€Y
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.
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:
R, 38 bytes
for(i in 0:scan())print(choose(i,0:i))
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')
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, 111 characters
I know this can be improved on, just a first try:
$r=<>;
@p=(1);
while($r--){
print join(' ',@p)."\n";
@q=@p;
unshift @q,0;
push @p,0;
$i=0;
foreach(@p){$_+=$q[$i++];}
}
PHP, 105 92 characters
for($e=1;$e++<=$i;$n=$a,$a=''){
foreach($n as $k=>$v)$a[]=$v+$n[$k-1];
$a[]=1;print_r($a);}
Input: $i = 9;
Output:
Array
(
[0] => 1
)
Array
(
[0] => 1
[1] => 1
)
Array
(
[0] => 1
[1] => 2
[2] => 1
)
Array
(
[0] => 1
[1] => 3
[2] => 3
[3] => 1
)
Array
(
[0] => 1
[1] => 4
[2] => 6
[3] => 4
[4] => 1
)
Array
(
[0] => 1
[1] => 5
[2] => 10
[3] => 10
[4] => 5
[5] => 1
)
Array
(
[0] => 1
[1] => 6
[2] => 15
[3] => 20
[4] => 15
[5] => 6
[6] => 1
)
Array
(
[0] => 1
[1] => 7
[2] => 21
[3] => 35
[4] => 35
[5] => 21
[6] => 7
[7] => 1
)
Array
(
[0] => 1
[1] => 8
[2] => 28
[3] => 56
[4] => 70
[5] => 56
[6] => 28
[7] => 8
[8] => 1
)
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.
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]);}
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);}
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;
}
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
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
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 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⍳⍵+1with an index origin of 0.
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}}
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
;
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]
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
Perl, 52, 49 characters
Edit: using say instead of print
map{@_=(1,map$_[$_-1]+$_[$_],1..@_);say"@_"}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
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
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
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")
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
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);}
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
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]
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|+-+--+|||||| |||
|| ||| ||| || || ||!|{:||||||| |||
|| ||| ||| || || |+-+--+|||||| |||
|| ||| ||| || |+-+------+||||| |||
|| ||| ||| |+--+----------+|||| |||
|| ||| ||+-+---------------+||| |||
|| ||| |+-------------------+|| |||
|| ||+-+---------------------+| |||
|| |+-------------------------+--+||
|+-+------------------------------+|
+----------------------------------+
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)))
Python, 94 91 88 70 63 characters
x=[1]
for i in input()*x:
print x
x=map(sum,zip([0]+x,x+[0]))
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]
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)
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
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
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



