Pascal's triangle: Difference between revisions
m
→{{header|Wren}}: Minor tidy and now uses binomial method in Math module.
(Added solution for Action!) |
m (→{{header|Wren}}: Minor tidy and now uses binomial method in Math module.) |
||
(38 intermediate revisions by 17 users not shown) | |||
Line 42:
{{trans|Python}}
<
V row = [1]
V k = [0]
Line 49:
row = zip(row [+] k, k [+] row).map((l, r) -> l + r)
pascal(7)</
{{out}}
Line 64:
=={{header|360 Assembly}}==
{{trans|PL/I}}
<
PASCAL CSECT
USING PASCAL,R15 set base register
Line 101:
XD DS CL12 temp
YREGS
END PASCAL</
{{out}}
<pre>
Line 119:
=={{header|8th}}==
One way, using array operations:
<
\ print the array
: .arr \ a -- a
Line 135:
\ print the first 16 rows:
[1] ' pasc 16 times
</syntaxhighlight>
Another way, using the relation between element 'n' and element 'n-1' in a row:
<
: ratio \ m n -- num denom
tuck n:- n:1+ swap ;
Line 160:
15 pasc
</syntaxhighlight>
=={{header|Action!}}==
<
BYTE count=[10],row,item
CHAR ARRAY s(5)
Line 180:
PutE()
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer]
Line 200:
The specification of auxiliary package "Pascal". "First_Row" outputs a row with a single "1", "Next_Row" computes the next row from a given row, and "Length" gives the number of entries in a row. The package is also used for the Catalan numbers solution [[http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle]]
<
type Row is array (Natural range <>) of Natural;
Line 210:
function Next_Row(R: Row) return Row;
end Pascal;</
The implementation of that auxiliary package "Pascal":
<
function First_Row(Max_Length: Positive) return Row is
Line 239:
end Length;
end Pascal;</
The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line.
<
procedure Triangle is
Line 260:
Row := Next_Row(Row);
end loop;
end Triangle;</
{{out}}
Line 279:
=={{header|ALGOL 68}}==
<
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);
Line 297:
# WHILE # i < stop DO
row := row[AT 1] + row[AT 2]
OD</
{{Out}}
<pre>
Line 312:
=={{header|ALGOL W}}==
<
% prints the first n lines of Pascal's triangle lines %
% if n is <= 0, no output is produced %
Line 330:
printPascalTriangle( 8 )
end.</
{{out}}
<pre>
Line 341:
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="Amazing Hopper">
#include <jambo.h>
#define Mulbyandmoveto(_X_) Mul by '_X_', Move to '_X_'
Main
filas=0, Get arg numeric '2', Move to 'filas'
i=0, r=""
Loop if( var 'i' Is less than 'filas' )
c=1, j=0
Set 'c' To str, Move to 'r'
Loop if ( var 'j' Is less than 'i' )
Set 'i' Minus 'j', Plus one 'j', Div it; Mul by and move to 'c'
Multi cat ' r, "\t", Str(c) '; Move to 'r'
++j
Back
Printnl 'r'
++i
Back
End
</syntaxhighlight>
{{out}}
<pre>
$ hopper jm/pascal.jambo 14
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
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
</pre>
Line 346 ⟶ 387:
Pascal' s triangle of order ⍵
=== Dyalog APL ===
<
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}
</syntaxhighlight>
example
<
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5
</syntaxhighlight>
<pre>
Line 367 ⟶ 408:
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently:
<
{{⍉⍵∘.!⍵} 0,⍳⍵}
</syntaxhighlight>
example
<
{{⍉⍵∘.!⍵} 0,⍳⍵} 3
</syntaxhighlight>
<pre>
Line 386 ⟶ 427:
=={{header|AppleScript}}==
Drawing n rows from a generator:
<
-- pascal :: Generator [[Int]]
Line 598 ⟶ 639:
return lst
end tell
end zipWith</
{{Out}}
<pre> 1
Line 607 ⟶ 648:
1 5 10 10 5 1
1 6 15 20 15 6 1</pre>
=={{header|Arturo}}==
{{trans|Nim}}
<syntaxhighlight lang="rebol">pascalTriangle: function [n][
triangle: new [[1]]
loop 1..dec n 'x [
'triangle ++ @[map couple (last triangle)++[0] [0]++(last triangle) 'x -> x\[0] + x\[1]]
]
return triangle
]
loop pascalTriangle 10 'row [
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60
]</syntaxhighlight>
{{out}}
<pre> 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</pre>
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion]
<
Loop %n% {
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
Line 631 ⟶ 701:
GuiClose:
ExitApp</
Alternate {{works with|AutoHotkey L}}
<
Return
Line 658 ⟶ 728:
: p[row-1, col])
Return p
}</
n <= 0 returns empty
=={{header|AWK}}==
<
{{Out}}<pre>
1
Line 671 ⟶ 741:
1 5 10 10 5 1
</pre>
=={{header|Bait}}==
<syntaxhighlight lang="bait">
// Create a Pascal's triangle with a given number of rows.
// Returns an empty array for row_nr <= 0.
fun pascals_triangle(row_nr i32) [][]i32 {
mut rows := [][]i32
// Iterate over all rows
for r := 0; r < row_nr; r += 1 {
// Store the row above the current one
mut above := rows[r - 1]
// Fill the current row. It contains r + 1 numbers
for i := 0; i <= r; i += 1 {
// First number is always 1
if i == 0 {
rows.push([1]) // Push new row
}
// Last number is always 1
else if i == r {
rows[r].push(1)
}
// Other numbers are the sum of the two numbers above them
else {
rows[r].push(above[i - 1] + above[i])
}
}
}
return rows
}
// Helper function to pretty print triangles.
// It still get's ugly once numbers have >= 2 digits.
fun print_triangle(triangle [][]i32) {
for i, row in triangle {
// Create string with leading spaces
mut s := ' '.repeat(triangle.length - i - 1)
// Add each number to the string
for n in row {
s += n.str() + ' '
}
// Print and trim the extra trailing space
println(s.trim_right(' '))
}
}
fun main() {
print_triangle(pascals_triangle(7))
}
</syntaxhighlight>
{{out}}
<pre>
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
</pre>
=={{header|BASIC}}==
Line 685 ⟶ 823:
If the user enters value less than 1, the first row is still always displayed.
<
DIM row AS Integer
DIM nrows AS Integer
Line 700 ⟶ 838:
NEXT i
PRINT
NEXT row</
=={{header|Batch File}}==
Based from the Fortran Code.
<
setlocal enabledelayedexpansion
Line 742 ⟶ 880:
for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
::/The Functions.</
{{Out}}
<pre> 1
Line 763 ⟶ 901:
=={{header|BBC BASIC}}==
<
colwidth% = 4
Line 775 ⟶ 913:
NEXT
PRINT
NEXT row%</
{{Out}}
<pre> 1
Line 789 ⟶ 927:
=={{header|BCPL}}==
<
let pascal(n) be
Line 802 ⟶ 940:
$)
let start() be pascal(8)</
{{out}}
<pre> 1
Line 814 ⟶ 952:
=={{header|Befunge}}==
<
v01*p00-1:g00.:<1p011p00:\-1_v#:<
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</
{{Out}}
<pre>Number of rows: 10
Line 830 ⟶ 968:
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1 </pre>
=={{header|BQN}}==
Displays n rows.
<syntaxhighlight lang="bqn">Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1}
•Show¨Pascal 6</syntaxhighlight>
<syntaxhighlight lang="text">⟨ 1 ⟩
⟨ 1 1 ⟩
⟨ 1 2 1 ⟩
⟨ 1 3 3 1 ⟩
⟨ 1 4 6 4 1 ⟩
⟨ 1 5 10 10 5 1 ⟩</syntaxhighlight>
=={{header|Bracmat}}==
<
& get':?R
& -1:?I
Line 849 ⟶ 1,001:
)
&
)</
{{Out}}
<pre>Number of rows?
Line 863 ⟶ 1,015:
=={{header|Burlesque}}==
<
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
1
Line 882 ⟶ 1,034:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
=={{header|C}}==
Line 888 ⟶ 1,040:
{{trans|Fortran}}
<
void pascaltriangle(unsigned int n)
Line 909 ⟶ 1,061:
pascaltriangle(8);
return 0;
}</
===Recursive===
<
#define D 32
Line 929 ⟶ 1,081:
int x[D] = {0, 1, 0}, y[D] = {0};
return pascals(x, y, 0);
}</
===Adding previous row values===
<
if (nRows <= 0) return;
int *prevRow = NULL;
Line 948 ⟶ 1,100:
}
free(prevRow);
}</
=={{header|C sharp|C#}}==
Line 954 ⟶ 1,106:
Produces no output when n is less than or equal to zero.
<
namespace RosettaCode {
Line 978 ⟶ 1,130:
}
}
}</
===Arbitrarily large numbers (BigInteger), arbitrary row selection===
<
using System.Linq;
using System.Numerics;
Line 1,028 ⟶ 1,180:
}
}
}</
Example:
<
{
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20);
string output = PascalsTriangle.FormatTriangleString(triangle)
Console.WriteLine(output);
}</
{{out}}
Line 1,063 ⟶ 1,215:
=={{header|C++}}==
<
#include <algorithm>
#include<cstdio>
Line 1,142 ⟶ 1,294:
}
}</
===C++11 (with dynamic and semi-static vectors)===
Constructs the whole triangle in memory before printing it. Uses vector of vectors as a 2D array with variable column size. Theoretically, semi-static version should work a little faster.
<
#include<iostream>
#include<vector>
Line 1,231 ⟶ 1,383:
}
</syntaxhighlight>
===C++11 (with a class) ===
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented.
<
#include<iostream>
#include<vector>
Line 1,315 ⟶ 1,467:
}
</syntaxhighlight>
=={{header|Clojure}}==
For n < 1, prints nothing, always returns nil. Copied from the Common Lisp implementation below, but with local functions and explicit tail-call-optimized recursion (recur).
<
(let [newrow (fn newrow [lst ret]
(if lst
Line 1,331 ⟶ 1,483:
(recur (dec n) (conj (newrow lst []) 1)))))]
(genrow n [1])))
(pascal 4)</
And here's another version, using the ''partition'' function to produce the sequence of pairs in a row, which are summed and placed between two ones to produce the next row:
<
(defn nextrow [row]
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))
Line 1,342 ⟶ 1,494:
(doseq [row triangle]
(println row))))
</syntaxhighlight>
The ''assert'' form causes the ''pascal'' function to throw an exception unless the argument is (integral and) positive.
Here's a third version using the ''iterate'' function
<
(def pascal
(iterate
Line 1,354 ⟶ 1,506:
(map (partial apply +) ,,,)))
[1]))
</syntaxhighlight>
Another short version which returns an infinite pascal triangle as a list, using the iterate function.
<
(def pascal
(iterate #(concat [1]
Line 1,364 ⟶ 1,516:
[1])
[1]))
</syntaxhighlight>
One can then get the first n rows using the take function
<
(take 10 pascal) ; returns a list of the first 10 pascal rows
</syntaxhighlight>
Also, one can retrieve the nth row using the nth function
<
(nth pascal 10) ;returns the nth row
</syntaxhighlight>
=={{header|CoffeeScript}}==
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients.
<
pascal = (n) ->
width = 6
Line 1,410 ⟶ 1,562:
pascal(7)
</syntaxhighlight>
{{Out}}
Line 1,425 ⟶ 1,577:
=={{header|Commodore BASIC}}==
<
20 IF N<1 THEN END
30 DIM C(N)
Line 1,448 ⟶ 1,600:
220 C(I)=D(I)
230 NEXT I
240 NEXT J</
Output:
<syntaxhighlight lang="text">RUN
HOW MANY? 8
1
Line 1,463 ⟶ 1,615:
1 8 28 56 70 56 28 8 1
READY.
</syntaxhighlight>
=={{header|Common Lisp}}==
To evaluate, call (pascal n). For n < 1, it simply returns nil.
<
(defun genrow (n l)
(defun newrow (l)
'(1)
(cons (+ (
(newrow (rest l)))))</syntaxhighlight>
An iterative solution with ''loop'', using ''nconc'' instead of ''collect'' to keep track of the last ''cons''. Otherwise, it would be necessary to traverse the list to do a ''(rplacd (last a) (list 1))''.
<
(defun pascal (n)
Another iterative solution, this time using pretty-printing to automatically print the triangle in the shape of a triangle in the terminal. The print-pascal-
<
(defun next-pascal-triangle-row (
`(1
1))
(defun pascal-
(loop repeat number-of-rows
(defun print-pascal-triangle (number-of-rows)
(let* ((triangle (pascal-triangle number-of-rows))
(max-row-length (length (write-to-string (first (last triangle))))))
(format t
(format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" max-row-length)
triangle)))
</syntaxhighlight>
For example:
<
<syntaxhighlight lang="text">
</syntaxhighlight>
<syntaxhighlight lang="lisp">(print-pascal-triangle 8)</syntaxhighlight>
<syntaxhighlight lang="text">
1
1
1 3 3 1
1 4 6
1 5 10 10
1 6 15
1 7 21
</syntaxhighlight>
=={{header|Component Pascal}}==
{{Works with|BlackBox Component Builder}}
<
MODULE PascalTriangle;
IMPORT StdLog, DevCommanders, TextMappers;
Line 1,609 ⟶ 1,765:
END PascalTriangle.
</syntaxhighlight>
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre>
{{out}}
Line 1,630 ⟶ 1,786:
=={{header|D}}==
===Less functional Version===
<
auto tri = new int[][rows];
foreach (r; 0 .. rows) {
Line 1,654 ⟶ 1,810:
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
}</
===More functional Version===
<
auto pascal() pure nothrow {
Line 1,666 ⟶ 1,822:
void main() {
pascal.take(5).writeln;
}</
{{out}}
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre>
Line 1,674 ⟶ 1,830:
Their difference are the initial line and the operation that act on the line element to produce next line.
The following is a generic pascal's triangle implementation for positive number of lines output (n).
<
string Pascal(alias dg, T, T initValue)(int n) {
Line 1,715 ⟶ 1,871:
foreach (i; [16])
writef(sierpinski(i));
}</
{{out}}
<pre> 1
Line 1,750 ⟶ 1,906:
=={{header|Dart}}==
<
import 'dart:io';
Line 1,793 ⟶ 1,949:
</syntaxhighlight>
=={{header|Delphi}}==
<
procedure Pascal(r:Integer);
Line 1,816 ⟶ 1,972:
begin
Pascal(9);
end.</
=={{header|DWScript}}==
Doesn't print anything for negative or null values.
<
var
i, c, k : Integer;
Line 1,834 ⟶ 1,990:
end;
Pascal(9);</
{{Out}}
<pre> 1
Line 1,850 ⟶ 2,006:
So as not to bother with text layout, this implementation generates a HTML fragment. It uses a single mutable array, appending one 1 and adding to each value the preceding value.
<
def row := [].diverge(int)
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
Line 1,869 ⟶ 2,025:
}
out.print("</table>")
}</
<
try {
pascalsTriangle(15, out)
Line 1,877 ⟶ 2,033:
out.close()
}
makeCommand("yourFavoriteWebBrowser")("triangle.html")</
=={{header|EasyLang}}==
<syntaxhighlight>
numfmt 0 4
proc pascal n . .
r[] = [ 1 ]
for i to n
rn[] = [ ]
l = 0
for j to n - len r[]
write " "
.
for r in r[]
write r
rn[] &= l + r
l = r
.
print ""
rn[] &= l
swap r[] rn[]
.
.
pascal 13
</syntaxhighlight>
=={{header|Eiffel}}==
<
note
description : "Prints pascal's triangle"
Line 1,983 ⟶ 2,163:
--Contains all already calculated lines
end
</syntaxhighlight>
=={{header|Elixir}}==
<
def triangle(n), do: triangle(n,[1])
Line 1,997 ⟶ 2,177:
end
Pascal.triangle(8)</
{{out}}
Line 2,013 ⟶ 2,193:
=={{header|Emacs Lisp}}==
===Using mapcar and append, returing a list of rows===
<syntaxhighlight lang
(cl-mapcar #'+ (cons 0 row)
(append row '(0))))
(defun triangle (row rows)
(if (= rows 0)
'()
(cons row (triangle (next-row row) (- rows 1)))))</syntaxhighlight>
{{Out}}
Line 2,035 ⟶ 2,216:
</pre>
===Translation from Pascal===
<
(dotimes (i r)
(let ((c 1))
Line 2,042 ⟶ 2,223:
(setq c (/ (* c (- i k))
(+ k 1))))
(terpri))))</syntaxhighlight>
{{Out}}
From the REPL:
Line 2,057 ⟶ 2,237:
===Returning a string===
Same as the translation from Pascal, but now returning a string.
<
(let ((out ""))
(dotimes (i r)
Line 2,066 ⟶ 2,246:
(+ k 1))))
(setq out (concat out "\n"))))
out))</syntaxhighlight>
{{Out}}
Now, since this one returns a string, it is possible to insert the result in the current buffer:
Line 2,083 ⟶ 2,262:
=={{header|Erlang}}==
<
-import(lists).
-export([pascal/1]).
Line 2,092 ⟶ 2,271:
[H|_] = L,
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].
</syntaxhighlight>
{{Out}}
Line 2,102 ⟶ 2,281:
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM PASCAL_TRIANGLE
Line 2,120 ⟶ 2,299:
PASCAL(9)
END PROGRAM
</syntaxhighlight>
Output:
<pre>
Line 2,136 ⟶ 2,315:
=={{header|Euphoria}}==
===Summing from Previous Rows===
<
row = {}
for m = 1 to 10 do
Line 2,145 ⟶ 2,324:
print(1,row)
puts(1,'\n')
end for</
{{Out}}
Line 2,169 ⟶ 2,348:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(n,
BINCOEFF(n - 1)(
Line 2,182 ⟶ 2,361:
QUOTIENT(FACT(n), FACT(k) * FACT(n - k))
)
)</
{{Out}}
Line 2,340 ⟶ 2,519:
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda:
<
=LAMBDA(n,
LET(
Line 2,351 ⟶ 2,530:
)
)
)</
{{Out}}
Line 2,508 ⟶ 2,687:
=={{header|F Sharp|F#}}==
<
match l with
| [] -> []
Line 2,520 ⟶ 2,699:
printf "%s" (i.ToString() + ", ")
printfn "%s" "\n"
</syntaxhighlight>
=={{header|Factor}}==
Line 2,526 ⟶ 2,705:
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1.
<
: (pascal) ( seq -- newseq )
Line 2,532 ⟶ 2,711:
: pascal ( n -- seq )
1 - { { 1 } } swap [ (pascal) ] times ;</
It works as:
<
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }</
=={{header|Fantom}}==
<
class Main
{
Line 2,571 ⟶ 2,750:
}
}
</syntaxhighlight>
=={{header|FOCAL}}==
<
1.2 F N=1,10; D 2
1.3 Q
Line 2,584 ⟶ 2,763:
3.1 S OLD(X)=NEW(X)
3.2 T %4.0, OLD(X)</
{{output}}
<pre>
Line 2,601 ⟶ 2,780:
=={{header|Forth}}==
<
here swap cells erase 1 here ! ;
: .line ( n -- )
Line 2,611 ⟶ 2,790:
: pascal ( n -- )
dup init 1 .line
1 ?do i next i 1+ .line loop ;</
This is a bit more efficient.
{{trans|C}}
<
cr dup 0
?do
Line 2,621 ⟶ 2,800:
;
13 PascTriangle</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Prints nothing for n<=0. Output formatting breaks down for n>20
<
CALL Print_Triangle(8)
Line 2,651 ⟶ 2,830:
END DO
END SUBROUTINE Print_Triangle</
=={{header|FreeBASIC}}==
<
Sub pascalTriangle(n As UInteger)
Line 2,690 ⟶ 2,869:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 2,712 ⟶ 2,891:
=={{header|Frink}}==
This version takes a little effort to automatically format the tree based upon the width of the largest numbers in the bottom row. It automatically calculates this easily using Frink's builtin function for efficiently calculating (even large) binomial coefficients with cached factorials and binary splitting.
<
pascal[rows] :=
{
Line 2,728 ⟶ 2,907:
pascal[10]
</syntaxhighlight>
{{out}}
Line 2,747 ⟶ 2,926:
=== Summing from Previous Rows ===
{{trans|Scala}}
<
def
pascal( 1 ) = [1]
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</
=== Combinations ===
{{trans|Haskell}}
<
def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</
=== Pascal's Triangle ===
<
width = max( map(a -> a.toString().length(), pascal(height)) )
Line 2,770 ⟶ 2,949:
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() )
triangle( 10 )</
{{out}}
Line 2,788 ⟶ 2,967:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Pascal%27s_triangle}}
'''Solution'''
[[File:Fōrmulæ - Pascal's triangle 01.png]]
'''Test case'''
[[File:Fōrmulæ - Pascal's triangle 02.png]]
[[File:Fōrmulæ - Pascal's triangle 03.png]]
=={{header|GAP}}==
<
local i, v;
v := [1];
Line 2,813 ⟶ 2,998:
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</
=={{header|Go}}==
No output for n < 1. Otherwise, output formatted left justified.
<syntaxhighlight lang="go">
package main
Line 2,860 ⟶ 3,045:
printTriangle(4)
}
</syntaxhighlight>
Output:
<pre>
Line 2,872 ⟶ 3,057:
=== Recursive ===
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution:
<
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</
However, this solution is horribly inefficient (O(''n''**2)). It slowly grinds to a halt on a reasonably powerful PC after about line 25 of the triangle.
Test program:
<
(1..count).each { n ->
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println ""
}</
{{out}}
Line 2,900 ⟶ 3,085:
=={{header|GW-BASIC}}==
<
20 FOR I=0 TO R-1
30 C=1
Line 2,908 ⟶ 3,093:
70 NEXT
80 PRINT
90 NEXT</
Output:
Line 2,930 ⟶ 3,115:
similar function
<
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</
Now we can shift a list and add it to itself, extending it by keeping
the ends:
<
extendWith f xs@(x:ys) = x : zapWith f xs ys</
And for the whole (infinite) triangle, we just iterate this operation,
starting with the first row:
<
For the first ''n'' rows, we just take the first ''n'' elements from this
list, as in
<
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</
A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind]
<
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])
-- returns the first n rows
pascal = iterate nextRow [1]</
Alternatively, using list comprehensions:
<
pascal :: [[Integer]]
pascal =
(1 : [ 0 | _ <- head pascal])
: [zipWith (+) (0:row) row | row <- pascal]
</syntaxhighlight>
<
*Pascal> take 5 <$> (take 5 $ triangle)
[[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]]
</syntaxhighlight>
With binomial coefficients:
<
binCoef n k = fac n `div` (fac k * fac (n - k))
pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred</
Example:
<
1
1 1
Line 2,992 ⟶ 3,177:
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</syntaxhighlight>
=={{header|HicEst}}==
<
SUBROUTINE Pascal(rows)
Line 3,009 ⟶ 3,194:
ENDDO
ENDDO
END</
=={{header|Icon}} and {{header|Unicon}}==
The code below is slightly modified from the library version of pascal which prints 0's to the full width of the carpet.
It also presents the data as an isoceles triangle.
<
procedure main(A)
Line 3,033 ⟶ 3,218:
write()
}
end</
{{libheader|Icon Programming Library}}
Line 3,059 ⟶ 3,244:
=={{header|IDL}}==
<
;n is the number of lines of the triangle to be displayed
r=[1]
Line 3,075 ⟶ 3,260:
print, r
End</
=={{header|IS-BASIC}}==
<
110 TEXT 80
120 LET ROW=12
Line 3,089 ⟶ 3,274:
190 NEXT
200 PRINT
210 NEXT</
{{out}}
Line 3,107 ⟶ 3,292:
=={{header|ivy}}==
<
op pascal N = transp (0 , iota N) o.! -1 , iota N
pascal 5
Line 3,116 ⟶ 3,301:
1 4 6 4 1 0
1 5 10 10 5 1
</syntaxhighlight>
=={{header|J}}==
<
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</
<
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</
<
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1</
However, multi-digit numbers take up additional space, which looks slightly odd. But we can work around that by adding additional padding and shifting the lines a bit more:
<syntaxhighlight lang=J> (|."_1~ 0-3*i.@-@#) ;@((<'%6d') sprintf each -.&0)"1 !~/~i.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
</syntaxhighlight>
Also... when we mix positive and negative numbers it stops being a triangle:
<syntaxhighlight lang=J> i:5
_5 _4 _3 _2 _1 0 1 2 3 4 5
!~/~i:5
1 0 0 0 0 1 _5 15 _35 70 _126
_4 1 0 0 0 1 _4 10 _20 35 _56
6 _3 1 0 0 1 _3 6 _10 15 _21
_4 3 _2 1 0 1 _2 3 _4 5 _6
1 _1 1 _1 1 1 _1 1 _1 1 _1
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 1 2 1 0 0 0
0 0 0 0 0 1 3 3 1 0 0
0 0 0 0 0 1 4 6 4 1 0
0 0 0 0 0 1 5 10 10 5 1
!/~i:5
1 _4 6 _4 1 0 0 0 0 0 0
0 1 _3 3 _1 0 0 0 0 0 0
0 0 1 _2 1 0 0 0 0 0 0
0 0 0 1 _1 0 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1
_5 _4 _3 _2 _1 0 1 2 3 4 5
15 10 6 3 1 0 0 1 3 6 10
_35 _20 _10 _4 _1 0 0 0 1 4 10
70 35 15 5 1 0 0 0 0 1 5
_126 _56 _21 _6 _1 0 0 0 0 0 1</syntaxhighlight>
See the [[Talk:Pascal's_triangle#J_Explanation|talk page]] for explanation of earlier version
Line 3,147 ⟶ 3,378:
===Summing from Previous Rows===
{{works with|Java|1.5+}}
<
...//class definition, etc.
public static void genPyrN(int rows){
Line 3,167 ⟶ 3,398:
System.out.println(thisRow);
}
}</
===Combinations===
This method is limited to 21 rows because of the limits of <tt>long</tt>. Calling <tt>pas</tt> with an argument of 22 or above will cause intermediate math to wrap around and give false answers.
<
public static void main(String[] args){
//usage
Line 3,197 ⟶ 3,428:
return ans;
}
}</
===Using arithmetic calculation of each row element ===
This method is limited to 30 rows because of the limits of integer calculations (probably when calculating the multiplication). If m is declared as long then 62 rows can be printed.
<
public class Pascal {
private static void printPascalLine (int n) {
Line 3,221 ⟶ 3,452:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 3,228 ⟶ 3,459:
{{works with|SpiderMonkey}}
{{works with|V8}}
<
function pascalTriangle (rows) {
Line 3,298 ⟶ 3,529:
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri.print(16);</
Output:
<pre>$ d8 pascal.js
Line 3,316 ⟶ 3,547:
====Functional====
{{Trans|Haskell}}
<
'use strict';
Line 3,417 ⟶ 3,648:
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n');
})(7);</
{{Out}}
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;"
Line 3,436 ⟶ 3,667:
|}
<
===ES6===
<
// ---------------- PASCAL'S TRIANGLE ----------------
// pascal :: Generator [[Int]]
Line 3,450 ⟶ 3,679:
iterate(
xs => zipWith(
[...xs, 0]
)
)([1]);
// ---------------------- TEST -----------------------
// main :: IO ()
const main = () =>
showPascal(
take(10)(
pascal()
)
);
// showPascal :: [[Int]] -> String
const showPascal = xs => {
const w = last(xs).join(" ").length;
return xs.map(
)
.join("\n");
};
//
//
const
// Size of space -> filler Char ->
margin = c.repeat(Math.floor(gap / 2)),
dust = c.repeat(gap % 2);
return `${margin}${s}${margin}${dust}`;
})() : s;
};
//
const
// applications of f to x.
function* (x) {
let v = x;
while (true) {
yield v;
v = f(v);
}
};
// last :: [a] -> a
Line 3,507 ⟶ 3,746:
0 < xs.length ? xs.slice(-1)[0] : undefined;
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take =
// The first n elements of a list,
// string of characters, or stream.
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) :
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}).flat();
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith =
// A list constructed by zipping with a
// custom function, rather than with the
// default tuple
xs =>
// MAIN ---
return main();
})();</
{{Out}}
<pre> 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</pre>
====Recursive====
<
const aux = n => {
if(n <= 1) return [1]
Line 3,582 ⟶ 3,805:
}
pascal(8)
</syntaxhighlight>
{{Out}}
<pre>
Line 3,595 ⟶ 3,818:
</pre>
====Recursive - memoized====
<
const aux = (() => {
const layers = [[1], [1]]
Line 3,612 ⟶ 3,835:
}
pascal(8)
</syntaxhighlight>
=={{header|jq}}==
Line 3,619 ⟶ 3,842:
each corresponding to a row of the Pascal triangle.
The implementation avoids any arithmetic except addition.
<
def pascal(n):
def _pascal: # input: the previous row
Line 3,629 ⟶ 3,852:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal
end;
if n <= 0 then empty else [1] | _pascal end ;</
'''Example''':
pascal(5)
{{ Out }}
<
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]</
'''Using recurse/1'''
Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function.
<
if n <= 0 then empty
else [1]
Line 3,651 ⟶ 3,874:
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1]
end)
end;</
=={{header|Julia}}==
Line 3,680 ⟶ 3,903:
Another solution using matrix exponentiation.
<syntaxhighlight lang="julia">
iround(x) = round(Int64, x)
Line 3,690 ⟶ 3,913:
end
</syntaxhighlight>
{{Out}}
Line 3,706 ⟶ 3,929:
Yet another solution using a static vector
<syntaxhighlight lang="julia">
function pascal(n)
(n<=0) && error("Pascal trinalge can not have zero or negative rows")
Line 3,722 ⟶ 3,945:
end
end
</syntaxhighlight>
{{Out}}
Line 3,739 ⟶ 3,962:
=={{header|K}}==
<syntaxhighlight lang="k">
pascal:{(x-1){+':x,0}\1}
pascal 6
Line 3,747 ⟶ 3,970:
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1)</
=={{header|Kotlin}}==
<
for (i in 0..rows - 1) {
for (j in 0..i)
Line 3,767 ⟶ 3,990:
}
fun main(args: Array<String>) = pas(args[0].toInt())</
=={{header|Lambdatalk}}==
<
1) Based on this expression of pascalian binomial:
Line 3,808 ⟶ 4,031:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
dim a$(n)
Line 3,829 ⟶ 4,052:
next i
end</
=={{header|Locomotive Basic}}==
<
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
Line 3,844 ⟶ 4,067:
100 PRINT
110 NEXT
120 RETURN</
Output:
Line 3,860 ⟶ 4,083:
=={{header|Logo}}==
<
if :n = 1 [output [1]]
localmake "a pascal :n-1
Line 3,866 ⟶ 4,089:
end
for [i 1 10] [print pascal :i]</
=={{header|Logtalk}}==
Our implementation will have an object <code>pascals</code> with work done in the method <code>triangle/2</code>. We will be caching results for time efficiency at the cost of space efficiency,and the <code>reset/0</code> method will flush that cache should it grow to be a problem. The resulting object looks like this:
<syntaxhighlight lang="logtalk">
:- object(pascals).
:- uses(integer, [plus/3, succ/2]).
:- public(reset/0).
reset :-
retractall(triangle_(_,_,_)).
:- private(triangle_/3).
:- dynamic(triangle_/3).
:- public(triangle/2).
triangle(N, Lines) :-
triangle(N, _, DiffLines),
difflist::as_list(DiffLines, Lines).
% Shortcut with cached value if it exists.
triangle(N, Line, DiffLines) :- triangle_(N, Line, DiffLines), !.
triangle(N, Line, DiffLines) :-
succ(N0, N),
triangle(N0, Line0, DiffLines0),
ZL = [0|Line0],
list::append(Line0, [0], ZR),
meta::map(plus, ZL, ZR, Line),
difflist::add(Line, DiffLines0, DiffLines),
asserta(triangle_(N, Line, DiffLines)).
triangle(1, [1], [[1]|X]-X).
:- end_object.
</syntaxhighlight>
{{Out}}
Using the SWI-Prolog back-end:
<pre>
?- logtalk_load([meta(loader), types(loader), pascals], [optimize(on)]).
% messages elided
true.
?- pascals::triangle(17, Ls), logtalk::print_message(information, user, Ls).
% - [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]
% - [1,10,45,120,210,252,210,120,45,10,1]
% - [1,11,55,165,330,462,462,330,165,55,11,1]
% - [1,12,66,220,495,792,924,792,495,220,66,12,1]
% - [1,13,78,286,715,1287,1716,1716,1287,715,286,78,13,1]
% - [1,14,91,364,1001,2002,3003,3432,3003,2002,1001,364,91,14,1]
% - [1,15,105,455,1365,3003,5005,6435,6435,5005,3003,1365,455,105,15,1]
% - [1,16,120,560,1820,4368,8008,11440,12870,11440,8008,4368,1820,560,120,16,1]
Ls = [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4|...], [1, 5, 10|...], [1, 6|...], [1|...], [...|...]|...].
?-
</pre>
=={{header|Lua}}==
<
function nextrow(t)
local ret = {}
Line 3,884 ⟶ 4,177:
end
end
</syntaxhighlight>
=={{header|Maple}}==
<
f(3);</
1
1 1
Line 3,895 ⟶ 4,188:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">n=7;
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]</
[[File:MmaPascal.png]]
A more graphical output with arrows would involve the plotting functionality with Graph[]:
<
pascal[nmax_] := Module[
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}],
Line 3,920 ⟶ 4,213:
];
pascal[nmax]
</syntaxhighlight>
=={{header|MATLAB}} / {{header|Octave}}==
A matrix containing the pascal triangle can be obtained this way:
<syntaxhighlight lang
<pre>>> pascal(6)
Line 3,940 ⟶ 4,233:
The binomial coefficients can be extracted from the Pascal triangle in this way:
<
<pre>>> for k=1:6,diag(rot90(pascal(k)))', end
Line 3,990 ⟶ 4,283:
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " "));
Line 4,001 ⟶ 4,295:
"1 4 6 4 1"
"1 5 10 10 5 1"
"1 6 15 20 15 6 1" */
</syntaxhighlight>
=={{header|Metafont}}==
Line 4,007 ⟶ 4,302:
(The formatting starts to be less clear when numbers start to have more than two digits)
<
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
Line 4,024 ⟶ 4,319:
pascaltr(4);
end</
=={{header|Microsoft Small Basic}}==
{{trans|GW-BASIC}}
<
TextWindow.Write("Number of rows? ")
r = TextWindow.ReadNumber()
Line 4,040 ⟶ 4,335:
TextWindow.WriteLine("")
EndFor
</syntaxhighlight>
Output:
Line 4,055 ⟶ 4,350:
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 4,087 ⟶ 4,382:
ReadChar
END Pascal.</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 4,130 ⟶ 4,425:
end n_
return fac /*calc. factorial*/
</syntaxhighlight>
{{out}}
<pre>
Line 4,150 ⟶ 4,445:
(pascal.nial)
<
combination is fork [ > [first, second], 0 first,
/ [factorial second, * [factorial - [second, first], factorial first] ]
]
pascal is transpose each combination cart [pass, pass] tell</
Using it
<
|pascal 5</
=={{header|Nim}}==
<
proc printPascalTriangle(n: int) =
Line 4,182 ⟶ 4,477:
echo line.center(lineLength)
printPascalTriangle(10)</
{{out}}
Line 4,197 ⟶ 4,492:
A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this:
<
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations
Line 4,209 ⟶ 4,504:
if row + 1 <= ROWS: printPascalTri(row + 1, result)
printPascalTri(1, triangle)</
{{out}}
Line 4,225 ⟶ 4,520:
=={{header|OCaml}}==
<
let next_row row =
List.map2 (+) ([0] @ row) (row @ [0])
Line 4,234 ⟶ 4,529:
if i = n then []
else row :: loop (i+1) (next_row row)
in loop 0 [1]</
=={{header|Octave}}==
<
for i = 0:h-1
for k = 0:h-i
Line 4,249 ⟶ 4,544:
endfunction
pascaltriangle(4);</
=={{header|Oforth}}==
Line 4,255 ⟶ 4,550:
No result if n <= 0
<
{{out}}
Line 4,273 ⟶ 4,568:
=={{header|Oz}}==
<
fun {NextLine Xs}
{List.zip 0|Xs {Append Xs [0]}
Line 4,303 ⟶ 4,598:
end
in
{PrintTriangle {Triangle 5}}</
For n = 0, prints nothing. For negative n, throws an exception.
=={{header|PARI/GP}}==
<
my(row=[],prevrow=[]);
for(x=1,N,
Line 4,322 ⟶ 4,617:
print(row);
);
}</
=={{header|Pascal}}==
<
procedure Pascal(r : Integer);
Line 4,345 ⟶ 4,640:
begin
Pascal(9)
end.</
Output:
<pre>% ./PascalsTriangle
Line 4,361 ⟶ 4,656:
=={{header|Perl}}==
These functions perform as requested in the task: they print out the first ''n'' lines. If ''n'' <= 0, they print nothing. The output is simple (no fancy formatting).
<
my $rows = shift;
my @next = (1);
Line 4,368 ⟶ 4,663:
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1);
}
}</
If you want more than 68 rows, then use either "use bigint" or "use Math::GMP qw/:constant/" inside the function to enable bigints. We can also use a binomial function which will expand to bigints if many rows are requested:
{{libheader|ntheory}}
<
sub pascal {
my $rows = shift;
Line 4,378 ⟶ 4,673:
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n";
}
}</
Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used:
<
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</
This triangle is build using the 'sock' or 'hockey stick' pattern property. Here I use the word tartaglia and not pascal because in my country it's called after the Niccolò Fontana, known also as Tartaglia. A full graphical implementation of 16 properties that can be found in the triangle can be found at mine [https://github.com/LorenzoTa/Tartaglia-s-triangle Tartaglia's triangle]
<
#!/usr/bin/perl
use strict;
Line 4,422 ⟶ 4,717:
my @third = tartaglia_row(5);
print "@third\n";
</syntaxhighlight>
which output
Line 4,439 ⟶ 4,734:
=={{header|Phix}}==
<!--<
<span style="color: #004080;">sequence</span> <span style="color: #000000;">row</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">13</span> <span style="color: #008080;">do</span>
Line 4,452 ⟶ 4,747:
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre style="font-size: 8px">
Line 4,473 ⟶ 4,768:
=={{header|PHP}}==
<
<?php
//Author Ivan Gavryshin @dcc0
Line 4,519 ⟶ 4,814:
?>
</
<
$c = 1;
$triangle = Array();
Line 4,542 ⟶ 4,837:
}
echo '<br>';
}</
1
1 1
Line 4,552 ⟶ 4,847:
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
=={{header|Picat}}==
<syntaxhighlight lang="picat">
%Author: Petar Kabashki
spatr([]) = [].
spatr([_|T]) = A, T = [] => A = [].
spatr([H|T]) = A, T = [TH|_] => A = [H+TH] ++ spatr(T).
table
patr(0) = [1].
patr(1) = [1, 1].
patr(N) = A, N > 1 => Apre = patr(N-1), A = [1] ++ spatr(Apre) ++ [1].
foreach(I in 0 .. 10) println(patr(I)) end.
</syntaxhighlight>
<syntaxhighlight lang="picat">
[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]
[1,10,45,120,210,252,210,120,45,10,1]
</syntaxhighlight>
=={{header|PicoLisp}}==
{{trans|C}}
<
(for I N
(space (* 2 (- N I)))
Line 4,562 ⟶ 4,885:
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(prinl) ) )</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;
Line 4,581 ⟶ 4,904:
t = u;
end;
</syntaxhighlight>
<syntaxhighlight lang="text">
1
1 1
Line 4,595 ⟶ 4,918:
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
</syntaxhighlight>
=={{header|Potion}}==
<
if (n < 1) :
1 print
Line 4,615 ⟶ 4,938:
.
printpascal(read number integer)</
=={{header|PowerShell}}==
<
$Infinity = 1
$NewNumbers = $null
Line 4,683 ⟶ 5,006:
$Infinity++
}
</syntaxhighlight>
Save the above code to a .ps1 script file and start it by calling its name and providing N.
Line 4,712 ⟶ 5,035:
=={{header|Prolog}}==
Difference-lists are used to make quick append.
<
pascal(1, N, [1], [[1]|X]-X, L),
maplist(my_format, L).
Line 4,748 ⟶ 5,071:
my_writef(X) :-
writef(' %5r', [X]).
</syntaxhighlight>
Output :
<
1
1 1
Line 4,769 ⟶ 5,092:
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
true.
</syntaxhighlight>
===An alternative===
The above use of difference lists is a really innovative example of late binding. Here's an alternative source which, while possibly not as efficient (or as short) as the previous example, may be a little easier to read and understand.
<
% Produce a pascal's triangle of depth N
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Line 4,800 ⟶ 5,123:
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row
write(Row), nl, fail.
pascal(_).</
*Output*:
<
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]</
=={{header|PureBasic}}==
<
For i= 0 To n
Line 4,827 ⟶ 5,150:
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
Input()</
=={{header|Python}}==
===Procedural===
<
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
Line 4,839 ⟶ 5,162:
print row
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1</
or by creating a scan function:
<
a = []
result = it
Line 4,858 ⟶ 5,181:
for row in pascal(4):
print(row)</
===Functional===
Line 4,865 ⟶ 5,188:
{{Works with|Python|3.7}}
<
from itertools import (accumulate, chain, islice)
Line 4,961 ⟶ 5,284:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre> 1
Line 4,979 ⟶ 5,302:
=={{header|q}}==
<syntaxhighlight lang="q">
pascal:{(x-1){0+':x,0}\1}
pascal 5
Line 4,987 ⟶ 5,310:
1 3 3 1
1 4 6 4 1
</syntaxhighlight>
=={{header|Qi}}==
{{trans|Haskell}}
<syntaxhighlight lang="qi">
(define iterate
_ _ 0 -> []
Line 5,001 ⟶ 5,324:
(define pascal
N -> (iterate next-row [1] N))
</syntaxhighlight>
=={{header|Quackery}}==
Line 5,007 ⟶ 5,330:
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1.
<
space swap of
swap join ] is justify ( $ n --> )
Line 5,028 ⟶ 5,351:
echoline ] is pascal ( n --> )
16 pascal</
{{out}}
Line 5,052 ⟶ 5,375:
=={{header|R}}==
{{trans|Octave}}
<
for(i in 0:(h-1)) {
s <- ""
Line 5,061 ⟶ 5,384:
print(s)
}
}</
Here's an R version:
<
lapply(0:h, function(i) choose(i, 0:i))
}</
=={{header|Racket}}==
Line 5,073 ⟶ 5,396:
Iterative version by summing rows up to <math>n</math>.
<
(define (pascal n)
Line 5,085 ⟶ 5,408:
</syntaxhighlight>
=={{header|Raku}}==
Line 5,093 ⟶ 5,416:
The following routine returns a lazy list of lines using the sequence operator (<tt>...</tt>). With a lazy result you need not tell the routine how many you want; you can just use a slice subscript to get the first N lines:
<syntaxhighlight lang="raku"
[1], { [0, |$_ Z+ |$_, 0] } ... *
}
.say for pascal[^10];</
One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant. Here we use the <tt>@</tt> sigil to indicate that the sequence should cache its values for reuse, and use an explicit parameter <tt>$prev</tt> for variety:
<syntaxhighlight lang="raku"
.say for @pascal[^10];</
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
Line 5,111 ⟶ 5,434:
{{trans|Haskell}}
<syntaxhighlight lang="raku"
multi sub pascal (Int $n where 2..*) {
my @rows = pascal $n - 1;
Line 5,117 ⟶ 5,440:
}
.say for pascal 10;</
Non-positive inputs throw a multiple-dispatch error.
Line 5,124 ⟶ 5,447:
{{trans|Perl}}
<syntaxhighlight lang="raku"
say my @last = 1;
for 1 .. $n - 1 -> $row {
Line 5,132 ⟶ 5,455:
}
pascal 10;</
Non-positive inputs throw a type check error.
Line 5,161 ⟶ 5,484:
RapidQ does not require simple variables to be declared before use.
<
INPUT "Number of rows: "; nrows
Line 5,172 ⟶ 5,495:
NEXT i
PRINT
NEXT row</
===Using binary coefficients===
{{trans|BASIC}}
<
FOR row = 0 TO nrows-1
c = 1
Line 5,185 ⟶ 5,508:
NEXT i
PRINT
NEXT row</
=={{header|Red}}==
<
pascal-triangle: function [
n [ integer! ] "number of rows"
Line 5,201 ⟶ 5,524:
row: left + right
]
]</
Output:
<pre>
Line 5,215 ⟶ 5,538:
=={{header|Retro}}==
<
: pascalTriangle
cr dup
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
;
13 pascalTriangle</
=={{header|REXX}}==
Line 5,237 ⟶ 5,560:
:::* Tartaglia's triangle
:::* Yang Hui's triangle
<
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn . /*obtain the optional argument from CL.*/
Line 5,260 ⟶ 5,583:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</
{{out|output|text= when using the input of: <tt> 11 </tt>}}
<pre>
Line 5,304 ⟶ 5,627:
=={{header|Ring}}==
<
row = 5
for i = 0 to row - 1
Line 5,315 ⟶ 5,638:
see nl
next
</syntaxhighlight>
Output:
<pre>
Line 5,324 ⟶ 5,647:
1 4 6 4 1
</pre>
=={{header|RPL}}==
« 0 SWAP '''FOR''' n
"" 0 n '''FOR''' p
n p COMB + " " +
'''NEXT'''
n 1 + DISP
'''NEXT'''
7 FREEZE
» '<span style="color:blue">PASCAL</span>' STO
8 <span style="color:blue">PASCAL</span>
{{out}}
<pre>
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 …
</pre>
RPL screens are limited to 22 characters.
=={{header|Ruby}}==
<
raise ArgumentError, "must be positive." if n < 1
yield ar = [1]
Line 5,335 ⟶ 5,683:
end
pascal(8){|row| puts row.join(" ").center(20)}</
{{out}}
<pre>
Line 5,350 ⟶ 5,698:
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know):
<
def pascal(n) n.times.inject([1]) {|x,_| next_row x } end
8.times{|i| p pascal(i)}</
{{out}}
<pre>
Line 5,368 ⟶ 5,716:
=={{header|Run BASIC}}==
<
for i = 0 to r - 1
c = 1
Line 5,377 ⟶ 5,725:
next
print
next</
<pre>Number of rows? ?5
1
Line 5,387 ⟶ 5,735:
=={{header|Rust}}==
{{trans|C}}
<
fn pascal_triangle(n: u64)
{
Line 5,403 ⟶ 5,751:
}
}
</syntaxhighlight>
=={{header|Scala}}==
===Functional solutions===
====Summing: Recursive row definition====
<
def tri(row: Int): List[Int] =
row match {
case 1 => List(1)
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1
}</
Function to pretty print n rows:
<
prettyTri(5)</
{{Out}}
<pre> 1
Line 5,425 ⟶ 5,773:
1 4 6 4 1</pre>
====Summing: Scala Stream (Recursive & Memoization)====
<
def pascalTriangle(): Stream[Vector[Int]] =
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1)
Line 5,434 ⟶ 5,782:
println("Pascal's Triangle")
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line"))
}</
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/8VqiX0P/1 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/c3dDWMCcT3eoydy6QJcWCw Scastie (JVM)].
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(map + (cons 0 row) (append row '(0))))
Line 5,448 ⟶ 5,796:
(triangle (list 1) 5)
</syntaxhighlight>
Output:
<syntaxhighlight lang="text">((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</
=={{header|Seed7}}==
<
const proc: main is func
Line 5,474 ⟶ 5,822:
writeln;
end for;
end func;</
=={{header|Sidef}}==
<
var row = [1]
{ | n|
Line 5,485 ⟶ 5,833:
}
pascal(10)</
=={{header|Stata}}==
First, a few ways to compute a "Pascal matrix". With the first, the upper triangle is made of missing values (zeros with the other two).
<
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
}
Line 5,515 ⟶ 5,863:
}
return(s)
}</
Now print the Pascal triangle.
<
a = pascal1(n)
for (i=1; i<=n; i++) {
Line 5,534 ⟶ 5,882:
1 2 1
1 3 3 1
1 4 6 4 1</
=={{header|Swift}}==
<
if n==1{
let a=[1]
Line 5,559 ⟶ 5,907:
}
let waste = pascal(n:10)
</syntaxhighlight>
=={{header|Tcl}}==
===Summing from Previous Rows===
<
if {$n < 1} {error "undefined behaviour for n < 1"}
set row [list 1]
Line 5,580 ⟶ 5,928:
}
puts [join [pascal_iterative 6] \n]</
<pre>1
1 1
Line 5,589 ⟶ 5,937:
===Using binary coefficients===
{{trans|BASIC}}
<
if {$n < 1} {error "undefined behaviour for n < 1"}
for {set i 0} {$i < $n} {incr i} {
Line 5,603 ⟶ 5,951:
}
puts [join [pascal_coefficients 6] \n]</
===Combinations===
{{trans|Java}}
Thanks to Tcl 8.5's arbitrary precision integer arithmetic, this solution is not limited to a couple of dozen rows. Uses a caching factorial calculator to improve performance.
<
proc pascal_combinations n {
Line 5,641 ⟶ 5,989:
}
puts [join [pascal_combinations 6] \n]</
===Comparing Performance===
<
puts "calculate $n rows:"
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} {
puts "$proc: [time [list $proc $n] 100]"
}</
{{Out}}
<pre>calculate 100 rows:
Line 5,657 ⟶ 6,005:
=={{header|TI-83 BASIC}}==
===Using Addition of Previous Rows===
<
:Lbl IN
:ClrHome
Line 5,673 ⟶ 6,021:
:End
:End
:[A]</
===Using nCr Function===
<
:Lbl IN
:ClrHome
Line 5,687 ⟶ 6,035:
:End
:End
:[A]</
=={{header|Turing}}==
<
for i : 0 .. n
var c := 1
Line 5,702 ⟶ 6,050:
end pascal
pascal(5)</
Output:
Line 5,711 ⟶ 6,059:
1 4 6 4 1
1 5 10 10 5 1
== {{header|TypeScript}} ==
{{trans|XPL0}}
<syntaxhighlight lang="javascript">// Pascal's triangle
function pascal(n: number): void {
// Display the first n rows of Pascal's triangle
// if n<=0 then nothing is displayed
var ld: number[] = new Array(40); // Old
var nw: number[] = new Array(40); // New
for (var row = 0; row < n; row++) {
nw[0] = 1;
for (var i = 1; i <= row; i++)
nw[i] = ld[i - 1] + ld[i];
process.stdout.write(" ".repeat((n - row - 1) * 2));
for (var i = 0; i <= row; i++) {
if (nw[i] < 100)
process.stdout.write(" ");
process.stdout.write(nw[i].toString());
if (nw[i] < 10)
process.stdout.write(" ");
process.stdout.write(" ");
}
nw[row + 1] = 0;
// We do not copy data from nw to ld
// but we work with references.
var tmp = ld;
ld = nw;
nw = tmp;
console.log();
}
}
pascal(13);
</syntaxhighlight>
{{out}}
<pre>
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
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
</pre>
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">Input "Number Of Rows: "; N
@(1) = 1
Print Tab((N+1)*3);"1"
Line 5,726 ⟶ 6,125:
Print
End</
Output:
<pre>Number Of Rows: 10
Line 5,746 ⟶ 6,145:
{{works with|Bourne Again SHell}}
Any n <= 1 will print the "1" row.
<
pascal() {
local -i n=${1:-1}
Line 5,763 ⟶ 6,162:
fi
}
pascal "$1"</
=={{header|Ursala}}==
Zero maps to the empty list. Negatives are inexpressible.
This solution uses a library function for binomial coefficients.
<
#import nat
pascal = choose**ziDS+ iota*t+ iota+ successor</
This solution uses direct summation. The algorithm is to
insert zero at the head of a list (initially the unit list <1>), zip it with its reversal,
map the sum over the list of pairs, iterate n times, and return the trace.
<
#import nat
pascal "n" = (next"n" sum*NiCixp) <1></
test program:
<
example = pascal 10</
{{Out}}
<pre><
Line 5,797 ⟶ 6,196:
=={{header|VBA}}==
<
Private Sub pascal_triangle(n As Integer)
Dim odd() As String
Line 5,826 ⟶ 6,225:
Public Sub main()
pascal_triangle 13
End Sub</
<pre> 1
1 1
Line 5,843 ⟶ 6,242:
=={{header|VBScript}}==
Derived from the BASIC version.
<
Function Pascal_Triangle(n)
Dim values(100)
Line 5,856 ⟶ 6,255:
WScript.StdOut.WriteLine
Next
End Function</
{{out}}
Invoke from a command line.
Line 5,877 ⟶ 6,276:
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2.
<
#0=0; #1=1
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1)
Line 5,889 ⟶ 6,288:
}
Ins_Newline
}</
===Using binary coefficients===
{{trans|BASIC}}
<
for (#2 = 0; #2 < #1; #2++) {
#3 = 1
Line 5,902 ⟶ 6,301:
}
Ins_Newline
}</
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<
'Pascal's triangle
Const m = 11
Line 5,923 ⟶ 6,322:
Next n
MsgBox ss, , "Pascal's triangle"
End Sub 'pascaltriangle</
{{out}}
<pre>
Line 5,941 ⟶ 6,340:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 5,982 ⟶ 6,381:
End Sub
End Module</
{{out}}
<pre> 1
Line 6,007 ⟶ 6,406:
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|
<
import "./math" for Int
var pascalTriangle = Fn.new { |n|
Line 6,027 ⟶ 6,415:
System.write(" " * (n-i-1))
for (j in 0..i) {
Fmt.write("$3d ",
}
System.print()
Line 6,033 ⟶ 6,421:
}
pascalTriangle.call(13)</
{{out}}
Line 6,056 ⟶ 6,444:
{{works with|Windows}}
<b>uses:</b> io.inc - Macro library from SASM
<
%include "io.inc"
Line 6,135 ⟶ 6,523:
pop ecx
ret
</syntaxhighlight>
{{out}}
<pre>
Line 6,150 ⟶ 6,538:
{{trans|GW-BASIC}}
{{works with|Windows XBasic}}
<
PROGRAM "pascal"
VERSION "0.0001"
Line 6,168 ⟶ 6,556:
END FUNCTION
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 6,182 ⟶ 6,570:
=={{header|XPL0}}==
<
proc Pascal(N); \Display the first N rows of Pascal's triangle
Line 6,203 ⟶ 6,591:
];
Pascal(13)</
{{Out}}
Line 6,224 ⟶ 6,612:
=={{header|zkl}}==
{{trans|C}}
<
foreach i in (n){
c := 1;
Line 6,236 ⟶ 6,624:
}
pascalTriangle(8);</
{{out}}
<pre>
Line 6,252 ⟶ 6,640:
In edit mode insert:
<
15 IF n<1 THEN GO TO 210
20 DIM c(n)
Line 6,275 ⟶ 6,663:
180 LET c(i)=d(i)
190 NEXT i
200 NEXT r</
Then in command mode (basically don't put a number in front):
<syntaxhighlight lang
{{out}}
<pre>
|