Pascal's triangle: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 42: | Line 42: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F pascal(n) |
||
V row = [1] |
V row = [1] |
||
V k = [0] |
V k = [0] |
||
Line 49: | Line 49: | ||
row = zip(row [+] k, k [+] row).map((l, r) -> l + r) |
row = zip(row [+] k, k [+] row).map((l, r) -> l + r) |
||
pascal(7)</ |
pascal(7)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 64: | Line 64: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
{{trans|PL/I}} |
{{trans|PL/I}} |
||
< |
<syntaxhighlight lang="360asm">* Pascal's triangle 25/10/2015 |
||
PASCAL CSECT |
PASCAL CSECT |
||
USING PASCAL,R15 set base register |
USING PASCAL,R15 set base register |
||
Line 101: | Line 101: | ||
XD DS CL12 temp |
XD DS CL12 temp |
||
YREGS |
YREGS |
||
END PASCAL</ |
END PASCAL</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 119: | Line 119: | ||
=={{header|8th}}== |
=={{header|8th}}== |
||
One way, using array operations: |
One way, using array operations: |
||
< |
<syntaxhighlight lang="forth"> |
||
\ print the array |
\ print the array |
||
: .arr \ a -- a |
: .arr \ a -- a |
||
Line 135: | Line 135: | ||
\ print the first 16 rows: |
\ print the first 16 rows: |
||
[1] ' pasc 16 times |
[1] ' pasc 16 times |
||
</syntaxhighlight> |
|||
</lang> |
|||
Another way, using the relation between element 'n' and element 'n-1' in a row: |
Another way, using the relation between element 'n' and element 'n-1' in a row: |
||
< |
<syntaxhighlight lang="forth"> |
||
: ratio \ m n -- num denom |
: ratio \ m n -- num denom |
||
tuck n:- n:1+ swap ; |
tuck n:- n:1+ swap ; |
||
Line 160: | Line 160: | ||
15 pasc |
15 pasc |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">PROC Main() |
||
BYTE count=[10],row,item |
BYTE count=[10],row,item |
||
CHAR ARRAY s(5) |
CHAR ARRAY s(5) |
||
Line 180: | Line 180: | ||
PutE() |
PutE() |
||
OD |
OD |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal's_triangle.png Screenshot from Atari 8-bit computer] |
||
Line 200: | 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]] |
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]] |
||
< |
<syntaxhighlight lang="ada">package Pascal is |
||
type Row is array (Natural range <>) of Natural; |
type Row is array (Natural range <>) of Natural; |
||
Line 210: | Line 210: | ||
function Next_Row(R: Row) return Row; |
function Next_Row(R: Row) return Row; |
||
end Pascal;</ |
end Pascal;</syntaxhighlight> |
||
The implementation of that auxiliary package "Pascal": |
The implementation of that auxiliary package "Pascal": |
||
< |
<syntaxhighlight lang="ada">package body Pascal is |
||
function First_Row(Max_Length: Positive) return Row is |
function First_Row(Max_Length: Positive) return Row is |
||
Line 239: | Line 239: | ||
end Length; |
end Length; |
||
end Pascal;</ |
end Pascal;</syntaxhighlight> |
||
The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line. |
The main program, using "Pascal". It prints the desired number of rows. The number is read from the command line. |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal; |
||
procedure Triangle is |
procedure Triangle is |
||
Line 260: | Line 260: | ||
Row := Next_Row(Row); |
Row := Next_Row(Row); |
||
end loop; |
end loop; |
||
end Triangle;</ |
end Triangle;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 279: | Line 279: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">PRIO MINLWB = 8, MAXUPB = 8; |
||
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b), |
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); |
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b); |
||
Line 297: | Line 297: | ||
# WHILE # i < stop DO |
# WHILE # i < stop DO |
||
row := row[AT 1] + row[AT 2] |
row := row[AT 1] + row[AT 2] |
||
OD</ |
OD</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 312: | Line 312: | ||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% prints the first n lines of Pascal's triangle lines % |
% prints the first n lines of Pascal's triangle lines % |
||
% if n is <= 0, no output is produced % |
% if n is <= 0, no output is produced % |
||
Line 330: | Line 330: | ||
printPascalTriangle( 8 ) |
printPascalTriangle( 8 ) |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 346: | Line 346: | ||
Pascal' s triangle of order ⍵ |
Pascal' s triangle of order ⍵ |
||
=== Dyalog APL === |
=== Dyalog APL === |
||
< |
<syntaxhighlight lang="apl"> |
||
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵} |
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵} |
||
</syntaxhighlight> |
|||
</lang> |
|||
example |
example |
||
< |
<syntaxhighlight lang="apl"> |
||
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5 |
{⍕0~¨⍨(-⌽A)⌽↑,/0,¨⍉A∘.!A←0,⍳⍵}5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
Line 367: | Line 367: | ||
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently: |
GNU APL doesn't allow multiple statements within lambdas so the solution is phrased differently: |
||
< |
<syntaxhighlight lang="apl"> |
||
{{⍉⍵∘.!⍵} 0,⍳⍵} |
{{⍉⍵∘.!⍵} 0,⍳⍵} |
||
</syntaxhighlight> |
|||
</lang> |
|||
example |
example |
||
< |
<syntaxhighlight lang="apl"> |
||
{{⍉⍵∘.!⍵} 0,⍳⍵} 3 |
{{⍉⍵∘.!⍵} 0,⍳⍵} 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> |
<pre> |
||
Line 386: | Line 386: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
Drawing n rows from a generator: |
Drawing n rows from a generator: |
||
< |
<syntaxhighlight lang="applescript">-------------------- PASCAL'S TRIANGLE ------------------- |
||
-- pascal :: Generator [[Int]] |
-- pascal :: Generator [[Int]] |
||
Line 598: | Line 598: | ||
return lst |
return lst |
||
end tell |
end tell |
||
end zipWith</ |
end zipWith</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 610: | Line 610: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
{{trans|Nim}} |
{{trans|Nim}} |
||
< |
<syntaxhighlight lang="rebol">pascalTriangle: function [n][ |
||
triangle: new [[1]] |
triangle: new [[1]] |
||
Line 622: | Line 622: | ||
loop pascalTriangle 10 'row [ |
loop pascalTriangle 10 'row [ |
||
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60 |
print pad.center join.with: " " map to [:string] row 'x -> pad.center x 5 60 |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 639: | Line 639: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion] |
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?p=276617#276617 discussion] |
||
< |
<syntaxhighlight lang="autohotkey">n := 8, p0 := "1" ; 1+n rows of Pascal's triangle |
||
Loop %n% { |
Loop %n% { |
||
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1 |
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1 |
||
Line 660: | Line 660: | ||
GuiClose: |
GuiClose: |
||
ExitApp</ |
ExitApp</syntaxhighlight> |
||
Alternate {{works with|AutoHotkey L}} |
Alternate {{works with|AutoHotkey L}} |
||
< |
<syntaxhighlight lang="autohotkey">Msgbox % format(pascalstriangle()) |
||
Return |
Return |
||
Line 687: | Line 687: | ||
: p[row-1, col]) |
: p[row-1, col]) |
||
Return p |
Return p |
||
}</ |
}</syntaxhighlight> |
||
n <= 0 returns empty |
n <= 0 returns empty |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'</syntaxhighlight> |
||
{{Out}}<pre> |
{{Out}}<pre> |
||
1 |
1 |
||
Line 714: | Line 714: | ||
If the user enters value less than 1, the first row is still always displayed. |
If the user enters value less than 1, the first row is still always displayed. |
||
< |
<syntaxhighlight lang="freebasic">DIM i AS Integer |
||
DIM row AS Integer |
DIM row AS Integer |
||
DIM nrows AS Integer |
DIM nrows AS Integer |
||
Line 729: | Line 729: | ||
NEXT i |
NEXT i |
||
PRINT |
PRINT |
||
NEXT row</ |
NEXT row</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Based from the Fortran Code. |
Based from the Fortran Code. |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 771: | Line 771: | ||
for /l %%A in (1,1,%numspaces%) do set "space=!space! " |
for /l %%A in (1,1,%numspaces%) do set "space=!space! " |
||
goto :EOF |
goto :EOF |
||
::/The Functions.</ |
::/The Functions.</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 792: | Line 792: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> nrows% = 10 |
||
colwidth% = 4 |
colwidth% = 4 |
||
Line 804: | Line 804: | ||
NEXT |
NEXT |
||
PRINT |
PRINT |
||
NEXT row%</ |
NEXT row%</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 818: | Line 818: | ||
=={{header|BCPL}}== |
=={{header|BCPL}}== |
||
< |
<syntaxhighlight lang="bcpl">get "libhdr" |
||
let pascal(n) be |
let pascal(n) be |
||
Line 831: | Line 831: | ||
$) |
$) |
||
let start() be pascal(8)</ |
let start() be pascal(8)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 843: | Line 843: | ||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
< |
<syntaxhighlight lang="befunge">0" :swor fo rebmuN">:#,_&> 55+, v |
||
v01*p00-1:g00.:<1p011p00:\-1_v#:< |
v01*p00-1:g00.:<1p011p00:\-1_v#:< |
||
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</ |
>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Number of rows: 10 |
<pre>Number of rows: 10 |
||
Line 864: | Line 864: | ||
Displays n rows. |
Displays n rows. |
||
< |
<syntaxhighlight lang="bqn">Pascal ← {(0⊸∾+∾⟜0)⍟(↕𝕩)⋈1} |
||
•Show¨Pascal 6</ |
•Show¨Pascal 6</syntaxhighlight> |
||
<lang>⟨ 1 ⟩ |
<syntaxhighlight lang="text">⟨ 1 ⟩ |
||
⟨ 1 1 ⟩ |
⟨ 1 1 ⟩ |
||
⟨ 1 2 1 ⟩ |
⟨ 1 2 1 ⟩ |
||
⟨ 1 3 3 1 ⟩ |
⟨ 1 3 3 1 ⟩ |
||
⟨ 1 4 6 4 1 ⟩ |
⟨ 1 4 6 4 1 ⟩ |
||
⟨ 1 5 10 10 5 1 ⟩</ |
⟨ 1 5 10 10 5 1 ⟩</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( out$"Number of rows? " |
||
& get':?R |
& get':?R |
||
& -1:?I |
& -1:?I |
||
Line 892: | Line 892: | ||
) |
) |
||
& |
& |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Number of rows? |
<pre>Number of rows? |
||
Line 906: | Line 906: | ||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S |
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S |
||
1 |
1 |
||
Line 925: | Line 925: | ||
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 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 |
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
Line 931: | Line 931: | ||
{{trans|Fortran}} |
{{trans|Fortran}} |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
void pascaltriangle(unsigned int n) |
void pascaltriangle(unsigned int n) |
||
Line 952: | Line 952: | ||
pascaltriangle(8); |
pascaltriangle(8); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
===Recursive=== |
===Recursive=== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#define D 32 |
#define D 32 |
||
Line 972: | Line 972: | ||
int x[D] = {0, 1, 0}, y[D] = {0}; |
int x[D] = {0, 1, 0}, y[D] = {0}; |
||
return pascals(x, y, 0); |
return pascals(x, y, 0); |
||
}</ |
}</syntaxhighlight> |
||
===Adding previous row values=== |
===Adding previous row values=== |
||
< |
<syntaxhighlight lang="c">void triangleC(int nRows) { |
||
if (nRows <= 0) return; |
if (nRows <= 0) return; |
||
int *prevRow = NULL; |
int *prevRow = NULL; |
||
Line 991: | Line 991: | ||
} |
} |
||
free(prevRow); |
free(prevRow); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
Line 997: | Line 997: | ||
Produces no output when n is less than or equal to zero. |
Produces no output when n is less than or equal to zero. |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
namespace RosettaCode { |
namespace RosettaCode { |
||
Line 1,021: | Line 1,021: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Arbitrarily large numbers (BigInteger), arbitrary row selection=== |
===Arbitrarily large numbers (BigInteger), arbitrary row selection=== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Linq; |
using System.Linq; |
||
using System.Numerics; |
using System.Numerics; |
||
Line 1,071: | Line 1,071: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="csharp">static void Main() |
||
{ |
{ |
||
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20); |
IEnumerable<BigInteger[]> triangle = PascalsTriangle.GetTriangle(20); |
||
string output = PascalsTriangle.FormatTriangleString(triangle) |
string output = PascalsTriangle.FormatTriangleString(triangle) |
||
Console.WriteLine(output); |
Console.WriteLine(output); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,106: | Line 1,106: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <algorithm> |
#include <algorithm> |
||
#include<cstdio> |
#include<cstdio> |
||
Line 1,185: | Line 1,185: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===C++11 (with dynamic and semi-static vectors)=== |
===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. |
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. |
||
< |
<syntaxhighlight lang="cpp">// Compile with -std=c++11 |
||
#include<iostream> |
#include<iostream> |
||
#include<vector> |
#include<vector> |
||
Line 1,274: | Line 1,274: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===C++11 (with a class) === |
===C++11 (with a class) === |
||
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented. |
A full fledged example with a class definition and methods to retrieve data, worthy of the title object-oriented. |
||
< |
<syntaxhighlight lang="cpp">// Compile with -std=c++11 |
||
#include<iostream> |
#include<iostream> |
||
#include<vector> |
#include<vector> |
||
Line 1,358: | Line 1,358: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{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). |
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). |
||
< |
<syntaxhighlight lang="lisp">(defn pascal [n] |
||
(let [newrow (fn newrow [lst ret] |
(let [newrow (fn newrow [lst ret] |
||
(if lst |
(if lst |
||
Line 1,374: | Line 1,374: | ||
(recur (dec n) (conj (newrow lst []) 1)))))] |
(recur (dec n) (conj (newrow lst []) 1)))))] |
||
(genrow n [1]))) |
(genrow n [1]))) |
||
(pascal 4)</ |
(pascal 4)</syntaxhighlight> |
||
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: |
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: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defn nextrow [row] |
(defn nextrow [row] |
||
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] ))) |
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] ))) |
||
Line 1,385: | Line 1,385: | ||
(doseq [row triangle] |
(doseq [row triangle] |
||
(println row)))) |
(println row)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
The ''assert'' form causes the ''pascal'' function to throw an exception unless the argument is (integral and) positive. |
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 |
Here's a third version using the ''iterate'' function |
||
< |
<syntaxhighlight lang="lisp"> |
||
(def pascal |
(def pascal |
||
(iterate |
(iterate |
||
Line 1,397: | Line 1,397: | ||
(map (partial apply +) ,,,))) |
(map (partial apply +) ,,,))) |
||
[1])) |
[1])) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Another short version which returns an infinite pascal triangle as a list, using the iterate function. |
Another short version which returns an infinite pascal triangle as a list, using the iterate function. |
||
< |
<syntaxhighlight lang="lisp"> |
||
(def pascal |
(def pascal |
||
(iterate #(concat [1] |
(iterate #(concat [1] |
||
Line 1,407: | Line 1,407: | ||
[1]) |
[1]) |
||
[1])) |
[1])) |
||
</syntaxhighlight> |
|||
</lang> |
|||
One can then get the first n rows using the take function |
One can then get the first n rows using the take function |
||
< |
<syntaxhighlight lang="lisp"> |
||
(take 10 pascal) ; returns a list of the first 10 pascal rows |
(take 10 pascal) ; returns a list of the first 10 pascal rows |
||
</syntaxhighlight> |
|||
</lang> |
|||
Also, one can retrieve the nth row using the nth function |
Also, one can retrieve the nth row using the nth function |
||
< |
<syntaxhighlight lang="lisp"> |
||
(nth pascal 10) ;returns the nth row |
(nth pascal 10) ;returns the nth row |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients. |
This version assumes n is an integer and n >= 1. It efficiently computes binomial coefficients. |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
pascal = (n) -> |
pascal = (n) -> |
||
width = 6 |
width = 6 |
||
Line 1,453: | Line 1,453: | ||
pascal(7) |
pascal(7) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 1,468: | Line 1,468: | ||
=={{header|Commodore BASIC}}== |
=={{header|Commodore BASIC}}== |
||
< |
<syntaxhighlight lang="basic">10 INPUT "HOW MANY";N |
||
20 IF N<1 THEN END |
20 IF N<1 THEN END |
||
30 DIM C(N) |
30 DIM C(N) |
||
Line 1,491: | Line 1,491: | ||
220 C(I)=D(I) |
220 C(I)=D(I) |
||
230 NEXT I |
230 NEXT I |
||
240 NEXT J</ |
240 NEXT J</syntaxhighlight> |
||
Output: |
Output: |
||
<lang>RUN |
<syntaxhighlight lang="text">RUN |
||
HOW MANY? 8 |
HOW MANY? 8 |
||
1 |
1 |
||
Line 1,506: | Line 1,506: | ||
1 8 28 56 70 56 28 8 1 |
1 8 28 56 70 56 28 8 1 |
||
READY. |
READY. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
To evaluate, call (pascal n). For n < 1, it simply returns nil. |
To evaluate, call (pascal n). For n < 1, it simply returns nil. |
||
< |
<syntaxhighlight lang="lisp">(defun pascal (n) |
||
(genrow n '(1))) |
(genrow n '(1))) |
||
Line 1,523: | Line 1,523: | ||
'(1) |
'(1) |
||
(cons (+ (first l) (second l)) |
(cons (+ (first l) (second l)) |
||
(newrow (rest l)))))</ |
(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))''. |
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))''. |
||
< |
<syntaxhighlight lang="lisp">(defun pascal-next-row (a) |
||
(loop :for q :in a |
(loop :for q :in a |
||
:and p = 0 :then q |
:and p = 0 :then q |
||
Line 1,538: | Line 1,538: | ||
(loop :for a = (list 1) :then (pascal-next-row a) |
(loop :for a = (list 1) :then (pascal-next-row a) |
||
:repeat n |
:repeat n |
||
:collect a))</ |
:collect a))</syntaxhighlight> |
||
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-triangle function computes and uses the length of the printed last row to decide how wide the triangle should be. |
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-triangle function computes and uses the length of the printed last row to decide how wide the triangle should be. |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun next-pascal-triangle-row (list) |
(defun next-pascal-triangle-row (list) |
||
`(1 |
`(1 |
||
Line 1,559: | Line 1,559: | ||
(format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" max-row-length) |
(format nil "~~{~~~D:@<~~{~~A ~~}~~>~~%~~}" max-row-length) |
||
triangle))) |
triangle))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
For example: |
For example: |
||
<lang |
<syntaxhighlight lang="lisp">(print-pascal-triangle 4)</syntaxhighlight> |
||
<lang> |
<syntaxhighlight lang="text"> |
||
1 |
1 |
||
1 1 |
1 1 |
||
1 2 1 |
1 2 1 |
||
1 3 3 1 |
1 3 3 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
<lang |
<syntaxhighlight lang="lisp">(print-pascal-triangle 8)</syntaxhighlight> |
||
<lang> |
<syntaxhighlight lang="text"> |
||
1 |
1 |
||
1 1 |
1 1 |
||
Line 1,580: | Line 1,580: | ||
1 6 15 20 15 6 1 |
1 6 15 20 15 6 1 |
||
1 7 21 35 35 21 7 1 |
1 7 21 35 35 21 7 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
{{Works with|BlackBox Component Builder}} |
{{Works with|BlackBox Component Builder}} |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE PascalTriangle; |
MODULE PascalTriangle; |
||
IMPORT StdLog, DevCommanders, TextMappers; |
IMPORT StdLog, DevCommanders, TextMappers; |
||
Line 1,656: | Line 1,656: | ||
END PascalTriangle. |
END PascalTriangle. |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre> |
<pre>Execute: ^Q PascalTriangle.Do 0 1 2 3 4 5 6 7 8 9 10 11 12~</pre> |
||
{{out}} |
{{out}} |
||
Line 1,677: | Line 1,677: | ||
=={{header|D}}== |
=={{header|D}}== |
||
===Less functional Version=== |
===Less functional Version=== |
||
< |
<syntaxhighlight lang="d">int[][] pascalsTriangle(in int rows) pure nothrow { |
||
auto tri = new int[][rows]; |
auto tri = new int[][rows]; |
||
foreach (r; 0 .. rows) { |
foreach (r; 0 .. rows) { |
||
Line 1,701: | Line 1,701: | ||
[1, 8, 28, 56, 70, 56, 28, 8, 1], |
[1, 8, 28, 56, 70, 56, 28, 8, 1], |
||
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]); |
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]); |
||
}</ |
}</syntaxhighlight> |
||
===More functional Version=== |
===More functional Version=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range; |
||
auto pascal() pure nothrow { |
auto pascal() pure nothrow { |
||
Line 1,713: | Line 1,713: | ||
void main() { |
void main() { |
||
pascal.take(5).writeln; |
pascal.take(5).writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre> |
<pre>[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]</pre> |
||
Line 1,721: | Line 1,721: | ||
Their difference are the initial line and the operation that act on the line element to produce next line. |
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). |
The following is a generic pascal's triangle implementation for positive number of lines output (n). |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.string, std.array, std.format; |
||
string Pascal(alias dg, T, T initValue)(int n) { |
string Pascal(alias dg, T, T initValue)(int n) { |
||
Line 1,762: | Line 1,762: | ||
foreach (i; [16]) |
foreach (i; [16]) |
||
writef(sierpinski(i)); |
writef(sierpinski(i)); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 1,797: | Line 1,797: | ||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang="dart"> |
||
import 'dart:io'; |
import 'dart:io'; |
||
Line 1,840: | Line 1,840: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang="delphi">program PascalsTriangle; |
||
procedure Pascal(r:Integer); |
procedure Pascal(r:Integer); |
||
Line 1,863: | Line 1,863: | ||
begin |
begin |
||
Pascal(9); |
Pascal(9); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
Doesn't print anything for negative or null values. |
Doesn't print anything for negative or null values. |
||
< |
<syntaxhighlight lang="delphi">procedure Pascal(r : Integer); |
||
var |
var |
||
i, c, k : Integer; |
i, c, k : Integer; |
||
Line 1,881: | Line 1,881: | ||
end; |
end; |
||
Pascal(9);</ |
Pascal(9);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 1,897: | Line 1,897: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="e">def pascalsTriangle(n, out) { |
||
def row := [].diverge(int) |
def row := [].diverge(int) |
||
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>") |
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>") |
||
Line 1,916: | Line 1,916: | ||
} |
} |
||
out.print("</table>") |
out.print("</table>") |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="e">def out := <file:triangle.html>.textWriter() |
||
try { |
try { |
||
pascalsTriangle(15, out) |
pascalsTriangle(15, out) |
||
Line 1,924: | Line 1,924: | ||
out.close() |
out.close() |
||
} |
} |
||
makeCommand("yourFavoriteWebBrowser")("triangle.html")</ |
makeCommand("yourFavoriteWebBrowser")("triangle.html")</syntaxhighlight> |
||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel"> |
||
note |
note |
||
description : "Prints pascal's triangle" |
description : "Prints pascal's triangle" |
||
Line 2,030: | Line 2,030: | ||
--Contains all already calculated lines |
--Contains all already calculated lines |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Pascal do |
||
def triangle(n), do: triangle(n,[1]) |
def triangle(n), do: triangle(n,[1]) |
||
Line 2,044: | Line 2,044: | ||
end |
end |
||
Pascal.triangle(8)</ |
Pascal.triangle(8)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,060: | Line 2,060: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
===Using mapcar and append, returing a list of rows=== |
===Using mapcar and append, returing a list of rows=== |
||
< |
<syntaxhighlight lang="lisp">(require 'cl-lib) |
||
(defun next-row (row) |
(defun next-row (row) |
||
Line 2,069: | Line 2,069: | ||
(if (= rows 0) |
(if (= rows 0) |
||
'() |
'() |
||
(cons row (triangle (next-row row) (- rows 1)))))</ |
(cons row (triangle (next-row row) (- rows 1)))))</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,083: | Line 2,083: | ||
</pre> |
</pre> |
||
===Translation from Pascal=== |
===Translation from Pascal=== |
||
< |
<syntaxhighlight lang="lisp">(defun pascal (r) |
||
(dotimes (i r) |
(dotimes (i r) |
||
(let ((c 1)) |
(let ((c 1)) |
||
Line 2,090: | Line 2,090: | ||
(setq c (/ (* c (- i k)) |
(setq c (/ (* c (- i k)) |
||
(+ k 1)))) |
(+ k 1)))) |
||
(terpri))))</ |
(terpri))))</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
From the REPL: |
From the REPL: |
||
Line 2,104: | Line 2,104: | ||
===Returning a string=== |
===Returning a string=== |
||
Same as the translation from Pascal, but now returning a string. |
Same as the translation from Pascal, but now returning a string. |
||
< |
<syntaxhighlight lang="lisp">(defun pascal (r) |
||
(let ((out "")) |
(let ((out "")) |
||
(dotimes (i r) |
(dotimes (i r) |
||
Line 2,113: | Line 2,113: | ||
(+ k 1)))) |
(+ k 1)))) |
||
(setq out (concat out "\n")))) |
(setq out (concat out "\n")))) |
||
out))</ |
out))</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Now, since this one returns a string, it is possible to insert the result in the current buffer: |
Now, since this one returns a string, it is possible to insert the result in the current buffer: |
||
Line 2,129: | Line 2,129: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang"> |
||
-import(lists). |
-import(lists). |
||
-export([pascal/1]). |
-export([pascal/1]). |
||
Line 2,138: | Line 2,138: | ||
[H|_] = L, |
[H|_] = L, |
||
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L]. |
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L]. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 2,148: | Line 2,148: | ||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM PASCAL_TRIANGLE |
PROGRAM PASCAL_TRIANGLE |
||
Line 2,166: | Line 2,166: | ||
PASCAL(9) |
PASCAL(9) |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,182: | Line 2,182: | ||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
===Summing from Previous Rows=== |
===Summing from Previous Rows=== |
||
< |
<syntaxhighlight lang="euphoria">sequence row |
||
row = {} |
row = {} |
||
for m = 1 to 10 do |
for m = 1 to 10 do |
||
Line 2,191: | Line 2,191: | ||
print(1,row) |
print(1,row) |
||
puts(1,'\n') |
puts(1,'\n') |
||
end for</ |
end for</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,215: | Line 2,215: | ||
{{Works with|Office 365 betas 2021}} |
{{Works with|Office 365 betas 2021}} |
||
< |
<syntaxhighlight lang="lisp">PASCAL |
||
=LAMBDA(n, |
=LAMBDA(n, |
||
BINCOEFF(n - 1)( |
BINCOEFF(n - 1)( |
||
Line 2,228: | Line 2,228: | ||
QUOTIENT(FACT(n), FACT(k) * FACT(n - k)) |
QUOTIENT(FACT(n), FACT(k) * FACT(n - k)) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,386: | Line 2,386: | ||
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda: |
Or defining the whole triangle as a single grid, by binding the name TRIANGLE to an additional lambda: |
||
< |
<syntaxhighlight lang="lisp">TRIANGLE |
||
=LAMBDA(n, |
=LAMBDA(n, |
||
LET( |
LET( |
||
Line 2,397: | Line 2,397: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 2,554: | Line 2,554: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">let rec nextrow l = |
||
match l with |
match l with |
||
| [] -> [] |
| [] -> [] |
||
Line 2,566: | Line 2,566: | ||
printf "%s" (i.ToString() + ", ") |
printf "%s" (i.ToString() + ", ") |
||
printfn "%s" "\n" |
printfn "%s" "\n" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Line 2,572: | Line 2,572: | ||
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1. |
This implementation works by summing the previous line content. Result for n < 1 is the same as for n == 1. |
||
< |
<syntaxhighlight lang="factor">USING: grouping kernel math sequences ; |
||
: (pascal) ( seq -- newseq ) |
: (pascal) ( seq -- newseq ) |
||
Line 2,578: | Line 2,578: | ||
: pascal ( n -- seq ) |
: pascal ( n -- seq ) |
||
1 - { { 1 } } swap [ (pascal) ] times ;</ |
1 - { { 1 } } swap [ (pascal) ] times ;</syntaxhighlight> |
||
It works as: |
It works as: |
||
< |
<syntaxhighlight lang="factor">5 pascal . |
||
{ { 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 } }</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 2,617: | Line 2,617: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FOCAL}}== |
=={{header|FOCAL}}== |
||
< |
<syntaxhighlight lang="focal">1.1 S OLD(1)=1; T %4.0, 1, ! |
||
1.2 F N=1,10; D 2 |
1.2 F N=1,10; D 2 |
||
1.3 Q |
1.3 Q |
||
Line 2,630: | Line 2,630: | ||
3.1 S OLD(X)=NEW(X) |
3.1 S OLD(X)=NEW(X) |
||
3.2 T %4.0, OLD(X)</ |
3.2 T %4.0, OLD(X)</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<pre> |
<pre> |
||
Line 2,647: | Line 2,647: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: init ( n -- ) |
||
here swap cells erase 1 here ! ; |
here swap cells erase 1 here ! ; |
||
: .line ( n -- ) |
: .line ( n -- ) |
||
Line 2,657: | Line 2,657: | ||
: pascal ( n -- ) |
: pascal ( n -- ) |
||
dup init 1 .line |
dup init 1 .line |
||
1 ?do i next i 1+ .line loop ;</ |
1 ?do i next i 1+ .line loop ;</syntaxhighlight> |
||
This is a bit more efficient. |
This is a bit more efficient. |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="forth">: PascTriangle |
||
cr dup 0 |
cr dup 0 |
||
?do |
?do |
||
Line 2,667: | Line 2,667: | ||
; |
; |
||
13 PascTriangle</ |
13 PascTriangle</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
Prints nothing for n<=0. Output formatting breaks down for n>20 |
Prints nothing for n<=0. Output formatting breaks down for n>20 |
||
< |
<syntaxhighlight lang="fortran">PROGRAM Pascals_Triangle |
||
CALL Print_Triangle(8) |
CALL Print_Triangle(8) |
||
Line 2,697: | Line 2,697: | ||
END DO |
END DO |
||
END SUBROUTINE Print_Triangle</ |
END SUBROUTINE Print_Triangle</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
Sub pascalTriangle(n As UInteger) |
Sub pascalTriangle(n As UInteger) |
||
Line 2,736: | Line 2,736: | ||
Print |
Print |
||
Print "Press any key to quit" |
Print "Press any key to quit" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,758: | Line 2,758: | ||
=={{header|Frink}}== |
=={{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. |
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. |
||
< |
<syntaxhighlight lang="frink"> |
||
pascal[rows] := |
pascal[rows] := |
||
{ |
{ |
||
Line 2,774: | Line 2,774: | ||
pascal[10] |
pascal[10] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,793: | Line 2,793: | ||
=== Summing from Previous Rows === |
=== Summing from Previous Rows === |
||
{{trans|Scala}} |
{{trans|Scala}} |
||
< |
<syntaxhighlight lang="funl">import lists.zip |
||
def |
def |
||
pascal( 1 ) = [1] |
pascal( 1 ) = [1] |
||
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</ |
pascal( n ) = [1] + map( (a, b) -> a + b, zip(pascal(n-1), pascal(n-1).tail()) ) + [1]</syntaxhighlight> |
||
=== Combinations === |
=== Combinations === |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
< |
<syntaxhighlight lang="funl">import integers.choose |
||
def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</ |
def pascal( n ) = [choose( n - 1, k ) | k <- 0..n-1]</syntaxhighlight> |
||
=== Pascal's Triangle === |
=== Pascal's Triangle === |
||
< |
<syntaxhighlight lang="funl">def triangle( height ) = |
||
width = max( map(a -> a.toString().length(), pascal(height)) ) |
width = max( map(a -> a.toString().length(), pascal(height)) ) |
||
Line 2,816: | Line 2,816: | ||
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() ) |
println( map(a -> format('%' + width + 'd ', a), pascal(n)).mkString() ) |
||
triangle( 10 )</ |
triangle( 10 )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,841: | Line 2,841: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">Pascal := function(n) |
||
local i, v; |
local i, v; |
||
v := [1]; |
v := [1]; |
||
Line 2,859: | Line 2,859: | ||
# [ 1, 6, 15, 20, 15, 6, 1 ] |
# [ 1, 6, 15, 20, 15, 6, 1 ] |
||
# [ 1, 7, 21, 35, 35, 21, 7, 1 ] |
# [ 1, 7, 21, 35, 35, 21, 7, 1 ] |
||
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</ |
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
No output for n < 1. Otherwise, output formatted left justified. |
No output for n < 1. Otherwise, output formatted left justified. |
||
<syntaxhighlight lang="go"> |
|||
<lang go> |
|||
package main |
package main |
||
Line 2,906: | Line 2,906: | ||
printTriangle(4) |
printTriangle(4) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,918: | Line 2,918: | ||
=== Recursive === |
=== Recursive === |
||
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution: |
In the spirit of the Haskell "think in whole lists" solution here is a list-driven, minimalist solution: |
||
< |
<syntaxhighlight lang="groovy">def pascal |
||
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</ |
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }</syntaxhighlight> |
||
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. |
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: |
Test program: |
||
< |
<syntaxhighlight lang="groovy">def count = 15 |
||
(1..count).each { n -> |
(1..count).each { n -> |
||
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println "" |
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println "" |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,946: | Line 2,946: | ||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
< |
<syntaxhighlight lang="qbasic">10 INPUT "Number of rows? ",R |
||
20 FOR I=0 TO R-1 |
20 FOR I=0 TO R-1 |
||
30 C=1 |
30 C=1 |
||
Line 2,954: | Line 2,954: | ||
70 NEXT |
70 NEXT |
||
80 PRINT |
80 PRINT |
||
90 NEXT</ |
90 NEXT</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,976: | Line 2,976: | ||
similar function |
similar function |
||
< |
<syntaxhighlight lang="haskell">zapWith :: (a -> a -> a) -> [a] -> [a] -> [a] |
||
zapWith f xs [] = xs |
zapWith f xs [] = xs |
||
zapWith f [] ys = ys |
zapWith f [] ys = ys |
||
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</ |
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys</syntaxhighlight> |
||
Now we can shift a list and add it to itself, extending it by keeping |
Now we can shift a list and add it to itself, extending it by keeping |
||
the ends: |
the ends: |
||
< |
<syntaxhighlight lang="haskell">extendWith f [] = [] |
||
extendWith f xs@(x:ys) = x : zapWith f xs ys</ |
extendWith f xs@(x:ys) = x : zapWith f xs ys</syntaxhighlight> |
||
And for the whole (infinite) triangle, we just iterate this operation, |
And for the whole (infinite) triangle, we just iterate this operation, |
||
starting with the first row: |
starting with the first row: |
||
< |
<syntaxhighlight lang="haskell">pascal = iterate (extendWith (+)) [1]</syntaxhighlight> |
||
For the first ''n'' rows, we just take the first ''n'' elements from this |
For the first ''n'' rows, we just take the first ''n'' elements from this |
||
list, as in |
list, as in |
||
< |
<syntaxhighlight lang="haskell">*Main> take 6 pascal |
||
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</ |
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]</syntaxhighlight> |
||
A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind] |
A shorter approach, plagiarized from [http://www.haskell.org/haskellwiki/Blow_your_mind] |
||
< |
<syntaxhighlight lang="haskell">-- generate next row from current row |
||
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0]) |
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0]) |
||
-- returns the first n rows |
-- returns the first n rows |
||
pascal = iterate nextRow [1]</ |
pascal = iterate nextRow [1]</syntaxhighlight> |
||
Alternatively, using list comprehensions: |
Alternatively, using list comprehensions: |
||
< |
<syntaxhighlight lang="haskell"> |
||
pascal :: [[Integer]] |
pascal :: [[Integer]] |
||
pascal = |
pascal = |
||
(1 : [ 0 | _ <- head pascal]) |
(1 : [ 0 | _ <- head pascal]) |
||
: [zipWith (+) (0:row) row | row <- pascal] |
: [zipWith (+) (0:row) row | row <- pascal] |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="haskell"> |
||
*Pascal> take 5 <$> (take 5 $ triangle) |
*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]] |
[[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> |
|||
</lang> |
|||
With binomial coefficients: |
With binomial coefficients: |
||
< |
<syntaxhighlight lang="haskell">fac = product . enumFromTo 1 |
||
binCoef n k = fac n `div` (fac k * fac (n - k)) |
binCoef n k = fac n `div` (fac k * fac (n - k)) |
||
pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred</ |
pascal = ((fmap . binCoef) <*> enumFromTo 0) . pred</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="haskell">*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10 |
||
1 |
1 |
||
1 1 |
1 1 |
||
Line 3,038: | Line 3,038: | ||
1 8 28 56 70 56 28 8 1 |
1 8 28 56 70 56 28 8 1 |
||
1 9 36 84 126 126 84 36 9 1 |
1 9 36 84 126 126 84 36 9 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest"> CALL Pascal(30) |
||
SUBROUTINE Pascal(rows) |
SUBROUTINE Pascal(rows) |
||
Line 3,055: | Line 3,055: | ||
ENDDO |
ENDDO |
||
ENDDO |
ENDDO |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{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. |
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. |
It also presents the data as an isoceles triangle. |
||
< |
<syntaxhighlight lang="icon">link math |
||
procedure main(A) |
procedure main(A) |
||
Line 3,079: | Line 3,079: | ||
write() |
write() |
||
} |
} |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Icon Programming Library}} |
{{libheader|Icon Programming Library}} |
||
Line 3,105: | Line 3,105: | ||
=={{header|IDL}}== |
=={{header|IDL}}== |
||
< |
<syntaxhighlight lang="idl">Pro Pascal, n |
||
;n is the number of lines of the triangle to be displayed |
;n is the number of lines of the triangle to be displayed |
||
r=[1] |
r=[1] |
||
Line 3,121: | Line 3,121: | ||
print, r |
print, r |
||
End</ |
End</syntaxhighlight> |
||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic">100 PROGRAM "PascalTr.bas" |
||
110 TEXT 80 |
110 TEXT 80 |
||
120 LET ROW=12 |
120 LET ROW=12 |
||
Line 3,135: | Line 3,135: | ||
190 NEXT |
190 NEXT |
||
200 PRINT |
200 PRINT |
||
210 NEXT</ |
210 NEXT</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,153: | Line 3,153: | ||
=={{header|ivy}}== |
=={{header|ivy}}== |
||
< |
<syntaxhighlight lang="ivy"> |
||
op pascal N = transp (0 , iota N) o.! -1 , iota N |
op pascal N = transp (0 , iota N) o.! -1 , iota N |
||
pascal 5 |
pascal 5 |
||
Line 3,162: | Line 3,162: | ||
1 4 6 4 1 0 |
1 4 6 4 1 0 |
||
1 5 10 10 5 1 |
1 5 10 10 5 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> !~/~ i.5 |
||
1 0 0 0 0 |
1 0 0 0 0 |
||
1 1 0 0 0 |
1 1 0 0 0 |
||
1 2 1 0 0 |
1 2 1 0 0 |
||
1 3 3 1 0 |
1 3 3 1 0 |
||
1 4 6 4 1</ |
1 4 6 4 1</syntaxhighlight> |
||
< |
<syntaxhighlight lang="j"> ([: ":@-.&0"1 !~/~)@i. 5 |
||
1 |
1 |
||
1 1 |
1 1 |
||
1 2 1 |
1 2 1 |
||
1 3 3 1 |
1 3 3 1 |
||
1 4 6 4 1</ |
1 4 6 4 1</syntaxhighlight> |
||
< |
<syntaxhighlight lang="j"> (-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5 |
||
1 |
1 |
||
1 1 |
1 1 |
||
1 2 1 |
1 2 1 |
||
1 3 3 1 |
1 3 3 1 |
||
1 4 6 4 1</ |
1 4 6 4 1</syntaxhighlight> |
||
See the [[Talk:Pascal's_triangle#J_Explanation|talk page]] for explanation of earlier version |
See the [[Talk:Pascal's_triangle#J_Explanation|talk page]] for explanation of earlier version |
||
Line 3,193: | Line 3,193: | ||
===Summing from Previous Rows=== |
===Summing from Previous Rows=== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
< |
<syntaxhighlight lang="java">import java.util.ArrayList; |
||
...//class definition, etc. |
...//class definition, etc. |
||
public static void genPyrN(int rows){ |
public static void genPyrN(int rows){ |
||
Line 3,213: | Line 3,213: | ||
System.out.println(thisRow); |
System.out.println(thisRow); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Combinations=== |
===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. |
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. |
||
< |
<syntaxhighlight lang="java">public class Pas{ |
||
public static void main(String[] args){ |
public static void main(String[] args){ |
||
//usage |
//usage |
||
Line 3,243: | Line 3,243: | ||
return ans; |
return ans; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
===Using arithmetic calculation of each row element === |
===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. |
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. |
||
< |
<syntaxhighlight lang="java"> |
||
public class Pascal { |
public class Pascal { |
||
private static void printPascalLine (int n) { |
private static void printPascalLine (int n) { |
||
Line 3,267: | Line 3,267: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 3,274: | Line 3,274: | ||
{{works with|SpiderMonkey}} |
{{works with|SpiderMonkey}} |
||
{{works with|V8}} |
{{works with|V8}} |
||
< |
<syntaxhighlight lang="javascript">// Pascal's triangle object |
||
function pascalTriangle (rows) { |
function pascalTriangle (rows) { |
||
Line 3,344: | Line 3,344: | ||
// Display 8 row triangle in base 16 |
// Display 8 row triangle in base 16 |
||
tri = new pascalTriangle(8); |
tri = new pascalTriangle(8); |
||
tri.print(16);</ |
tri.print(16);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>$ d8 pascal.js |
<pre>$ d8 pascal.js |
||
Line 3,362: | Line 3,362: | ||
====Functional==== |
====Functional==== |
||
{{Trans|Haskell}} |
{{Trans|Haskell}} |
||
< |
<syntaxhighlight lang="javascript">(function (n) { |
||
'use strict'; |
'use strict'; |
||
Line 3,463: | Line 3,463: | ||
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth + |
}), false, 'text-align:center;width:' + nWidth + 'em;height:' + nWidth + |
||
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n'); |
'em;table-layout:fixed;'), JSON.stringify(lstTriangle)].join('\n\n'); |
||
})(7);</ |
})(7);</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;" |
{| class="wikitable" style="text-align:center;width:26em;height:26em;table-layout:fixed;" |
||
Line 3,482: | Line 3,482: | ||
|} |
|} |
||
< |
<syntaxhighlight lang="javascript">[[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]]</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
"use strict"; |
"use strict"; |
||
Line 3,593: | Line 3,593: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 3,607: | Line 3,607: | ||
====Recursive==== |
====Recursive==== |
||
< |
<syntaxhighlight lang="javascript"> |
||
const aux = n => { |
const aux = n => { |
||
if(n <= 1) return [1] |
if(n <= 1) return [1] |
||
Line 3,620: | Line 3,620: | ||
} |
} |
||
pascal(8) |
pascal(8) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 3,633: | Line 3,633: | ||
</pre> |
</pre> |
||
====Recursive - memoized==== |
====Recursive - memoized==== |
||
< |
<syntaxhighlight lang="javascript"> |
||
const aux = (() => { |
const aux = (() => { |
||
const layers = [[1], [1]] |
const layers = [[1], [1]] |
||
Line 3,650: | Line 3,650: | ||
} |
} |
||
pascal(8) |
pascal(8) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 3,657: | Line 3,657: | ||
each corresponding to a row of the Pascal triangle. |
each corresponding to a row of the Pascal triangle. |
||
The implementation avoids any arithmetic except addition. |
The implementation avoids any arithmetic except addition. |
||
< |
<syntaxhighlight lang="jq"># pascal(n) for n>=0; pascal(0) emits an empty stream. |
||
def pascal(n): |
def pascal(n): |
||
def _pascal: # input: the previous row |
def _pascal: # input: the previous row |
||
Line 3,667: | Line 3,667: | ||
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal |
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] | _pascal |
||
end; |
end; |
||
if n <= 0 then empty else [1] | _pascal end ;</ |
if n <= 0 then empty else [1] | _pascal end ;</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
pascal(5) |
pascal(5) |
||
{{ Out }} |
{{ Out }} |
||
< |
<syntaxhighlight lang="sh">$ jq -c -n -f pascal_triangle.jq |
||
[1] |
[1] |
||
[1,1] |
[1,1] |
||
[1,2,1] |
[1,2,1] |
||
[1,3,3,1] |
[1,3,3,1] |
||
[1,4,6,4,1]</ |
[1,4,6,4,1]</syntaxhighlight> |
||
'''Using recurse/1''' |
'''Using recurse/1''' |
||
Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function. |
Here is an equivalent implementation that uses the built-in filter, recurse/1, instead of the inner function. |
||
< |
<syntaxhighlight lang="jq">def pascal(n): |
||
if n <= 0 then empty |
if n <= 0 then empty |
||
else [1] |
else [1] |
||
Line 3,689: | Line 3,689: | ||
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] |
([1]; . + [ $in[$i] + $in[$i + 1] ]) + [1] |
||
end) |
end) |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 3,718: | Line 3,718: | ||
Another solution using matrix exponentiation. |
Another solution using matrix exponentiation. |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
iround(x) = round(Int64, x) |
iround(x) = round(Int64, x) |
||
Line 3,728: | Line 3,728: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,744: | Line 3,744: | ||
Yet another solution using a static vector |
Yet another solution using a static vector |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
function pascal(n) |
function pascal(n) |
||
(n<=0) && error("Pascal trinalge can not have zero or negative rows") |
(n<=0) && error("Pascal trinalge can not have zero or negative rows") |
||
Line 3,760: | Line 3,760: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 3,777: | Line 3,777: | ||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
pascal:{(x-1){+':x,0}\1} |
pascal:{(x-1){+':x,0}\1} |
||
pascal 6 |
pascal 6 |
||
Line 3,785: | Line 3,785: | ||
1 3 3 1 |
1 3 3 1 |
||
1 4 6 4 1 |
1 4 6 4 1 |
||
1 5 10 10 5 1)</ |
1 5 10 10 5 1)</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="kotlin">fun pas(rows: Int) { |
||
for (i in 0..rows - 1) { |
for (i in 0..rows - 1) { |
||
for (j in 0..i) |
for (j in 0..i) |
||
Line 3,805: | Line 3,805: | ||
} |
} |
||
fun main(args: Array<String>) = pas(args[0].toInt())</ |
fun main(args: Array<String>) = pas(args[0].toInt())</syntaxhighlight> |
||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
1) Based on this expression of pascalian binomial: |
1) Based on this expression of pascalian binomial: |
||
Line 3,846: | Line 3,846: | ||
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 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 |
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">input "How much rows would you like? "; n |
||
dim a$(n) |
dim a$(n) |
||
Line 3,867: | Line 3,867: | ||
next i |
next i |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Locomotive Basic}}== |
=={{header|Locomotive Basic}}== |
||
< |
<syntaxhighlight lang="locobasic">10 CLS |
||
20 INPUT "Number of rows? ", rows:GOSUB 40 |
20 INPUT "Number of rows? ", rows:GOSUB 40 |
||
30 END |
30 END |
||
Line 3,882: | Line 3,882: | ||
100 PRINT |
100 PRINT |
||
110 NEXT |
110 NEXT |
||
120 RETURN</ |
120 RETURN</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,898: | Line 3,898: | ||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to pascal :n |
||
if :n = 1 [output [1]] |
if :n = 1 [output [1]] |
||
localmake "a pascal :n-1 |
localmake "a pascal :n-1 |
||
Line 3,904: | Line 3,904: | ||
end |
end |
||
for [i 1 10] [print pascal :i]</ |
for [i 1 10] [print pascal :i]</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
function nextrow(t) |
function nextrow(t) |
||
local ret = {} |
local ret = {} |
||
Line 3,922: | Line 3,922: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
< |
<syntaxhighlight lang="maple">f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1); |
||
f(3);</ |
f(3);</syntaxhighlight> |
||
1 |
1 |
||
1 1 |
1 1 |
||
Line 3,933: | Line 3,933: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
<syntaxhighlight lang="mathematica">n=7; |
|||
<lang Mathematica>n=7; |
|||
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[ |
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[ |
||
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]</ |
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]</syntaxhighlight> |
||
[[File:MmaPascal.png]] |
[[File:MmaPascal.png]] |
||
A more graphical output with arrows would involve the plotting functionality with Graph[]: |
A more graphical output with arrows would involve the plotting functionality with Graph[]: |
||
< |
<syntaxhighlight lang="mathematica">nmax := 10; |
||
pascal[nmax_] := Module[ |
pascal[nmax_] := Module[ |
||
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}], |
{vals = Table[Binomial[n, k], {n, 0, nmax}, {k, 0, n}], |
||
Line 3,958: | Line 3,958: | ||
]; |
]; |
||
pascal[nmax] |
pascal[nmax] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
A matrix containing the pascal triangle can be obtained this way: |
A matrix containing the pascal triangle can be obtained this way: |
||
<lang |
<syntaxhighlight lang="matlab">pascal(n);</syntaxhighlight> |
||
<pre>>> pascal(6) |
<pre>>> pascal(6) |
||
Line 3,978: | Line 3,978: | ||
The binomial coefficients can be extracted from the Pascal triangle in this way: |
The binomial coefficients can be extracted from the Pascal triangle in this way: |
||
< |
<syntaxhighlight lang="matlab"> binomCoeff = diag(rot90(pascal(n)))', </syntaxhighlight> |
||
<pre>>> for k=1:6,diag(rot90(pascal(k)))', end |
<pre>>> for k=1:6,diag(rot90(pascal(k)))', end |
||
Line 4,028: | Line 4,028: | ||
=={{header|Maxima}}== |
=={{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), " ")); |
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " ")); |
||
Line 4,039: | Line 4,039: | ||
"1 4 6 4 1" |
"1 4 6 4 1" |
||
"1 5 10 10 5 1" |
"1 5 10 10 5 1" |
||
"1 6 15 20 15 6 1" */</ |
"1 6 15 20 15 6 1" */</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 4,045: | Line 4,045: | ||
(The formatting starts to be less clear when numbers start to have more than two digits) |
(The formatting starts to be less clear when numbers start to have more than two digits) |
||
< |
<syntaxhighlight lang="metafont">vardef bincoeff(expr n, k) = |
||
save ?; |
save ?; |
||
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor ) |
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor ) |
||
Line 4,062: | Line 4,062: | ||
pascaltr(4); |
pascaltr(4); |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Microsoft Small Basic}}== |
=={{header|Microsoft Small Basic}}== |
||
{{trans|GW-BASIC}} |
{{trans|GW-BASIC}} |
||
< |
<syntaxhighlight lang="microsoftsmallbasic"> |
||
TextWindow.Write("Number of rows? ") |
TextWindow.Write("Number of rows? ") |
||
r = TextWindow.ReadNumber() |
r = TextWindow.ReadNumber() |
||
Line 4,078: | Line 4,078: | ||
TextWindow.WriteLine("") |
TextWindow.WriteLine("") |
||
EndFor |
EndFor |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 4,093: | Line 4,093: | ||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE Pascal; |
||
FROM FormatString IMPORT FormatString; |
FROM FormatString IMPORT FormatString; |
||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
||
Line 4,125: | Line 4,125: | ||
ReadChar |
ReadChar |
||
END Pascal.</ |
END Pascal.</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 4,168: | Line 4,168: | ||
end n_ |
end n_ |
||
return fac /*calc. factorial*/ |
return fac /*calc. factorial*/ |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 4,188: | Line 4,188: | ||
(pascal.nial) |
(pascal.nial) |
||
< |
<syntaxhighlight lang="nial">factorial is recur [ 0 =, 1 first, pass, product, -1 +] |
||
combination is fork [ > [first, second], 0 first, |
combination is fork [ > [first, second], 0 first, |
||
/ [factorial second, * [factorial - [second, first], factorial first] ] |
/ [factorial second, * [factorial - [second, first], factorial first] ] |
||
] |
] |
||
pascal is transpose each combination cart [pass, pass] tell</ |
pascal is transpose each combination cart [pass, pass] tell</syntaxhighlight> |
||
Using it |
Using it |
||
< |
<syntaxhighlight lang="nial">|loaddefs 'pascal.nial' |
||
|pascal 5</ |
|pascal 5</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import sequtils, strutils |
||
proc printPascalTriangle(n: int) = |
proc printPascalTriangle(n: int) = |
||
Line 4,220: | Line 4,220: | ||
echo line.center(lineLength) |
echo line.center(lineLength) |
||
printPascalTriangle(10)</ |
printPascalTriangle(10)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,235: | Line 4,235: | ||
A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this: |
A more optimized solution that doesn't require importing, but produces, naturally, uglier output, would look like this: |
||
< |
<syntaxhighlight lang="nim">const ROWS = 10 |
||
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression |
const TRILEN = toInt(ROWS * (ROWS + 1) / 2) # Sum of arth progression |
||
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations |
var triangle = newSeqOfCap[Natural](TRILEN) # Avoid reallocations |
||
Line 4,247: | Line 4,247: | ||
if row + 1 <= ROWS: printPascalTri(row + 1, result) |
if row + 1 <= ROWS: printPascalTri(row + 1, result) |
||
printPascalTri(1, triangle)</ |
printPascalTri(1, triangle)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,263: | Line 4,263: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">(* generate next row from current row *) |
||
let next_row row = |
let next_row row = |
||
List.map2 (+) ([0] @ row) (row @ [0]) |
List.map2 (+) ([0] @ row) (row @ [0]) |
||
Line 4,272: | Line 4,272: | ||
if i = n then [] |
if i = n then [] |
||
else row :: loop (i+1) (next_row row) |
else row :: loop (i+1) (next_row row) |
||
in loop 0 [1]</ |
in loop 0 [1]</syntaxhighlight> |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function pascaltriangle(h) |
||
for i = 0:h-1 |
for i = 0:h-1 |
||
for k = 0:h-i |
for k = 0:h-i |
||
Line 4,287: | Line 4,287: | ||
endfunction |
endfunction |
||
pascaltriangle(4);</ |
pascaltriangle(4);</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
Line 4,293: | Line 4,293: | ||
No result if n <= 0 |
No result if n <= 0 |
||
< |
<syntaxhighlight lang="oforth">: pascal(n) [ 1 ] #[ dup println dup 0 + 0 rot + zipWith(#+) ] times(n) drop ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,311: | Line 4,311: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {NextLine Xs} |
fun {NextLine Xs} |
||
{List.zip 0|Xs {Append Xs [0]} |
{List.zip 0|Xs {Append Xs [0]} |
||
Line 4,341: | Line 4,341: | ||
end |
end |
||
in |
in |
||
{PrintTriangle {Triangle 5}}</ |
{PrintTriangle {Triangle 5}}</syntaxhighlight> |
||
For n = 0, prints nothing. For negative n, throws an exception. |
For n = 0, prints nothing. For negative n, throws an exception. |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">pascals_triangle(N)= { |
||
my(row=[],prevrow=[]); |
my(row=[],prevrow=[]); |
||
for(x=1,N, |
for(x=1,N, |
||
Line 4,360: | Line 4,360: | ||
print(row); |
print(row); |
||
); |
); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program PascalsTriangle(output); |
||
procedure Pascal(r : Integer); |
procedure Pascal(r : Integer); |
||
Line 4,383: | Line 4,383: | ||
begin |
begin |
||
Pascal(9) |
Pascal(9) |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>% ./PascalsTriangle |
<pre>% ./PascalsTriangle |
||
Line 4,399: | Line 4,399: | ||
=={{header|Perl}}== |
=={{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). |
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). |
||
< |
<syntaxhighlight lang="perl">sub pascal { |
||
my $rows = shift; |
my $rows = shift; |
||
my @next = (1); |
my @next = (1); |
||
Line 4,406: | Line 4,406: | ||
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1); |
@next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
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: |
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}} |
{{libheader|ntheory}} |
||
< |
<syntaxhighlight lang="perl">use ntheory qw/binomial/; |
||
sub pascal { |
sub pascal { |
||
my $rows = shift; |
my $rows = shift; |
||
Line 4,416: | Line 4,416: | ||
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n"; |
print join(" ", map { binomial($n,$_) } 0 .. $n), "\n"; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used: |
Here is a non-obvious version using bignum, which is limited to the first 23 rows because of the algorithm used: |
||
< |
<syntaxhighlight lang="perl">use bignum; |
||
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 } |
sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 } |
||
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</ |
sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 }</syntaxhighlight> |
||
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] |
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] |
||
< |
<syntaxhighlight lang="perl"> |
||
#!/usr/bin/perl |
#!/usr/bin/perl |
||
use strict; |
use strict; |
||
Line 4,460: | Line 4,460: | ||
my @third = tartaglia_row(5); |
my @third = tartaglia_row(5); |
||
print "@third\n"; |
print "@third\n"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
which output |
which output |
||
Line 4,477: | Line 4,477: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<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: #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> |
<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,490: | Line 4,490: | ||
<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: #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> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre style="font-size: 8px"> |
<pre style="font-size: 8px"> |
||
Line 4,511: | Line 4,511: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"> |
||
<?php |
<?php |
||
//Author Ivan Gavryshin @dcc0 |
//Author Ivan Gavryshin @dcc0 |
||
Line 4,557: | Line 4,557: | ||
?> |
?> |
||
</ |
</syntaxhighlight> =={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">function pascalsTriangle($num){ |
||
$c = 1; |
$c = 1; |
||
$triangle = Array(); |
$triangle = Array(); |
||
Line 4,580: | Line 4,580: | ||
} |
} |
||
echo '<br>'; |
echo '<br>'; |
||
}</ |
}</syntaxhighlight> |
||
1 |
1 |
||
1 1 |
1 1 |
||
Line 4,592: | Line 4,592: | ||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
<syntaxhighlight lang="picat"> |
|||
<lang Picat> |
|||
%Author: Petar Kabashki |
%Author: Petar Kabashki |
||
spatr([]) = []. |
spatr([]) = []. |
||
Line 4,604: | Line 4,604: | ||
foreach(I in 0 .. 10) println(patr(I)) end. |
foreach(I in 0 .. 10) println(patr(I)) end. |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="picat"> |
||
[1] |
[1] |
||
[1,1] |
[1,1] |
||
Line 4,617: | Line 4,617: | ||
[1,9,36,84,126,126,84,36,9,1] |
[1,9,36,84,126,126,84,36,9,1] |
||
[1,10,45,120,210,252,210,120,45,10,1] |
[1,10,45,120,210,252,210,120,45,10,1] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="picolisp">(de pascalTriangle (N) |
||
(for I N |
(for I N |
||
(space (* 2 (- N I))) |
(space (* 2 (- N I))) |
||
Line 4,628: | Line 4,628: | ||
(prin (align 3 C) " ") |
(prin (align 3 C) " ") |
||
(setq C (*/ C (- I K) K)) ) ) |
(setq C (*/ C (- I K) K)) ) ) |
||
(prinl) ) )</ |
(prinl) ) )</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
declare (t, u)(40) fixed binary; |
declare (t, u)(40) fixed binary; |
||
declare (i, n) fixed binary; |
declare (i, n) fixed binary; |
||
Line 4,647: | Line 4,647: | ||
t = u; |
t = u; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
<lang> |
<syntaxhighlight lang="text"> |
||
1 |
1 |
||
1 1 |
1 1 |
||
Line 4,661: | Line 4,661: | ||
1 9 36 84 126 126 84 36 9 1 |
1 9 36 84 126 126 84 36 9 1 |
||
1 10 45 120 210 252 210 120 45 10 1 |
1 10 45 120 210 252 210 120 45 10 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Potion}}== |
=={{header|Potion}}== |
||
< |
<syntaxhighlight lang="potion">printpascal = (n) : |
||
if (n < 1) : |
if (n < 1) : |
||
1 print |
1 print |
||
Line 4,681: | Line 4,681: | ||
. |
. |
||
printpascal(read number integer)</ |
printpascal(read number integer)</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell"> |
||
$Infinity = 1 |
$Infinity = 1 |
||
$NewNumbers = $null |
$NewNumbers = $null |
||
Line 4,749: | Line 4,749: | ||
$Infinity++ |
$Infinity++ |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Save the above code to a .ps1 script file and start it by calling its name and providing N. |
Save the above code to a .ps1 script file and start it by calling its name and providing N. |
||
Line 4,778: | Line 4,778: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Difference-lists are used to make quick append. |
Difference-lists are used to make quick append. |
||
< |
<syntaxhighlight lang="prolog">pascal(N) :- |
||
pascal(1, N, [1], [[1]|X]-X, L), |
pascal(1, N, [1], [[1]|X]-X, L), |
||
maplist(my_format, L). |
maplist(my_format, L). |
||
Line 4,814: | Line 4,814: | ||
my_writef(X) :- |
my_writef(X) :- |
||
writef(' %5r', [X]). |
writef(' %5r', [X]). |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output : |
Output : |
||
< |
<syntaxhighlight lang="prolog"> ?- pascal(15). |
||
1 |
1 |
||
1 1 |
1 1 |
||
Line 4,835: | Line 4,835: | ||
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1 |
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1 |
||
true. |
true. |
||
</syntaxhighlight> |
|||
</lang> |
|||
===An alternative=== |
===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. |
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. |
||
< |
<syntaxhighlight lang="prolog">%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
||
% Produce a pascal's triangle of depth N |
% Produce a pascal's triangle of depth N |
||
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
||
Line 4,866: | Line 4,866: | ||
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row |
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row |
||
write(Row), nl, fail. |
write(Row), nl, fail. |
||
pascal(_).</ |
pascal(_).</syntaxhighlight> |
||
*Output*: |
*Output*: |
||
< |
<syntaxhighlight lang="prolog">?- pascal(5). |
||
[1] |
[1] |
||
[1,1] |
[1,1] |
||
[1,2,1] |
[1,2,1] |
||
[1,3,3,1] |
[1,3,3,1] |
||
[1,4,6,4,1]</ |
[1,4,6,4,1]</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure pascaltriangle( n.i) |
||
For i= 0 To n |
For i= 0 To n |
||
Line 4,893: | Line 4,893: | ||
Parameter.i = Val(ProgramParameter(0)) |
Parameter.i = Val(ProgramParameter(0)) |
||
pascaltriangle(Parameter); |
pascaltriangle(Parameter); |
||
Input()</ |
Input()</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Procedural=== |
===Procedural=== |
||
< |
<syntaxhighlight lang="python">def pascal(n): |
||
"""Prints out n rows of Pascal's triangle. |
"""Prints out n rows of Pascal's triangle. |
||
It returns False for failure and True for success.""" |
It returns False for failure and True for success.""" |
||
Line 4,905: | Line 4,905: | ||
print row |
print row |
||
row=[l+r for l,r in zip(row+k,k+row)] |
row=[l+r for l,r in zip(row+k,k+row)] |
||
return n>=1</ |
return n>=1</syntaxhighlight> |
||
or by creating a scan function: |
or by creating a scan function: |
||
< |
<syntaxhighlight lang="python">def scan(op, seq, it): |
||
a = [] |
a = [] |
||
result = it |
result = it |
||
Line 4,924: | Line 4,924: | ||
for row in pascal(4): |
for row in pascal(4): |
||
print(row)</ |
print(row)</syntaxhighlight> |
||
===Functional=== |
===Functional=== |
||
Line 4,931: | Line 4,931: | ||
{{Works with|Python|3.7}} |
{{Works with|Python|3.7}} |
||
< |
<syntaxhighlight lang="python">'''Pascal's triangle''' |
||
from itertools import (accumulate, chain, islice) |
from itertools import (accumulate, chain, islice) |
||
Line 5,027: | Line 5,027: | ||
# MAIN --- |
# MAIN --- |
||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main()</ |
main()</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 5,045: | Line 5,045: | ||
=={{header|q}}== |
=={{header|q}}== |
||
<syntaxhighlight lang="q"> |
|||
<lang q> |
|||
pascal:{(x-1){0+':x,0}\1} |
pascal:{(x-1){0+':x,0}\1} |
||
pascal 5 |
pascal 5 |
||
Line 5,053: | Line 5,053: | ||
1 3 3 1 |
1 3 3 1 |
||
1 4 6 4 1 |
1 4 6 4 1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Qi}}== |
=={{header|Qi}}== |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
<syntaxhighlight lang="qi"> |
|||
<lang Qi> |
|||
(define iterate |
(define iterate |
||
_ _ 0 -> [] |
_ _ 0 -> [] |
||
Line 5,067: | Line 5,067: | ||
(define pascal |
(define pascal |
||
N -> (iterate next-row [1] N)) |
N -> (iterate next-row [1] N)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 5,073: | Line 5,073: | ||
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1. |
The behaviour of <code>pascal</code> for values less than 1 is the same as its behaviour for 1. |
||
< |
<syntaxhighlight lang="quackery"> [ over size - |
||
space swap of |
space swap of |
||
swap join ] is justify ( $ n --> ) |
swap join ] is justify ( $ n --> ) |
||
Line 5,094: | Line 5,094: | ||
echoline ] is pascal ( n --> ) |
echoline ] is pascal ( n --> ) |
||
16 pascal</ |
16 pascal</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,118: | Line 5,118: | ||
=={{header|R}}== |
=={{header|R}}== |
||
{{trans|Octave}} |
{{trans|Octave}} |
||
< |
<syntaxhighlight lang="r">pascalTriangle <- function(h) { |
||
for(i in 0:(h-1)) { |
for(i in 0:(h-1)) { |
||
s <- "" |
s <- "" |
||
Line 5,127: | Line 5,127: | ||
print(s) |
print(s) |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Here's an R version: |
Here's an R version: |
||
< |
<syntaxhighlight lang="r">pascalTriangle <- function(h) { |
||
lapply(0:h, function(i) choose(i, 0:i)) |
lapply(0:h, function(i) choose(i, 0:i)) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 5,139: | Line 5,139: | ||
Iterative version by summing rows up to <math>n</math>. |
Iterative version by summing rows up to <math>n</math>. |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define (pascal n) |
(define (pascal n) |
||
Line 5,151: | Line 5,151: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 5,159: | Line 5,159: | ||
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: |
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: |
||
<lang |
<syntaxhighlight lang="raku" line>sub pascal { |
||
[1], { [0, |$_ Z+ |$_, 0] } ... * |
[1], { [0, |$_ Z+ |$_, 0] } ... * |
||
} |
} |
||
.say for pascal[^10];</ |
.say for pascal[^10];</syntaxhighlight> |
||
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: |
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: |
||
<lang |
<syntaxhighlight lang="raku" line>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *; |
||
.say for @pascal[^10];</ |
.say for @pascal[^10];</syntaxhighlight> |
||
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error. |
Since we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error. |
||
Line 5,177: | Line 5,177: | ||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
<lang |
<syntaxhighlight lang="raku" line>multi sub pascal (1) { $[1] } |
||
multi sub pascal (Int $n where 2..*) { |
multi sub pascal (Int $n where 2..*) { |
||
my @rows = pascal $n - 1; |
my @rows = pascal $n - 1; |
||
Line 5,183: | Line 5,183: | ||
} |
} |
||
.say for pascal 10;</ |
.say for pascal 10;</syntaxhighlight> |
||
Non-positive inputs throw a multiple-dispatch error. |
Non-positive inputs throw a multiple-dispatch error. |
||
Line 5,190: | Line 5,190: | ||
{{trans|Perl}} |
{{trans|Perl}} |
||
<lang |
<syntaxhighlight lang="raku" line>sub pascal ($n where $n >= 1) { |
||
say my @last = 1; |
say my @last = 1; |
||
for 1 .. $n - 1 -> $row { |
for 1 .. $n - 1 -> $row { |
||
Line 5,198: | Line 5,198: | ||
} |
} |
||
pascal 10;</ |
pascal 10;</syntaxhighlight> |
||
Non-positive inputs throw a type check error. |
Non-positive inputs throw a type check error. |
||
Line 5,227: | Line 5,227: | ||
RapidQ does not require simple variables to be declared before use. |
RapidQ does not require simple variables to be declared before use. |
||
< |
<syntaxhighlight lang="rapidq">DEFINT values(100) = {0,1} |
||
INPUT "Number of rows: "; nrows |
INPUT "Number of rows: "; nrows |
||
Line 5,238: | Line 5,238: | ||
NEXT i |
NEXT i |
||
PRINT |
PRINT |
||
NEXT row</ |
NEXT row</syntaxhighlight> |
||
===Using binary coefficients=== |
===Using binary coefficients=== |
||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
< |
<syntaxhighlight lang="rapidq">INPUT "Number of rows: "; nrows |
||
FOR row = 0 TO nrows-1 |
FOR row = 0 TO nrows-1 |
||
c = 1 |
c = 1 |
||
Line 5,251: | Line 5,251: | ||
NEXT i |
NEXT i |
||
PRINT |
PRINT |
||
NEXT row</ |
NEXT row</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">Red[] |
||
pascal-triangle: function [ |
pascal-triangle: function [ |
||
n [ integer! ] "number of rows" |
n [ integer! ] "number of rows" |
||
Line 5,267: | Line 5,267: | ||
row: left + right |
row: left + right |
||
] |
] |
||
]</ |
]</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,281: | Line 5,281: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">2 elements i j |
||
: pascalTriangle |
: pascalTriangle |
||
cr dup |
cr dup |
||
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop |
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop |
||
; |
; |
||
13 pascalTriangle</ |
13 pascalTriangle</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 5,303: | Line 5,303: | ||
:::* Tartaglia's triangle |
:::* Tartaglia's triangle |
||
:::* Yang Hui's triangle |
:::* Yang Hui's triangle |
||
< |
<syntaxhighlight lang="rexx">/*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/ |
||
numeric digits 3000 /*be able to handle gihugeic triangles.*/ |
numeric digits 3000 /*be able to handle gihugeic triangles.*/ |
||
parse arg nn . /*obtain the optional argument from CL.*/ |
parse arg nn . /*obtain the optional argument from CL.*/ |
||
Line 5,326: | Line 5,326: | ||
exit /*stick a fork in it, we're all done. */ |
exit /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</ |
!: procedure; !=1; do j=2 to arg(1); != !*j; end /*j*/; return ! /*compute factorial*/</syntaxhighlight> |
||
{{out|output|text= when using the input of: <tt> 11 </tt>}} |
{{out|output|text= when using the input of: <tt> 11 </tt>}} |
||
<pre> |
<pre> |
||
Line 5,370: | Line 5,370: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
row = 5 |
row = 5 |
||
for i = 0 to row - 1 |
for i = 0 to row - 1 |
||
Line 5,381: | Line 5,381: | ||
see nl |
see nl |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,392: | Line 5,392: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def pascal(n) |
||
raise ArgumentError, "must be positive." if n < 1 |
raise ArgumentError, "must be positive." if n < 1 |
||
yield ar = [1] |
yield ar = [1] |
||
Line 5,401: | Line 5,401: | ||
end |
end |
||
pascal(8){|row| puts row.join(" ").center(20)}</ |
pascal(8){|row| puts row.join(" ").center(20)}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,416: | Line 5,416: | ||
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know): |
Or for more or less a translation of the two line Haskell version (with inject being abused a bit I know): |
||
< |
<syntaxhighlight lang="ruby">def next_row(row) ([0] + row).zip(row + [0]).collect {|l,r| l + r } end |
||
def pascal(n) n.times.inject([1]) {|x,_| next_row x } end |
def pascal(n) n.times.inject([1]) {|x,_| next_row x } end |
||
8.times{|i| p pascal(i)}</ |
8.times{|i| p pascal(i)}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,434: | Line 5,434: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">input "number of rows? ";r |
||
for i = 0 to r - 1 |
for i = 0 to r - 1 |
||
c = 1 |
c = 1 |
||
Line 5,443: | Line 5,443: | ||
next |
next |
||
print |
print |
||
next</ |
next</syntaxhighlight>Output: |
||
<pre>Number of rows? ?5 |
<pre>Number of rows? ?5 |
||
1 |
1 |
||
Line 5,453: | Line 5,453: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="rust"> |
||
fn pascal_triangle(n: u64) |
fn pascal_triangle(n: u64) |
||
{ |
{ |
||
Line 5,469: | Line 5,469: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
===Functional solutions=== |
===Functional solutions=== |
||
====Summing: Recursive row definition==== |
====Summing: Recursive row definition==== |
||
< |
<syntaxhighlight lang="scala"> |
||
def tri(row: Int): List[Int] = |
def tri(row: Int): List[Int] = |
||
row match { |
row match { |
||
case 1 => List(1) |
case 1 => List(1) |
||
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1 |
case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1 |
||
}</ |
}</syntaxhighlight> |
||
Function to pretty print n rows: |
Function to pretty print n rows: |
||
< |
<syntaxhighlight lang="scala">def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println} |
||
prettyTri(5)</ |
prettyTri(5)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 5,491: | Line 5,491: | ||
1 4 6 4 1</pre> |
1 4 6 4 1</pre> |
||
====Summing: Scala Stream (Recursive & Memoization)==== |
====Summing: Scala Stream (Recursive & Memoization)==== |
||
< |
<syntaxhighlight lang="scala">object Blaise extends App { |
||
def pascalTriangle(): Stream[Vector[Int]] = |
def pascalTriangle(): Stream[Vector[Int]] = |
||
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1) |
Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1) |
||
Line 5,500: | Line 5,500: | ||
println("Pascal's Triangle") |
println("Pascal's Triangle") |
||
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line")) |
output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line")) |
||
}</ |
}</syntaxhighlight> |
||
{{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)]. |
{{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}}== |
=={{header|Scheme}}== |
||
{{Works with|Scheme|R<math>^5</math>RS}} |
{{Works with|Scheme|R<math>^5</math>RS}} |
||
< |
<syntaxhighlight lang="scheme">(define (next-row row) |
||
(map + (cons 0 row) (append row '(0)))) |
(map + (cons 0 row) (append row '(0)))) |
||
Line 5,514: | Line 5,514: | ||
(triangle (list 1) 5) |
(triangle (list 1) 5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<lang>((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</ |
<syntaxhighlight lang="text">((1) (1 1) (1 2 1) (1 3 3 1) (1 4 6 4 1))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 5,540: | Line 5,540: | ||
writeln; |
writeln; |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">func pascal(rows) { |
||
var row = [1] |
var row = [1] |
||
{ | n| |
{ | n| |
||
Line 5,551: | Line 5,551: | ||
} |
} |
||
pascal(10)</ |
pascal(10)</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{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). |
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). |
||
< |
<syntaxhighlight lang="stata">function pascal1(n) { |
||
return(comb(J(1,n,0::n-1),J(n,1,0..n-1))) |
return(comb(J(1,n,0::n-1),J(n,1,0..n-1))) |
||
} |
} |
||
Line 5,581: | Line 5,581: | ||
} |
} |
||
return(s) |
return(s) |
||
}</ |
}</syntaxhighlight> |
||
Now print the Pascal triangle. |
Now print the Pascal triangle. |
||
< |
<syntaxhighlight lang="stata">function print_pascal_triangle(n) { |
||
a = pascal1(n) |
a = pascal1(n) |
||
for (i=1; i<=n; i++) { |
for (i=1; i<=n; i++) { |
||
Line 5,600: | Line 5,600: | ||
1 2 1 |
1 2 1 |
||
1 3 3 1 |
1 3 3 1 |
||
1 4 6 4 1</ |
1 4 6 4 1</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func pascal(n:Int)->[Int]{ |
||
if n==1{ |
if n==1{ |
||
let a=[1] |
let a=[1] |
||
Line 5,625: | Line 5,625: | ||
} |
} |
||
let waste = pascal(n:10) |
let waste = pascal(n:10) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
===Summing from Previous Rows=== |
===Summing from Previous Rows=== |
||
< |
<syntaxhighlight lang="tcl">proc pascal_iterative n { |
||
if {$n < 1} {error "undefined behaviour for n < 1"} |
if {$n < 1} {error "undefined behaviour for n < 1"} |
||
set row [list 1] |
set row [list 1] |
||
Line 5,646: | Line 5,646: | ||
} |
} |
||
puts [join [pascal_iterative 6] \n]</ |
puts [join [pascal_iterative 6] \n]</syntaxhighlight> |
||
<pre>1 |
<pre>1 |
||
1 1 |
1 1 |
||
Line 5,655: | Line 5,655: | ||
===Using binary coefficients=== |
===Using binary coefficients=== |
||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
< |
<syntaxhighlight lang="tcl">proc pascal_coefficients n { |
||
if {$n < 1} {error "undefined behaviour for n < 1"} |
if {$n < 1} {error "undefined behaviour for n < 1"} |
||
for {set i 0} {$i < $n} {incr i} { |
for {set i 0} {$i < $n} {incr i} { |
||
Line 5,669: | Line 5,669: | ||
} |
} |
||
puts [join [pascal_coefficients 6] \n]</ |
puts [join [pascal_coefficients 6] \n]</syntaxhighlight> |
||
===Combinations=== |
===Combinations=== |
||
{{trans|Java}} |
{{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. |
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. |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc pascal_combinations n { |
proc pascal_combinations n { |
||
Line 5,707: | Line 5,707: | ||
} |
} |
||
puts [join [pascal_combinations 6] \n]</ |
puts [join [pascal_combinations 6] \n]</syntaxhighlight> |
||
===Comparing Performance=== |
===Comparing Performance=== |
||
< |
<syntaxhighlight lang="tcl">set n 100 |
||
puts "calculate $n rows:" |
puts "calculate $n rows:" |
||
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} { |
foreach proc {pascal_iterative pascal_coefficients pascal_combinations} { |
||
puts "$proc: [time [list $proc $n] 100]" |
puts "$proc: [time [list $proc $n] 100]" |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>calculate 100 rows: |
<pre>calculate 100 rows: |
||
Line 5,723: | Line 5,723: | ||
=={{header|TI-83 BASIC}}== |
=={{header|TI-83 BASIC}}== |
||
===Using Addition of Previous Rows=== |
===Using Addition of Previous Rows=== |
||
< |
<syntaxhighlight lang="ti83b">PROGRAM:PASCALTR |
||
:Lbl IN |
:Lbl IN |
||
:ClrHome |
:ClrHome |
||
Line 5,739: | Line 5,739: | ||
:End |
:End |
||
:End |
:End |
||
:[A]</ |
:[A]</syntaxhighlight> |
||
===Using nCr Function=== |
===Using nCr Function=== |
||
< |
<syntaxhighlight lang="ti83b">PROGRAM:PASCALTR |
||
:Lbl IN |
:Lbl IN |
||
:ClrHome |
:ClrHome |
||
Line 5,753: | Line 5,753: | ||
:End |
:End |
||
:End |
:End |
||
:[A]</ |
:[A]</syntaxhighlight> |
||
=={{header|Turing}}== |
=={{header|Turing}}== |
||
< |
<syntaxhighlight lang="turing">proc pascal (n : int) |
||
for i : 0 .. n |
for i : 0 .. n |
||
var c := 1 |
var c := 1 |
||
Line 5,768: | Line 5,768: | ||
end pascal |
end pascal |
||
pascal(5)</ |
pascal(5)</syntaxhighlight> |
||
Output: |
Output: |
||
Line 5,780: | Line 5,780: | ||
== {{header|TypeScript}} == |
== {{header|TypeScript}} == |
||
{{trans|XPL0}} |
{{trans|XPL0}} |
||
< |
<syntaxhighlight lang="javascript">// Pascal's triangle |
||
function pascal(n: number): void { |
function pascal(n: number): void { |
||
Line 5,811: | Line 5,811: | ||
pascal(13); |
pascal(13); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,830: | Line 5,830: | ||
=={{header|uBasic/4tH}}== |
=={{header|uBasic/4tH}}== |
||
<lang>Input "Number Of Rows: "; N |
<syntaxhighlight lang="text">Input "Number Of Rows: "; N |
||
@(1) = 1 |
@(1) = 1 |
||
Print Tab((N+1)*3);"1" |
Print Tab((N+1)*3);"1" |
||
Line 5,843: | Line 5,843: | ||
Print |
Print |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Number Of Rows: 10 |
<pre>Number Of Rows: 10 |
||
Line 5,863: | Line 5,863: | ||
{{works with|Bourne Again SHell}} |
{{works with|Bourne Again SHell}} |
||
Any n <= 1 will print the "1" row. |
Any n <= 1 will print the "1" row. |
||
< |
<syntaxhighlight lang="bash">#! /bin/bash |
||
pascal() { |
pascal() { |
||
local -i n=${1:-1} |
local -i n=${1:-1} |
||
Line 5,880: | Line 5,880: | ||
fi |
fi |
||
} |
} |
||
pascal "$1"</ |
pascal "$1"</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Zero maps to the empty list. Negatives are inexpressible. |
Zero maps to the empty list. Negatives are inexpressible. |
||
This solution uses a library function for binomial coefficients. |
This solution uses a library function for binomial coefficients. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
pascal = choose**ziDS+ iota*t+ iota+ successor</ |
pascal = choose**ziDS+ iota*t+ iota+ successor</syntaxhighlight> |
||
This solution uses direct summation. The algorithm is to |
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, |
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. |
map the sum over the list of pairs, iterate n times, and return the trace. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
pascal "n" = (next"n" sum*NiCixp) <1></ |
pascal "n" = (next"n" sum*NiCixp) <1></syntaxhighlight> |
||
test program: |
test program: |
||
< |
<syntaxhighlight lang="ursala">#cast %nLL |
||
example = pascal 10</ |
example = pascal 10</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>< |
<pre>< |
||
Line 5,914: | Line 5,914: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
< |
<syntaxhighlight lang="vb">Option Base 1 |
||
Private Sub pascal_triangle(n As Integer) |
Private Sub pascal_triangle(n As Integer) |
||
Dim odd() As String |
Dim odd() As String |
||
Line 5,943: | Line 5,943: | ||
Public Sub main() |
Public Sub main() |
||
pascal_triangle 13 |
pascal_triangle 13 |
||
End Sub</ |
End Sub</syntaxhighlight>{{out}} |
||
<pre> 1 |
<pre> 1 |
||
1 1 |
1 1 |
||
Line 5,960: | Line 5,960: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
Derived from the BASIC version. |
Derived from the BASIC version. |
||
< |
<syntaxhighlight lang="vb">Pascal_Triangle(WScript.Arguments(0)) |
||
Function Pascal_Triangle(n) |
Function Pascal_Triangle(n) |
||
Dim values(100) |
Dim values(100) |
||
Line 5,973: | Line 5,973: | ||
WScript.StdOut.WriteLine |
WScript.StdOut.WriteLine |
||
Next |
Next |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Invoke from a command line. |
Invoke from a command line. |
||
Line 5,994: | Line 5,994: | ||
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2. |
For example, if #99 contains value 2, then #@99 accesses contents of numeric register #2. |
||
< |
<syntaxhighlight lang="vedit">#100 = Get_Num("Number of rows: ", STATLINE) |
||
#0=0; #1=1 |
#0=0; #1=1 |
||
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1) |
Ins_Char(' ', COUNT, #100*3-2) Num_Ins(1) |
||
Line 6,006: | Line 6,006: | ||
} |
} |
||
Ins_Newline |
Ins_Newline |
||
}</ |
}</syntaxhighlight> |
||
===Using binary coefficients=== |
===Using binary coefficients=== |
||
{{trans|BASIC}} |
{{trans|BASIC}} |
||
< |
<syntaxhighlight lang="vedit">#1 = Get_Num("Number of rows: ", STATLINE) |
||
for (#2 = 0; #2 < #1; #2++) { |
for (#2 = 0; #2 < #1; #2++) { |
||
#3 = 1 |
#3 = 1 |
||
Line 6,019: | Line 6,019: | ||
} |
} |
||
Ins_Newline |
Ins_Newline |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
{{works with|Visual Basic|VB6 Standard}} |
{{works with|Visual Basic|VB6 Standard}} |
||
< |
<syntaxhighlight lang="vb">Sub pascaltriangle() |
||
'Pascal's triangle |
'Pascal's triangle |
||
Const m = 11 |
Const m = 11 |
||
Line 6,040: | Line 6,040: | ||
Next n |
Next n |
||
MsgBox ss, , "Pascal's triangle" |
MsgBox ss, , "Pascal's triangle" |
||
End Sub 'pascaltriangle</ |
End Sub 'pascaltriangle</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,058: | Line 6,058: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vbnet">Imports System.Numerics |
||
Module Module1 |
Module Module1 |
||
Line 6,099: | Line 6,099: | ||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> 1 |
<pre> 1 |
||
Line 6,125: | Line 6,125: | ||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
{{libheader|wren-math}} |
{{libheader|wren-math}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt |
||
import "/math" for Int |
import "/math" for Int |
||
Line 6,150: | Line 6,150: | ||
} |
} |
||
pascalTriangle.call(13)</ |
pascalTriangle.call(13)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,173: | Line 6,173: | ||
{{works with|Windows}} |
{{works with|Windows}} |
||
<b>uses:</b> io.inc - Macro library from SASM |
<b>uses:</b> io.inc - Macro library from SASM |
||
< |
<syntaxhighlight lang="asm"> |
||
%include "io.inc" |
%include "io.inc" |
||
Line 6,252: | Line 6,252: | ||
pop ecx |
pop ecx |
||
ret |
ret |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,267: | Line 6,267: | ||
{{trans|GW-BASIC}} |
{{trans|GW-BASIC}} |
||
{{works with|Windows XBasic}} |
{{works with|Windows XBasic}} |
||
< |
<syntaxhighlight lang="xbasic"> |
||
PROGRAM "pascal" |
PROGRAM "pascal" |
||
VERSION "0.0001" |
VERSION "0.0001" |
||
Line 6,285: | Line 6,285: | ||
END FUNCTION |
END FUNCTION |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,299: | Line 6,299: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; |
||
proc Pascal(N); \Display the first N rows of Pascal's triangle |
proc Pascal(N); \Display the first N rows of Pascal's triangle |
||
Line 6,320: | Line 6,320: | ||
]; |
]; |
||
Pascal(13)</ |
Pascal(13)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 6,341: | Line 6,341: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="zkl">fcn pascalTriangle(n){ // n<=0-->"" |
||
foreach i in (n){ |
foreach i in (n){ |
||
c := 1; |
c := 1; |
||
Line 6,353: | Line 6,353: | ||
} |
} |
||
pascalTriangle(8);</ |
pascalTriangle(8);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 6,369: | Line 6,369: | ||
In edit mode insert: |
In edit mode insert: |
||
< |
<syntaxhighlight lang="basic"> 10 INPUT "How many rows? ";n |
||
15 IF n<1 THEN GO TO 210 |
15 IF n<1 THEN GO TO 210 |
||
20 DIM c(n) |
20 DIM c(n) |
||
Line 6,392: | Line 6,392: | ||
180 LET c(i)=d(i) |
180 LET c(i)=d(i) |
||
190 NEXT i |
190 NEXT i |
||
200 NEXT r</ |
200 NEXT r</syntaxhighlight> |
||
Then in command mode (basically don't put a number in front): |
Then in command mode (basically don't put a number in front): |
||
<lang |
<syntaxhighlight lang="basic">RUN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |