Pascal matrix generation: Difference between revisions
m
→{{header|Wren}}: Minor tidy
Alpha bravo (talk | contribs) (Added AutoHotkey) |
m (→{{header|Wren}}: Minor tidy) |
||
(15 intermediate revisions by 12 users not shown) | |||
Line 1:
{{task|Matrices}}
A pascal matrix is a two-dimensional square matrix holding numbers from [[Pascal's triangle]], also known as [[Evaluate binomial coefficients|binomial coefficients]] and which can be shown as <big><sup>n</sup>C<sub>r</sub>.</big>
Line 44:
The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F pascal_upp(n)
V s = [[0] * n] * n
s[0] = [1] * n
Line 80:
pp(pascal_low(n))
print("\nSymmetric:")
pp(pascal_sym(n))</
{{out}}
Line 107:
=={{header|360 Assembly}}==
<
PASCMATR CSECT
USING PASCMATR,R13 base register
Line 240:
XDEC DS CL12 temp
YREGS
END PASCMATR</
{{out}}
<pre>
Line 261:
1 4 10 20 35
1 5 15 35 70
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE FUNC Index(BYTE i,j,dim)
RETURN (i*dim+j)
PROC PascalUpper(BYTE ARRAY mat BYTE dim)
BYTE i,j
FOR i=0 TO dim-1
DO
FOR j=0 TO dim-1
DO
IF i>j THEN
mat(Index(i,j,dim))=0
ELSEIF i=j OR i=0 THEN
mat(Index(i,j,dim))=1
ELSE
mat(Index(i,j,dim))=mat(Index(i-1,j-1,dim))+mat(Index(i,j-1,dim))
FI
OD
OD
RETURN
PROC PascalLower(BYTE ARRAY mat BYTE dim)
BYTE i,j
FOR i=0 TO dim-1
DO
FOR j=0 TO dim-1
DO
IF i<j THEN
mat(Index(i,j,dim))=0
ELSEIF i=j OR j=0 THEN
mat(Index(i,j,dim))=1
ELSE
mat(Index(i,j,dim))=mat(Index(i-1,j-1,dim))+mat(Index(i-1,j,dim))
FI
OD
OD
RETURN
PROC PascalSymmetric(BYTE ARRAY mat BYTE dim)
BYTE i,j
FOR i=0 TO dim-1
DO
FOR j=0 TO dim-1
DO
IF i=0 OR j=0 THEN
mat(Index(i,j,dim))=1
ELSE
mat(Index(i,j,dim))=mat(Index(i-1,j,dim))+mat(Index(i,j-1,dim))
FI
OD
OD
RETURN
PROC PrintMatrix(BYTE ARRAY mat BYTE dim)
BYTE i,j,v
FOR i=0 TO dim-1
DO
FOR j=0 TO dim-1
DO
v=mat(Index(i,j,dim))
IF v<10 THEN
Print(" ")
ELSEIF v<100 THEN
Print(" ")
FI
PrintB(v)
OD
PutE()
OD
RETURN
PROC Main()
BYTE ARRAY mat(25)
BYTE dim=[5]
PrintE("Pascal upper matrix:")
PascalUpper(mat,dim)
PrintMatrix(mat,dim)
PutE()
PrintE("Pascal lower matrix:")
PascalLower(mat,dim)
PrintMatrix(mat,dim)
PutE()
PrintE("Pascal symmetric matrix:")
PascalSymmetric(mat,dim)
PrintMatrix(mat,dim)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal_matrix_generation.png Screenshot from Atari 8-bit computer]
<pre>
Pascal upper matrix:
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
Pascal lower matrix:
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
Pascal symmetric matrix:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
</pre>
=={{header|Ada}}==
<
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
Line 348 ⟶ 466:
Put("Symmetric:"); New_Line(1);
Print(Symmetric(n));
end PascalMatrix;</
{{out}}
<pre>What dimension Pascal matrix would you like? 5
Line 371 ⟶ 489:
=={{header|ALGOL 68}}==
<
# returns an upper Pascal matrix of size n #
PROC upper pascal matrix = ( INT n )[,]INT:
Line 431 ⟶ 549:
print( ( "symmetric:", newline ) ); print matrix( symmetric pascal matrix( 5 ), 2 )
END</
{{out}}
<pre>
Line 456 ⟶ 574:
=={{header|ALGOL W}}==
{{Trans|ALGOL_68}}
<
% initialises m to an upper Pascal matrix of size n %
% the bounds of m must be at least 1 :: n, 1 :: n %
Line 521 ⟶ 639:
end
end.</
{{out}}
<pre>
Line 546 ⟶ 664:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
lower ← ⍉(∘.!⍨¯1+⍳)
symmetric ← (⊢![1]∘.+⍨)¯1+⍳</
{{out}}
<pre style='line-height:normal'>
Line 562 ⟶ 680:
=={{header|AppleScript}}==
By composition of generic functions:
<
-- pascalMatrix :: ((Int, Int) -> (Int, Int)) -> Int -> [[Int]]
Line 897 ⟶ 1,015:
return lst
end tell
end zipWith</
{{Out}}
<pre>Lower
Line 921 ⟶ 1,039:
=={{header|AutoHotkey}}==
<
MsgBox, 262144, ,% ""
. "Pascal upper-triangular :`n" show(Pascal_Upper(n))
Line 985 ⟶ 1,103:
}
return obj
}</
{{out}}
<pre>Pascal upper-triangular :
Line 1,009 ⟶ 1,127:
=={{header|BASIC}}==
<
20 PRINT "Lower-triangular matrix:": GOSUB 200: GOSUB 100
30 PRINT "Upper-triangular matrix:": GOSUB 300: GOSUB 100
Line 1,043 ⟶ 1,161:
420 IF X=1 OR Y=1 THEN M(X,Y)=1 ELSE M(X,Y)=M(X-1,Y)+M(X,Y-1)
430 NEXT Y,X
440 RETURN</
{{out}}
<pre>Lower-triangular matrix:
Line 1,067 ⟶ 1,185:
=={{header|BCPL}}==
<
manifest $( size = 5 $)
Line 1,119 ⟶ 1,237:
writes("*NSymmetric matrix:*N")
symmetric(mat, size) ; writemat(mat, size, 2)
$)</
{{out}}
<pre>Upper-triangular matrix:
Line 1,141 ⟶ 1,259:
1 4 10 20 35
1 5 15 35 70</pre>
=={{header|BQN}}==
<code>C</code> is the combinations function, taken from BQNcrate. The rest of the problem is simple with table (<code>⌜</code>).
<syntaxhighlight lang="bqn">C←(-÷○(×´)1⊸+)⟜↕
Upr←C˜⌜˜↕
Lwr←C⌜˜↕
Sym←(+C⊣)⌜˜↕</syntaxhighlight>
<syntaxhighlight lang="bqn"> Upr 5
┌─
╵ 1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
┘
Lwr 5
┌─
╵ 1 0 0 0 0
1 1 0 0 0
1 2 1 0 0
1 3 3 1 0
1 4 6 4 1
┘
Sym 5
┌─
╵ 1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
┘</syntaxhighlight>
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 1,217 ⟶ 1,368:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,241 ⟶ 1,392:
=={{header|C sharp}}==
<
public static class PascalMatrixGeneration
Line 1,306 ⟶ 1,457:
}
}</
{{out}}
<pre>
Line 1,329 ⟶ 1,480:
=={{header|C++}}==
{{works with|GCC|version 7.2.0 (Ubuntu 7.2.0-8ubuntu3.2) }}
<
#include <vector>
Line 1,386 ⟶ 1,537:
std::cout << "PASCAL SYMMETRIC MATRIX" << std::endl;
print_matrix(pascal_symmetric(5));
}</
{{out}}
<pre>
Line 1,410 ⟶ 1,561:
=={{header|Clojure}}==
<
(reduce #(quot (* %1 (inc (- n %2))) %2)
1
Line 1,447 ⟶ 1,598:
(println)
(println "Symmetric:")
(run! println (pascal-symmetric n)))</
{{out}}
<pre>=> (pascal-matrix 5)
Line 1,470 ⟶ 1,621:
(1 4 10 20 35)
(1 5 15 35 70)</pre>
=={{header|CLU}}==
<syntaxhighlight lang="clu">matrix = array[array[int]]
make_matrix = proc (gen: proctype (int,int,matrix) returns (int),
size: int) returns (matrix)
m: matrix := matrix$fill_copy(0, size, array[int]$fill(0, size, 0))
for y: int in int$from_to(0, size-1) do
for x: int in int$from_to(0, size-1) do
m[y][x] := gen(x,y,m)
end
end
return(m)
end make_matrix
lower = proc (x,y: int, m: matrix) returns (int)
if x>y then return(0)
elseif x=y | x=0 then return(1)
else return( m[y-1][x-1] + m[y-1][x] )
end
end lower
upper = proc (x,y: int, m: matrix) returns (int)
if x<y then return(0)
elseif x=y | y=0 then return(1)
else return( m[y-1][x-1] + m[y][x-1] )
end
end upper
symmetric = proc (x,y: int, m: matrix) returns (int)
if x=0 | y=0 then return(1)
else return(m[y][x-1] + m[y-1][x])
end
end symmetric
print_matrix = proc (s: stream, m: matrix, w: int)
for line: array[int] in matrix$elements(m) do
for item: int in array[int]$elements(line) do
stream$putright(s, int$unparse(item), w)
stream$putc(s, ' ')
end
stream$putl(s, "")
end
end print_matrix
start_up = proc ()
po: stream := stream$primary_output()
stream$putl(po, "Upper-triangular matrix:")
print_matrix(po, make_matrix(upper,5), 1)
stream$putl(po, "\nLower-triangular matrix:")
print_matrix(po, make_matrix(lower,5), 1)
stream$putl(po, "\nSymmetric matrix:")
print_matrix(po, make_matrix(symmetric,5), 2)
end start_up</syntaxhighlight>
{{out}}
<pre>Upper-triangular matrix:
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
Lower-triangular matrix:
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
Symmetric matrix:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</pre>
=={{header|Common Lisp}}==
<
(dotimes (i n)
(setf (aref a i 0) 1))
Line 1,536 ⟶ 1,765:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</
=={{header|D}}==
{{trans|Python}}
<
auto binomialCoeff(in uint n, in uint k) pure nothrow {
Line 1,566 ⟶ 1,795:
writefln("\nLower:\n%(%(%2d %)\n%)", pascalLow(n));
writefln("\nSymmetric:\n%(%(%2d %)\n%)", pascalSym(n));
}</
{{out}}
<pre>Upper:
Line 1,591 ⟶ 1,820:
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Pascal_matrix_generation Pascal].
=={{header|Elixir}}==
<
defp ij(n), do: for i <- 1..n, j <- 1..n, do: {i,j}
Line 1,637 ⟶ 1,867:
Pascal.lower_triangle(5)
IO.puts "Pascal symmetric matrix:"
Pascal.symmetic_triangle(5)</
{{out}}
Line 1,669 ⟶ 1,899:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(n,
LAMBDA(f,
Line 1,703 ⟶ 1,933:
)
)
)</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(f,
LAMBDA(a,
Line 1,718 ⟶ 1,948:
ID
=LAMBDA(x, x)</
{{Out}}
Line 1,933 ⟶ 2,163:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<
math.matrices prettyprint sequences ;
Line 1,948 ⟶ 2,178:
[ upper "Upper:" ]
[ symmetric "Symmetric:" ] tri
[ print simple-table. nl ] 2tri@</
{{out}}
<pre>
Line 1,971 ⟶ 2,201:
1 4 10 20 35
1 5 15 35 70
</pre>
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">&a; {set mode to 0-indexed matrices}
Func Pasmat( n, t ) =
;{create a Pascal matrix of size n by n}
;{t=0 -> upper triangular, 1 -> lower triangular,2->symmetric}
Array m[n, n]; {result is stored in array m}
if t = 0 then
[m]:=[<i=0,n-1><j=0,n-1> Bin(j,i) ];
fi;
if t = 1 then
[m]:=[<i=0,n-1><j=0,n-1> Bin(i,j) ];
fi;
if t = 2 then
[m]:=[<i=0,n-1><j=0,n-1> Bin(i+j,i) ];
fi;
.;
Pasmat(5, 0);
!!([m);
!;
Pasmat(5, 1);
!!([m);
!;
Pasmat(5, 2);
!!([m);</syntaxhighlight>
{{out}}<pre>
1, 1, 1, 1, 1,
0, 1, 2, 3, 4,
0, 0, 1, 3, 6,
0, 0, 0, 1, 4,
0, 0, 0, 0, 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
1, 1, 1, 1, 1,
1, 2, 3, 4, 5,
1, 3, 6, 10, 15,
1, 4, 10, 20, 35,
1, 5, 15, 35, 70
</pre>
Line 1,976 ⟶ 2,251:
The following program uses features of Fortran 2003.
<
implicit none
Line 2,053 ⟶ 2,328:
a = pascal_symmetric(n)
call print_matrix(a)
end program</
<syntaxhighlight lang="text"> Size?
5
Lower Pascal Matrix
Line 2,074 ⟶ 2,349:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
sub print_matrix( M() as integer )
'displays a matrix
for row as integer = 0 to ubound(M, 1)
for col as integer = 0 to ubound(M, 2)
print using "#### ";M(row, col);
next col
print
next row
return
end sub
function fact( n as uinteger ) as uinteger
'quick and dirty factorial
if n<2 then return 1 else return n*fact(n-1)
end function
function nCp( n as uinteger, p as uinteger ) as uinteger
'quick and dirty binomial
if p>n then return 0 else return fact(n)/(fact(p)*fact(n-p))
end function
sub make_pascal( M() as integer, typ as const ubyte )
'allocate the matrix first
'typ 0 = jCi, 1=iCj, 2=(j+i)Ci
for i as uinteger = 0 to ubound(M,1)
for j as uinteger = 0 to ubound(M,2)
select case typ
case 0
M(i,j) = nCp(j, i)
case 1
M(i,j) = nCp(i, j)
case 2
M(i,j) = nCp(i + j, j)
case else
M(i, j) = 0
end select
next j
next i
return
end sub
dim as integer M(0 to 4, 0 to 4)
print "Upper triangular"
make_pascal( M(), 0 )
print_matrix( M() )
print "Lower triangular"
make_pascal( M(), 1 )
print_matrix( M() )
print "Symmetric"
make_pascal( M(), 2 )
print_matrix( M() )
print "Technically the matrix needn't be square :)"
dim as integer Q(0 to 4, 0 to 9)
make_pascal( Q(), 2 )
print_matrix( Q() )</syntaxhighlight>
{{out}}<pre>
Upper triangular
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
Lower triangular
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
Symmetric
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
Technically the matrix needn't be square :)
1 1 1 1 1 1 1 1 1 1
1 2 3 4 5 6 7 8 9 10
1 3 6 10 15 21 28 36 45 55
1 4 10 20 35 56 84 120 165 220
1 5 15 35 70 126 210 330 495 715
</pre>
=={{header|Frink}}==
Frink has built-in functions for efficiently calculating arbitrary-sized binomial coefficients, initializing matrices based on a function, and formatting matrices using Unicode characters.
<syntaxhighlight lang="frink">println[formatMatrix[new array[[5,5], {|r,c| binomial[c,r]}]]]
println[formatMatrix[new array[[5,5], {|r,c| binomial[r,c]}]]]
println[formatMatrix[new array[[5,5], {|r,c| binomial[r+c, c]}]]]</syntaxhighlight>
{{out}}
<pre>
┌ ┐
│1 1 1 1 1│
│ │
│0 1 2 3 4│
│ │
│0 0 1 3 6│
│ │
│0 0 0 1 4│
│ │
│0 0 0 0 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│
└ ┘
┌ ┐
│1 1 1 1 1│
│ │
│1 2 3 4 5│
│ │
│1 3 6 10 15│
│ │
│1 4 10 20 35│
│ │
│1 5 15 35 70│
└ ┘
</pre>
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 2,158 ⟶ 2,559:
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}</
{{out}}
Line 2,185 ⟶ 2,586:
=={{header|Haskell}}==
<
import System.Environment (getArgs)
import Text.Printf (printf)
Line 2,219 ⟶ 2,620:
printMat "Upper triangular" $ pascUp n
printMat "Symmetric" $ pascSym n
_ -> error "Usage: pascmat <number>"</
{{out}}
Line 2,253 ⟶ 2,654:
Or, in terms of binomial coefficients and coordinate transformations:
<
import Data.Bifunctor (bimap)
import Data.Ix (range)
Line 2,297 ⟶ 2,698:
<*> [matrixSize]
)
)</
{{Out}}
<pre>Lower
Line 2,321 ⟶ 2,722:
=={{header|J}}==
<syntaxhighlight lang="j"> !/~ i. 5
1 1 1 1 1
0 1 2 3 4
Line 2,339 ⟶ 2,739:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</
Explanation:
Line 2,349 ⟶ 2,749:
For the final example we use an unadorned <code>!</code> but prepare tables for its x and y values. Its right argument is a sum table, and its left argument is a left identity table. They look like this:
<
0 1 2 3 4
1 2 3 4 5
Line 2,360 ⟶ 2,760:
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4</
The parenthesis in these last two examples are redundant - they could have been omitted without changing the result, but were left in place for emphasis.
Line 2,367 ⟶ 2,767:
Translation of [[Pascal_matrix_generation#Python|Python]] via [[Pascal_matrix_generation#D|D]]
{{works with|Java|8}}
<
import java.util.List;
import java.util.function.Function;
Line 2,411 ⟶ 2,811:
print("Symmetric:", pascalSym(5));
}
}</
<pre>Upper:
Line 2,438 ⟶ 2,838:
{{Trans|Haskell}}
===ES6===
<
'use strict';
Line 2,727 ⟶ 3,127:
// MAIN ---
return main();
})();</
{{Out}}
<pre>Lower:
Line 2,752 ⟶ 3,152:
=={{header|jq}}==
{{works with|jq|1.4}}
<
# Note: 'transpose' is defined in recent versions of jq
Line 2,774 ⟶ 3,174:
def pad(n): tostring | (n - length) * " " + .;
def row: reduce .[] as $x (""; . + ($x|pad(4)));
reduce .[] as $row (""; . + "\n\($row|row)");</
<
def pascal_upper:
. as $n
Line 2,793 ⟶ 3,193:
| reduce range(1; $n) as $i
(.; reduce range(1; $n) as $j
(.; .[$i][$j] = .[$i-1][$j] + .[$i][$j-1]) ) ;</
'''Example''':
<
| ("\nUpper:", (pascal_upper | pp),
"\nLower:", (pascal_lower | pp),
"\nSymmetric:", (pascal_symmetric | pp)
)</
{{out}}
<
Upper:
Line 2,825 ⟶ 3,225:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</
=={{header|Julia}}==
Julia has a built-in <code>binomial</code> function to compute the binomial coefficients, and we can construct the Pascal matrices with this function using list comprehensions:
<
5×5 Array{Int64,2}:
1 1 1 1 1
Line 2,852 ⟶ 3,252:
1 4 10 20 35
1 5 15 35 70
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun binomial(n: Int, k: Int): Int {
Line 2,886 ⟶ 3,286:
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}</
{{out}}
Line 2,913 ⟶ 3,313:
=={{header|Lua}}==
<
local f = 1
for i = 2, n do
Line 2,959 ⟶ 3,359:
for _, form in pairs({"upper", "lower", "symmetric"}) do
show(pascalMatrix(form, 5))
end</
{{out}}
<pre>Upper:
Line 2,983 ⟶ 3,383:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
PascalUT := proc(n::integer)
local M := Matrix(n,n):
Line 3,030 ⟶ 3,430:
Pascal(5);
</syntaxhighlight>
{{out}}<pre>
[1 1 1 1 1]
Line 3,067 ⟶ 3,467:
One solution is to generate a symmetric Pascal matrix then use the built in method to
compute the upper Pascal matrix. This would be done as follows:
<
upperPascal[size_] := CholeskyDecomposition[symPascal@size]
Line 3,075 ⟶ 3,475:
Column[MapThread[
Labeled[Grid[#1@5], #2, Top] &, {{upperPascal, lowerPascal,
symPascal}, {"Upper", "Lower", "Symmetric"}}]]</
{{out}}
<pre>
Line 3,101 ⟶ 3,501:
It is also possible to directly compute a lower Pascal matrix as follows:
<
MatrixExp[
SparseArray[{Band[{2, 1}] -> Range[size - 1]}, {size, size}]]]</
But since the builtin function MatrixExp works by first computing eigenvalues this is
likely to be slower for large Pascal matrices
=={{header|MATLAB}}==
{{trans|Mathematica/Wolfram_Language}}
<syntaxhighlight lang="MATLAB">
clear all;close all;clc;
size = 5; % size of Pascal matrix
% Generate the symmetric Pascal matrix
symPascalMatrix = symPascal(size);
% Generate the upper triangular Pascal matrix
upperPascalMatrix = upperPascal(size);
% Generate the lower triangular Pascal matrix
lowerPascalMatrix = lowerPascal(size);
% Display the matrices
disp('Upper Pascal Matrix:');
disp(upperPascalMatrix);
disp('Lower Pascal Matrix:');
disp(lowerPascalMatrix);
disp('Symmetric Pascal Matrix:');
disp(symPascalMatrix);
function symPascal = symPascal(size)
% Generates a symmetric Pascal matrix of given size
row = ones(1, size);
symPascal = row;
for k = 2:size
row = cumsum(row);
symPascal = [symPascal; row];
end
end
function upperPascal = upperPascal(size)
% Generates an upper triangular Pascal matrix using Cholesky decomposition
upperPascal = chol(symPascal(size));
end
function lowerPascal = lowerPascal(size)
% Generates a lower triangular Pascal matrix using Cholesky decomposition
lowerPascal = chol(symPascal(size))';
end
</syntaxhighlight>
{{out}}
<pre>
Upper Pascal Matrix:
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
Lower Pascal Matrix:
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
Symmetric Pascal Matrix:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
</pre>
=={{header|Maxima}}==
Using built-in functions genmatrix and binomial
<syntaxhighlight lang="maxima">
/* Function that returns a lower Pascal matrix */
lower_pascal(n):=genmatrix(lambda([i,j],binomial(i-1,j-1)),n,n)$
/* Function that returns an upper Pascal matrix */
upper_pascal(n):=genmatrix(lambda([i,j],binomial(j-1,i-1)),n,n)$
/* Function that returns a symmetric Pascal matrix (the matricial multiplication of a lower and an upper of the same size) */
symmetric_pascal(n):=lower_pascal(n).upper_pascal(n)$
/* Test cases */
lower_pascal(5);
upper_pascal(5);
symmetric_pascal(5);
</syntaxhighlight>
{{out}}
<pre>
matrix(
[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]
)
matrix(
[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]
)
matrix(
[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]
)
</pre>
=={{header|Nim}}==
Using the function “binom” from module “math” of standard library.
<
type SquareMatrix = seq[seq[Natural]]
Line 3,150 ⟶ 3,666:
print pascalLowerTriangular(5)
echo "\nSymmetric:"
print pascalSymmetric(5)</
{{out}}
Line 3,175 ⟶ 3,691:
=={{header|PARI/GP}}==
<
Pl(n)={matpascal(n-1)}
printf("%d",Pl(5))
</syntaxhighlight>
{{out}}
<pre>
Line 3,191 ⟶ 3,707:
[1 4 6 4 1]
</pre>
<
Pu(n)={Pl(n)~}
printf("%d",Pu(5))
</syntaxhighlight>
{{out}}
<pre>
Line 3,207 ⟶ 3,723:
[0 0 0 0 1]
</pre>
<
Ps(n)={matrix(n,n,n,g,binomial(n+g-2,n-1))}
printf("%d",Ps(5))
</syntaxhighlight>
{{out}}
<pre>
Line 3,225 ⟶ 3,741:
=={{header|Pascal}}==
<
const N = 5;
Line 3,294 ⟶ 3,810:
writeln('');
readln;
end.</
{{out}}
<pre>Upper:
Line 3,318 ⟶ 3,834:
=={{header|Perl}}==
<
use warnings;
use strict;
Line 3,377 ⟶ 3,893:
pretty(lower(5, 5));
say '-' x 14;
pretty(symmetric(5, 5));</
{{out}}
<pre>1, 1, 1, 1, 1
Line 3,399 ⟶ 3,915:
=={{header|Phix}}==
{{trans|Fortran}}
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">pascal_upper</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 3,445 ⟶ 3,961:
<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;">"=== Pascal symmetrical matrix ===\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">pp</span><span style="color: #0000FF;">(</span><span style="color: #000000;">pascal_symmetric</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">))</span>
<!--</
{{out}}
<pre>
Line 3,469 ⟶ 3,985:
=={{header|PicoLisp}}==
<
Low '(A B)
Upp '(B A)
Line 3,498 ⟶ 4,014:
(pascal 4 Low)
(pascal 4 Upp)
(pascal 4 Sym)</
{{out}}
<pre> 1 0 0 0 0
Line 3,519 ⟶ 4,035:
=={{header|PL/I}}==
Version I
<syntaxhighlight lang="pli">PASCAL_MATRIX: PROCEDURE OPTIONS (MAIN); /* derived from Fortran version 18 Decenber 2021 */
pascal_lower: procedure(a);
declare a(*,*) fixed binary;
declare (n, i, j) fixed binary;
n = hbound(a,1);
a = 0;
a(*, 1) = 1;
do i = 2 to n;
do j = 2 to i;
a(i, j) = a(i - 1, j) + a(i - 1, j - 1);
end;
end;
end pascal_lower;
pascal_upper: procedure(a);
declare a(*,*) fixed binary;
declare (n, i, j) fixed binary;
n = hbound(a,1);
a = 0;
a(1, *) = 1;
do i = 2 to n;
do j = 2 to i;
a(j, i) = a(j, i - 1) + a(j - 1, i - 1);
end;
end;
end pascal_upper;
pascal_symmetric: procedure(a);
declare a(*,*) fixed binary;
declare (n, i, j) fixed binary;
n = hbound(a,1);
a = 0;
a(*, 1) = 1;
a(1, *) = 1;
do i = 2 to n;
do j = 2 to n;
a(i, j) = a(i - 1, j) + a(i, j - 1);
end;
end;
end pascal_symmetric;
declare n fixed binary;
put ('Size of matrix?');
get (n);
begin;
declare a(n, n) fixed binary;
put skip list ('Lower Pascal Matrix');
call pascal_lower(a);
put edit (a) (skip, (n) f(3) );
put skip list ('Upper Pascal Matrix');
call pascal_upper(a);
put edit (a) (skip, (n) f(3) );
put skip list ('Symmetric Pascal Matrix');
call pascal_symmetric(a);
put edit (a) (skip, (n) f(3) );
end;
end PASCAL_MATRIX;
</syntaxhighlight>
{{out}}
<pre>
Size of matrix?
Lower Pascal Matrix
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
Upper Pascal Matrix
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
Symmetric Pascal Matrix
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
</pre>
Version II
<syntaxhighlight lang="pli">
PASCAL_MATRIX: PROCEDURE OPTIONS (MAIN); /* derived from Fortran version 18 Decenber 2021 */
define structure 1 array, 2 b(5,5) fixed binary;
declare A type (array);
pascal_lower: procedure() returns (type(array));
declare A type (array);
declare (n, i, j) fixed binary;
n = hbound(A.b,1);
A.b = 0;
A.b(*, 1) = 1;
do i = 2 to n;
do j = 2 to i;
A.b(i, j) = A.b(i - 1, j) + A.b(i - 1, j - 1);
end;
end;
return (A);
end pascal_lower;
pascal_upper: procedure() returns (type(array));
declare A type (array);
declare (n, i, j) fixed binary;
n = hbound(A.b,1);
A.b = 0;
A.b(1, *) = 1;
do i = 2 to n;
do j = 2 to i;
A.b(j, i) = A.b(j, i - 1) + A.b(j - 1, i - 1);
end;
end;
return (A);
end pascal_upper;
pascal_symmetric: procedure() returns (type(array));
declare A type (array);
declare (n, i, j) fixed binary;
n = hbound(A.b,1);
A.b = 0;
A.b(*, 1) = 1;
A.b(1, *) = 1;
do i = 2 to n;
do j = 2 to n;
A.b(i, j) = A.b(i - 1, j) + A.b(i, j - 1);
end;
end;
return (A);
end pascal_symmetric;
declare C type (array);
declare n fixed binary initial ((hbound(C.b,1)));
put skip list ('Lower Pascal Matrix');
C = pascal_lower();
put edit (C.b) (skip, (n) f(3) );
put skip list ('Upper Pascal Matrix');
C = pascal_upper();
put edit (C.b) (skip, (n) f(3) );
put skip list ('Symmetric Pascal Matrix');
C = pascal_symmetric();
put edit (C.b) (skip, (n) f(3) );
end PASCAL_MATRIX;
</syntaxhighlight>
{{trans|Rexx}}
<
pat: Proc Options(main);
Dcl (HBOUND,MAX,RIGHT) Builtin;
Line 3,606 ⟶ 4,277:
End;
End;</
{{out}}
<pre>Pascal upper triangular matrix
Line 3,630 ⟶ 4,301:
=={{header|PureBasic}}==
<
Define.i x=5, I, J
Line 3,683 ⟶ 4,354:
Input()
End</
{{out}}
<pre>Upper:
Line 3,711 ⟶ 4,382:
===Python: Procedural===
'''Summing adjacent values''':
<
def pascal_upp(n):
Line 3,740 ⟶ 4,411:
pp(pascal_low(n))
print("\nSymmetric:")
pp(pascal_sym(n))</
{{out}}
Line 3,767 ⟶ 4,438:
'''Using a binomial coefficient generator function''':
<
result = 1
for i in range(1, k+1):
Line 3,780 ⟶ 4,451:
def pascal_sym(n):
return [[binomialCoeff(i+j, i) for j in range(n)] for i in range(n)]</
{{out}}
Line 3,787 ⟶ 4,458:
===Python: Functional===
Defining binomial coefficients in terms of reduce:
<
from functools import reduce
Line 3,922 ⟶ 4,593:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Symmetric:
Line 3,946 ⟶ 4,617:
=={{header|R}}==
<
a <- matrix(0, n, n)
a[, 1] <- 1
Line 3,982 ⟶ 4,653:
}
a
}</
The results follow
<
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
Line 4,013 ⟶ 4,684:
[3,] 1 3 6 10 15
[4,] 1 4 10 20 35
[5,] 1 5 15 35 70</
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(require math/number-theory)
Line 4,041 ⟶ 4,711:
(printf "Upper:~%~a~%" (matrix->string (pascal-upper-matrix 5)))
(printf "Lower:~%~a~%" (matrix->string (pascal-lower-matrix 5)))
(printf "Symmetric:~%~a~%" (matrix->string (pascal-symmetric-matrix 5)))</
{{out}}
<pre>Upper:
Line 4,070 ⟶ 4,740:
{{Works with|rakudo|2016-12}}
Here is a rather more general solution than required. The <tt>grow-matrix</tt> function will grow any N by N matrix into an N+1 x N+1 matrix, using any function of the three leftward/upward neighbors, here labelled "West", "North", and "Northwest". We then define three iterator functions that can grow Pascal matrices, and use those iterators to define three constants, each of which is an infinite sequence of ever-larger Pascal matrices. Normal subscripting then pulls out the ones of the specified size.
<syntaxhighlight lang="raku"
sub grow-matrix(@matrix, &func) {
my $n = @matrix.shape eq '*' ?? 1 !! @matrix.shape[0];
Line 4,106 ⟶ 4,776:
}
say '';
}</
{{out}}
<pre> 1 1 1 1 1
Line 4,129 ⟶ 4,799:
===separate generation===
Commentary: <sup>1</sup>/<sub>3</sub> of the REXX program deals with the displaying of the matrix.
<
numeric digits 50 /*be able to calculate huge factorials.*/
parse arg N . /*obtain the optional matrix size (N).*/
Line 4,163 ⟶ 4,833:
say $ || left(',', r\==s)left("]", r==s) /*show row. */
end /*r*/
return</
{{out|output|text= when using the default input:}}
<pre>
Line 4,190 ⟶ 4,860:
===consolidated generation===
This REXX version uses a consolidated generation subroutine, even though this Rosetta Code implies to use '''functions''' (instead of a single function).
<
numeric digits 50 /*be able to calculate huge factorials.*/
parse arg N . /*obtain the optional matrix size (N).*/
Line 4,225 ⟶ 4,895:
say $ || left(',', r\==s)left(']', r==s) /*show row. */
end /*r*/
return</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
=={{header|Ring}}==
<
# Project : Pascal matrix generation
Line 4,303 ⟶ 4,973:
see nl
next
</syntaxhighlight>
Output:
<pre>
Line 4,326 ⟶ 4,996:
1 4 10 20 35
1 5 15 35 70
</pre>
=={{header|RPL}}==
≪ → n
≪ { } n + n + 0 CON
1 n '''FOR''' h 1 n '''FOR''' j
'''IF''' h j ≥ '''THEN''' { } j + h + h 1 - j 1 - COMB PUT '''END'''
'''NEXT NEXT'''
≫ ≫ ‘'''PASUT'''’ STO
≪ '''PASUT''' TRN ≫ ‘'''PASLT'''’ STO
≪ → n
≪ { } n + n + 0 CON
1 n '''FOR''' h 1 n '''FOR''' j
{ } j + h + h j + 2 - j 1 - COMB PUT
'''NEXT NEXT'''
≫ ≫ ‘'''PASYM'''’ STO
5 '''PASUT''' 5 '''PASLT''' 5 '''PASYM'''
{{out}}
<pre>
3: [[ 1 1 1 1 1 ]
[ 0 1 2 3 4 ]
[ 0 0 1 3 6 ]
[ 0 0 0 1 4 ]
[ 0 0 0 0 1 ]]
2: [[ 1 0 0 0 0 ]
[ 1 1 0 0 0 ]
[ 1 2 1 0 0 ]
[ 1 3 3 1 0 ]
[ 1 4 6 4 1 ]]
1: [[ 1 1 1 1 1 ]
[ 1 2 3 4 5 ]
[ 1 3 6 10 15 ]
[ 1 4 10 20 35 ]
[ 1 5 15 35 70 ]]
</pre>
=={{header|Ruby}}==
'''Summing adjacent values:'''
<
require 'pp'
Line 4,339 ⟶ 5,046:
pp ng; puts
g.each{|i| g.each{|j| ng[i][j] = (i==0 or j==0) ? 1 : ng[i-1][j ]+ng[i][j-1]}}
pp ng</
{{out}}
<pre>
Line 4,362 ⟶ 5,069:
===Binomial coefficient:===
<
def binomial_coeff(n,k) (1..k).inject(1){|res,i| res * (n-i+1) / i} end
Line 4,377 ⟶ 5,084:
puts "\nPascal symmetric matrix:"
pp pascal_symmetric(5)</
{{out}}
Line 4,404 ⟶ 5,111:
=={{header|Scala}}==
<
object pascal{
Line 4,468 ⟶ 5,175:
}
}
</syntaxhighlight>
=={{header|Scheme}}==
Using SRFI-25:
<
(define-syntax dotimes
Line 4,524 ⟶ 5,231:
(display (array-ref a row col))
(display #\space))
(newline))))</
<
{{out}}
<pre>
Line 4,535 ⟶ 5,242:
0 0 0 0 1
</pre>
<
{{out}}
<pre>
Line 4,544 ⟶ 5,251:
1 4 6 4 1
</pre>
<
{{out}}
<pre>
Line 4,556 ⟶ 5,263:
=={{header|Sidef}}==
{{trans|Raku}}
<
var m = matrix
var s = m.len
Line 4,584 ⟶ 5,291:
functions.map { |f|
f(4).map { .map{ '%2s' % _ }.join(' ') }.join("\n")
}.join("\n\n").say</
{{out}}
<pre>
Line 4,607 ⟶ 5,314:
=={{header|Stata}}==
Here are variants for the lower matrix.
<
function pascal1(n) {
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
Line 4,637 ⟶ 5,343:
return(s)
}
end</
One could trivially write functions for the upper matrix (same operations with transposed matrices).
Line 4,643 ⟶ 5,349:
immediately deduced:
<
: a
1 2 3 4 5
Line 4,673 ⟶ 5,379:
4 | 1 4 10 20 |
5 | 1 5 15 35 70 |
+--------------------------+</
The last is a symmetric matrix, but Stata only shows the lower triangular part of symmetric matrices.
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">
package require math
Line 4,712 ⟶ 5,418:
pascal::$type 5
}
</syntaxhighlight>
{{out}}
<pre>
Line 4,739 ⟶ 5,445:
=={{header|VBA}}==
{{trans|Phix}}
<
Private Function pascal_upper(n As Integer)
Dim res As Variant: ReDim res(n, n)
Line 4,787 ⟶ 5,493:
Debug.Print "=== Pascal symmetrical matrix ==="
pp pascal_symmetric(5)
End Sub</
<pre>=== Pascal upper matrix ===
1 1 1 1 1
Line 4,808 ⟶ 5,514:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function pascal_upper(i,j)
WScript.StdOut.Write "Pascal Upper"
Line 4,874 ⟶ 5,580:
Call pascal_lower(0,4)
Call pascal_symmetric(0,4)
</syntaxhighlight>
{{Out}}
Line 4,904 ⟶ 5,610:
{{libheader|Wren-math}}
{{libheader|Wren-matrix}}
<
import "./math" for Int
import "./matrix" for Matrix
var binomial = Fn.new { |n, k|
Line 4,945 ⟶ 5,651:
Fmt.mprint(pascalLowerTriangular.call(n), 2, 0)
System.print("\nPascal symmetric matrix:")
Fmt.mprint(pascalSymmetric.call(n), 2, 0)</
{{out}}
Line 4,969 ⟶ 5,675:
| 1 4 10 20 35|
| 1 5 15 35 70|
</pre>
=={{header|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0"> \Initialises M to an upper Pascal matrix of size N
\The bounds of M must be at least 1 :: N, 1 :: N
procedure UpperPascalMatrix ( M, N );
integer M, N, J, I;
begin
for J := 1 to N do M( 1, J ) := 1;
for I := 2 to N do begin
M( I, 1 ) := 0;
for J := 2 to N do M( I, J ) := M( I - 1, J - 1 ) + M( I, J - 1 )
end \for_I
end; \UpperPascalMatrix
\Initialises M to a lower Pascal matrix of size N
\The bounds of M must be at least 1 :: N, 1 :: N
procedure LowerPascalMatrix ( M, N );
integer M, N, I, J;
begin
for I := 1 to N do M( I, 1 ) := 1;
for J := 2 to N do begin
M( 1, J ) := 0;
for I := 2 to N do M( I, J ) := M( I - 1, J - 1 ) + M( I - 1, J )
end \for_J
end; \LowerPascalMatrix
\Initialises M to a symmetric Pascal matrix of size N
\The bounds of M must be at least 1 :: N, 1 :: N
procedure SymmetricPascalMatrix ( M, N );
integer M, N, I, J;
begin
for I := 1 to N do begin
M( I, 1 ) := 1;
M( 1, I ) := 1
end; \for_I
for J := 2 to N do for I := 2 to N do M( I, J ) := M( I, J - 1 ) + M( I - 1, J )
end; \SymmetricPascalMatrix
\Test the Pascal matrix procedures
\Print the matrix M with the specified field width
\The bounds of M must be at least 1 :: N, 1 :: N
procedure PrintMatrix ( M, N, FieldWidth );
integer M, N, I, J;
begin
Format(3, 0);
for I := 1 to N do begin
for J := 1 to N do RlOut(0, float( M( I, J ) ) );
CrLf(0)
end; \for_I
end; \PrintMatrix
integer M( 1+10, 1+10 );
integer N, W;
begin
N := 5; W := 2;
UpperPascalMatrix( M, N );
Text(0, "upper:^m^j" ); PrintMatrix( M, N, W );
LowerPascalMatrix( M, N );
Text(0, "lower:^m^j" ); PrintMatrix( M, N, W );
SymmetricPascalMatrix( M, N );
Text(0, "symmetric:^m^j" ); PrintMatrix( M, N, W )
end</syntaxhighlight>
{{out}}
<pre>
upper:
1 1 1 1 1
0 1 2 3 4
0 0 1 3 6
0 0 0 1 4
0 0 0 0 1
lower:
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
symmetric:
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
</pre>
=={{header|zkl}}==
{{trans|Python}}
<
fcn pascal_upp(n){ [[(i,j); n; n; '{ binomial(j,i) }]]:toMatrix(_) } // [[..]] is list comprehension
fcn pascal_low(n){ [[(i,j); n; n; binomial]]:toMatrix(_) }
Line 4,980 ⟶ 5,770:
cols:=ns.len().toFloat().sqrt().toInt();
ns.pump(List,T(Void.Read,cols-1),List.create)
}</
<
fmt:=("%3d "*m.len() + "\n").fmt;
m.pump(String,'wrap(col){ fmt(col.xplode()) });
Line 4,988 ⟶ 5,778:
println("Upper:\n", pascal_upp(N):prettyPrint(_));
println("Lower:\n", pascal_low(N):prettyPrint(_));
println("Symmetric:\n",pascal_sym(N):prettyPrint(_));</
{{out}}
<pre>
|