Pascal matrix generation: Difference between revisions

m
(→‎{{header|PL/I}}: New version added)
m (→‎{{header|Wren}}: Minor tidy)
(10 intermediate revisions by 9 users not shown)
Line 1:
{{task|Matrices}}
 
A pascal matrix is a two-dimensional square matrix holding numbers from &nbsp; [[Pascal's triangle]], &nbsp; also known as &nbsp; [[Evaluate binomial coefficients|binomial coefficients]] &nbsp; and which can be shown as &nbsp; <big><sup>n</sup>C<sub>r</sub>.</big>
Line 44:
The &nbsp; [[Cholesky decomposition]] &nbsp; 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)
 
<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))</langsyntaxhighlight>
 
{{out}}
Line 107:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Pascal matrix generation - 10/06/2018
PASCMATR CSECT
USING PASCMATR,R13 base register
Line 240:
XDEC DS CL12 temp
YREGS
END PASCMATR</langsyntaxhighlight>
{{out}}
<pre>
Line 264:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">BYTE FUNC Index(BYTE i,j,dim)
RETURN (i*dim+j)
 
Line 355:
PascalSymmetric(mat,dim)
PrintMatrix(mat,dim)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Pascal_matrix_generation.png Screenshot from Atari 8-bit computer]
Line 382:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">-- for I/O
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
Line 466:
Put("Symmetric:"); New_Line(1);
Print(Symmetric(n));
end PascalMatrix;</langsyntaxhighlight>
{{out}}
<pre>What dimension Pascal matrix would you like? 5
Line 489:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# returns an upper Pascal matrix of size n #
PROC upper pascal matrix = ( INT n )[,]INT:
Line 549:
print( ( "symmetric:", newline ) ); print matrix( symmetric pascal matrix( 5 ), 2 )
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 574:
=={{header|ALGOL W}}==
{{Trans|ALGOL_68}}
<langsyntaxhighlight lang="algolw">begin
% initialises m to an upper Pascal matrix of size n %
% the bounds of m must be at least 1 :: n, 1 :: n %
Line 639:
end
 
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 664:
=={{header|APL}}==
{{works with|Dyalog APL}}
<langsyntaxhighlight APLlang="apl">upper ← ∘.!⍨¯1+⍳
lower ← ⍉(∘.!⍨¯1+⍳)
symmetric ← (⊢![1]∘.+⍨)¯1+⍳</langsyntaxhighlight>
{{out}}
<pre style='line-height:normal'>
Line 680:
=={{header|AppleScript}}==
By composition of generic functions:
<langsyntaxhighlight AppleScriptlang="applescript">-- PASCAL MATRIX -------------------------------------------------------------
 
-- pascalMatrix :: ((Int, Int) -> (Int, Int)) -> Int -> [[Int]]
Line 1,015:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>Lower
Line 1,039:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">n := 5
MsgBox, 262144, ,% ""
. "Pascal upper-triangular :`n" show(Pascal_Upper(n))
Line 1,103:
}
return obj
}</langsyntaxhighlight>
{{out}}
<pre>Pascal upper-triangular :
Line 1,127:
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="basic">10 DEFINT A-Z: S=5: DIM M(S,S)
20 PRINT "Lower-triangular matrix:": GOSUB 200: GOSUB 100
30 PRINT "Upper-triangular matrix:": GOSUB 300: GOSUB 100
Line 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</langsyntaxhighlight>
{{out}}
<pre>Lower-triangular matrix:
Line 1,185:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
manifest $( size = 5 $)
 
Line 1,237:
writes("*NSymmetric matrix:*N")
symmetric(mat, size) ; writemat(mat, size, 2)
$)</langsyntaxhighlight>
{{out}}
<pre>Upper-triangular matrix:
Line 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">
<lang c>
#include <stdio.h>
#include <stdlib.h>
Line 1,335 ⟶ 1,368:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,359 ⟶ 1,392:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
 
public static class PascalMatrixGeneration
Line 1,424 ⟶ 1,457:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,447 ⟶ 1,480:
=={{header|C++}}==
{{works with|GCC|version 7.2.0 (Ubuntu 7.2.0-8ubuntu3.2) }}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
 
Line 1,504 ⟶ 1,537:
std::cout << "PASCAL SYMMETRIC MATRIX" << std::endl;
print_matrix(pascal_symmetric(5));
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,528 ⟶ 1,561:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn binomial-coeff [n k]
(reduce #(quot (* %1 (inc (- n %2))) %2)
1
Line 1,565 ⟶ 1,598:
(println)
(println "Symmetric:")
(run! println (pascal-symmetric n)))</langsyntaxhighlight>
{{out}}
<pre>=> (pascal-matrix 5)
Line 1,590 ⟶ 1,623:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">matrix = array[array[int]]
 
make_matrix = proc (gen: proctype (int,int,matrix) returns (int),
Line 1,644 ⟶ 1,677:
stream$putl(po, "\nSymmetric matrix:")
print_matrix(po, make_matrix(symmetric,5), 2)
end start_up</langsyntaxhighlight>
{{out}}
<pre>Upper-triangular matrix:
Line 1,668 ⟶ 1,701:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun pascal-lower (n &aux (a (make-array (list n n) :initial-element 0)))
(dotimes (i n)
(setf (aref a i 0) 1))
Line 1,732 ⟶ 1,765:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.bigint, std.range, std.algorithm;
 
auto binomialCoeff(in uint n, in uint k) pure nothrow {
Line 1,762 ⟶ 1,795:
writefln("\nLower:\n%(%(%2d %)\n%)", pascalLow(n));
writefln("\nSymmetric:\n%(%(%2d %)\n%)", pascalSym(n));
}</langsyntaxhighlight>
{{out}}
<pre>Upper:
Line 1,787 ⟶ 1,820:
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Pascal_matrix_generation Pascal].
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Pascal do
defp ij(n), do: for i <- 1..n, j <- 1..n, do: {i,j}
Line 1,833 ⟶ 1,867:
Pascal.lower_triangle(5)
IO.puts "Pascal symmetric matrix:"
Pascal.symmetic_triangle(5)</langsyntaxhighlight>
 
{{out}}
Line 1,865 ⟶ 1,899:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">PASCALMATRIX
=LAMBDA(n,
LAMBDA(f,
Line 1,899 ⟶ 1,933:
)
)
)</langsyntaxhighlight>
 
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<langsyntaxhighlight lang="lisp">FLIP
=LAMBDA(f,
LAMBDA(a,
Line 1,914 ⟶ 1,948:
 
ID
=LAMBDA(x, x)</langsyntaxhighlight>
 
{{Out}}
Line 2,129 ⟶ 2,163:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: arrays fry io kernel math math.combinatorics
math.matrices prettyprint sequences ;
 
Line 2,144 ⟶ 2,178:
[ upper "Upper:" ]
[ symmetric "Symmetric:" ] tri
[ print simple-table. nl ] 2tri@</langsyntaxhighlight>
{{out}}
<pre>
Line 2,170 ⟶ 2,204:
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">&a; {set mode to 0-indexed matrices}
Func Pasmat( n, t ) =
;{create a Pascal matrix of size n by n}
Line 2,193 ⟶ 2,227:
!;
Pasmat(5, 2);
!!([m);</langsyntaxhighlight>
{{out}}<pre>
1, 1, 1, 1, 1,
Line 2,217 ⟶ 2,251:
The following program uses features of Fortran 2003.
 
<langsyntaxhighlight lang="fortran">module pascal
 
implicit none
Line 2,294 ⟶ 2,328:
a = pascal_symmetric(n)
call print_matrix(a)
end program</langsyntaxhighlight>
 
<syntaxhighlight lang="text"> Size?
5
Lower Pascal Matrix
Line 2,315 ⟶ 2,349:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
sub print_matrix( M() as integer )
'displays a matrix
Line 2,373 ⟶ 2,407:
dim as integer Q(0 to 4, 0 to 9)
make_pascal( Q(), 2 )
print_matrix( Q() )</langsyntaxhighlight>
{{out}}<pre>
Upper triangular
Line 2,399 ⟶ 2,433:
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}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,483 ⟶ 2,559:
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}</langsyntaxhighlight>
 
{{out}}
Line 2,510 ⟶ 2,586:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (transpose)
import System.Environment (getArgs)
import Text.Printf (printf)
Line 2,544 ⟶ 2,620:
printMat "Upper triangular" $ pascUp n
printMat "Symmetric" $ pascSym n
_ -> error "Usage: pascmat <number>"</langsyntaxhighlight>
 
{{out}}
Line 2,578 ⟶ 2,654:
Or, in terms of binomial coefficients and coordinate transformations:
 
<langsyntaxhighlight lang="haskell">import Control.Monad (join)
import Data.Bifunctor (bimap)
import Data.Ix (range)
Line 2,622 ⟶ 2,698:
<*> [matrixSize]
)
)</langsyntaxhighlight>
{{Out}}
<pre>Lower
Line 2,646 ⟶ 2,722:
 
=={{header|J}}==
<syntaxhighlight lang="j"> !/~ i. 5
 
<lang J> !/~ i. 5
1 1 1 1 1
0 1 2 3 4
Line 2,664 ⟶ 2,739:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</langsyntaxhighlight>
 
Explanation:
Line 2,674 ⟶ 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:
 
<langsyntaxhighlight Jlang="j"> (+/)~ i. 5
0 1 2 3 4
1 2 3 4 5
Line 2,685 ⟶ 2,760:
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4</langsyntaxhighlight>
 
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,692 ⟶ 2,767:
Translation of [[Pascal_matrix_generation#Python|Python]] via [[Pascal_matrix_generation#D|D]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.System.out;
import java.util.List;
import java.util.function.Function;
Line 2,736 ⟶ 2,811:
print("Symmetric:", pascalSym(5));
}
}</langsyntaxhighlight>
 
<pre>Upper:
Line 2,763 ⟶ 2,838:
{{Trans|Haskell}}
===ES6===
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 3,052 ⟶ 3,127:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>Lower:
Line 3,077 ⟶ 3,152:
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># Generic functions
 
# Note: 'transpose' is defined in recent versions of jq
Line 3,099 ⟶ 3,174:
def pad(n): tostring | (n - length) * " " + .;
def row: reduce .[] as $x (""; . + ($x|pad(4)));
reduce .[] as $row (""; . + "\n\($row|row)");</langsyntaxhighlight>
<langsyntaxhighlight lang="jq"># n is input
def pascal_upper:
. as $n
Line 3,118 ⟶ 3,193:
| reduce range(1; $n) as $i
(.; reduce range(1; $n) as $j
(.; .[$i][$j] = .[$i-1][$j] + .[$i][$j-1]) ) ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">5
| ("\nUpper:", (pascal_upper | pp),
"\nLower:", (pascal_lower | pp),
"\nSymmetric:", (pascal_symmetric | pp)
)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -r -n -f Pascal_matrix_generation.jq
 
Upper:
Line 3,150 ⟶ 3,225:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</langsyntaxhighlight>
 
=={{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:
<langsyntaxhighlight Julialang="julia">julia> [binomial(j,i) for i in 0:4, j in 0:4]
5×5 Array{Int64,2}:
1 1 1 1 1
Line 3,177 ⟶ 3,252:
1 4 10 20 35
1 5 15 35 70
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
fun binomial(n: Int, k: Int): Int {
Line 3,211 ⟶ 3,286:
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}</langsyntaxhighlight>
 
{{out}}
Line 3,238 ⟶ 3,313:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function factorial (n)
local f = 1
for i = 2, n do
Line 3,284 ⟶ 3,359:
for _, form in pairs({"upper", "lower", "symmetric"}) do
show(pascalMatrix(form, 5))
end</langsyntaxhighlight>
{{out}}
<pre>Upper:
Line 3,308 ⟶ 3,383:
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
PascalUT := proc(n::integer)
local M := Matrix(n,n):
Line 3,355 ⟶ 3,430:
Pascal(5);
 
</syntaxhighlight>
</lang>
{{out}}<pre>
[1 1 1 1 1]
Line 3,392 ⟶ 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:
<langsyntaxhighlight Mathematicalang="mathematica">symPascal[size_] := NestList[Accumulate, Table[1, {k, size}], size - 1]
 
upperPascal[size_] := CholeskyDecomposition[symPascal@size]
Line 3,400 ⟶ 3,475:
Column[MapThread[
Labeled[Grid[#1@5], #2, Top] &, {{upperPascal, lowerPascal,
symPascal}, {"Upper", "Lower", "Symmetric"}}]]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,426 ⟶ 3,501:
 
It is also possible to directly compute a lower Pascal matrix as follows:
<langsyntaxhighlight Mathematicalang="mathematica">lowerPascal[size_] :=
MatrixExp[
SparseArray[{Band[{2, 1}] -> Range[size - 1]}, {size, size}]]]</langsyntaxhighlight>
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.
<langsyntaxhighlight Nimlang="nim">import math, sequtils, strutils
 
type SquareMatrix = seq[seq[Natural]]
Line 3,475 ⟶ 3,666:
print pascalLowerTriangular(5)
echo "\nSymmetric:"
print pascalSymmetric(5)</langsyntaxhighlight>
 
{{out}}
Line 3,500 ⟶ 3,691:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">
Pl(n)={matpascal(n-1)}
printf("%d",Pl(5))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,516 ⟶ 3,707:
[1 4 6 4 1]
</pre>
<langsyntaxhighlight lang="parigp">
Pu(n)={Pl(n)~}
printf("%d",Pu(5))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,532 ⟶ 3,723:
[0 0 0 0 1]
</pre>
<langsyntaxhighlight lang="parigp">
Ps(n)={matrix(n,n,n,g,binomial(n+g-2,n-1))}
printf("%d",Ps(5))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,550 ⟶ 3,741:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program Pascal_matrix(Output);
 
const N = 5;
Line 3,619 ⟶ 3,810:
writeln('');
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Upper:
Line 3,643 ⟶ 3,834:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 3,702 ⟶ 3,893:
pretty(lower(5, 5));
say '-' x 14;
pretty(symmetric(5, 5));</langsyntaxhighlight>
{{out}}
<pre>1, 1, 1, 1, 1
Line 3,724 ⟶ 3,915:
=={{header|Phix}}==
{{trans|Fortran}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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,770 ⟶ 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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,794 ⟶ 3,985:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(setq
Low '(A B)
Upp '(B A)
Line 3,823 ⟶ 4,014:
(pascal 4 Low)
(pascal 4 Upp)
(pascal 4 Sym)</langsyntaxhighlight>
{{out}}
<pre> 1 0 0 0 0
Line 3,844 ⟶ 4,035:
 
=={{header|PL/I}}==
Version I
<lang pli>
<syntaxhighlight lang="pli">PASCAL_MATRIX: PROCEDURE OPTIONS (MAIN); /* derived from Fortran version 18 Decenber 2021 */
 
pascal_lower: procedure(a);
Line 3,907 ⟶ 4,098:
 
end PASCAL_MATRIX;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,931 ⟶ 4,122:
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}}
<langsyntaxhighlight lang="pli">*process source attributes xref or(!);
pat: Proc Options(main);
Dcl (HBOUND,MAX,RIGHT) Builtin;
Line 4,019 ⟶ 4,277:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>Pascal upper triangular matrix
Line 4,043 ⟶ 4,301:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">EnableExplicit
Define.i x=5, I, J
 
Line 4,096 ⟶ 4,354:
 
Input()
End</langsyntaxhighlight>
{{out}}
<pre>Upper:
Line 4,124 ⟶ 4,382:
===Python: Procedural===
'''Summing adjacent values''':
<langsyntaxhighlight lang="python">from pprint import pprint as pp
 
def pascal_upp(n):
Line 4,153 ⟶ 4,411:
pp(pascal_low(n))
print("\nSymmetric:")
pp(pascal_sym(n))</langsyntaxhighlight>
 
{{out}}
Line 4,180 ⟶ 4,438:
'''Using a binomial coefficient generator function''':
 
<langsyntaxhighlight lang="python">def binomialCoeff(n, k):
result = 1
for i in range(1, k+1):
Line 4,193 ⟶ 4,451:
 
def pascal_sym(n):
return [[binomialCoeff(i+j, i) for j in range(n)] for i in range(n)]</langsyntaxhighlight>
 
{{out}}
Line 4,200 ⟶ 4,458:
===Python: Functional===
Defining binomial coefficients in terms of reduce:
<langsyntaxhighlight lang="python">'''Pascal matrix generation'''
 
from functools import reduce
Line 4,335 ⟶ 4,593:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>Symmetric:
Line 4,359 ⟶ 4,617:
 
=={{header|R}}==
<langsyntaxhighlight lang="r">lower.pascal <- function(n) {
a <- matrix(0, n, n)
a[, 1] <- 1
Line 4,395 ⟶ 4,653:
}
a
}</langsyntaxhighlight>
 
The results follow
 
<langsyntaxhighlight lang="r">> lower.pascal(5)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
Line 4,426 ⟶ 4,684:
[3,] 1 3 6 10 15
[4,] 1 4 10 20 35
[5,] 1 5 15 35 70</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
 
<lang racket>#lang racket
(require math/number-theory)
 
Line 4,454 ⟶ 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)))</langsyntaxhighlight>
{{out}}
<pre>Upper:
Line 4,483 ⟶ 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" perl6line># Extend a matrix in 2 dimensions based on 3 neighbors.
sub grow-matrix(@matrix, &func) {
my $n = @matrix.shape eq '*' ?? 1 !! @matrix.shape[0];
Line 4,519 ⟶ 4,776:
}
say '';
}</langsyntaxhighlight>
{{out}}
<pre> 1 1 1 1 1
Line 4,542 ⟶ 4,799:
===separate generation===
Commentary: &nbsp; <sup>1</sup>/<sub>3</sub> &nbsp; of the REXX program deals with the displaying of the matrix.
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays three forms of an NxN Pascal matrix. */
numeric digits 50 /*be able to calculate huge factorials.*/
parse arg N . /*obtain the optional matrix size (N).*/
Line 4,576 ⟶ 4,833:
say $ || left(',', r\==s)left("]", r==s) /*show row. */
end /*r*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 4,603 ⟶ 4,860:
===consolidated generation===
This REXX version uses a consolidated generation subroutine, even though this Rosetta Code implies to use &nbsp; '''functions''' &nbsp; (instead of a single function).
<langsyntaxhighlight lang="rexx">/*REXX program generates and displays three forms of an NxN Pascal matrix. */
numeric digits 50 /*be able to calculate huge factorials.*/
parse arg N . /*obtain the optional matrix size (N).*/
Line 4,638 ⟶ 4,895:
say $ || left(',', r\==s)left(']', r==s) /*show row. */
end /*r*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Pascal matrix generation
 
Line 4,716 ⟶ 4,973:
see nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,739 ⟶ 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:'''
<langsyntaxhighlight lang="ruby">#Upper, lower, and symetric Pascal Matrix - Nigel Galloway: May 3rd., 21015
require 'pp'
 
Line 4,752 ⟶ 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</langsyntaxhighlight>
{{out}}
<pre>
Line 4,775 ⟶ 5,069:
 
===Binomial coefficient:===
<langsyntaxhighlight lang="ruby">require 'pp'
 
def binomial_coeff(n,k) (1..k).inject(1){|res,i| res * (n-i+1) / i} end
Line 4,790 ⟶ 5,084:
 
puts "\nPascal symmetric matrix:"
pp pascal_symmetric(5)</langsyntaxhighlight>
 
{{out}}
Line 4,817 ⟶ 5,111:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">//Pascal Matrix Generator
 
object pascal{
Line 4,881 ⟶ 5,175:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
Using SRFI-25:
 
<langsyntaxhighlight lang="scheme">(import (srfi 25))
 
(define-syntax dotimes
Line 4,937 ⟶ 5,231:
(display (array-ref a row col))
(display #\space))
(newline))))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="scheme">(print-array (pascal-upper 6))</langsyntaxhighlight>
{{out}}
<pre>
Line 4,948 ⟶ 5,242:
0 0 0 0 1
</pre>
<langsyntaxhighlight lang="scheme">(print-array (pascal-lower 6))</langsyntaxhighlight>
{{out}}
<pre>
Line 4,957 ⟶ 5,251:
1 4 6 4 1
</pre>
<langsyntaxhighlight lang="scheme">(print-array (pascal-symmetric 6))</langsyntaxhighlight>
{{out}}
<pre>
Line 4,969 ⟶ 5,263:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func grow_matrix(matrix, callback) {
var m = matrix
var s = m.len
Line 4,997 ⟶ 5,291:
functions.map { |f|
f(4).map { .map{ '%2s' % _ }.join(' ') }.join("\n")
}.join("\n\n").say</langsyntaxhighlight>
{{out}}
<pre>
Line 5,020 ⟶ 5,314:
 
=={{header|Stata}}==
 
Here are variants for the lower matrix.
 
<langsyntaxhighlight lang="stata">mata
function pascal1(n) {
return(comb(J(1,n,0::n-1),J(n,1,0..n-1)))
Line 5,050 ⟶ 5,343:
return(s)
}
end</langsyntaxhighlight>
 
One could trivially write functions for the upper matrix (same operations with transposed matrices).
Line 5,056 ⟶ 5,349:
immediately deduced:
 
<langsyntaxhighlight lang="stata">: a = pascal3(5)
: a
1 2 3 4 5
Line 5,086 ⟶ 5,379:
4 | 1 4 10 20 |
5 | 1 5 15 35 70 |
+--------------------------+</langsyntaxhighlight>
 
The last is a symmetric matrix, but Stata only shows the lower triangular part of symmetric matrices.
 
=={{header|Tcl}}==
<syntaxhighlight lang="tcl">
<lang Tcl>
package require math
 
Line 5,125 ⟶ 5,418:
pascal::$type 5
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,152 ⟶ 5,445:
=={{header|VBA}}==
{{trans|Phix}}
<langsyntaxhighlight lang="vb">Option Base 1
Private Function pascal_upper(n As Integer)
Dim res As Variant: ReDim res(n, n)
Line 5,200 ⟶ 5,493:
Debug.Print "=== Pascal symmetrical matrix ==="
pp pascal_symmetric(5)
End Sub</langsyntaxhighlight>{{out}}
<pre>=== Pascal upper matrix ===
1 1 1 1 1
Line 5,221 ⟶ 5,514:
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
Function pascal_upper(i,j)
WScript.StdOut.Write "Pascal Upper"
Line 5,287 ⟶ 5,580:
Call pascal_lower(0,4)
Call pascal_symmetric(0,4)
</syntaxhighlight>
</lang>
 
{{Out}}
Line 5,317 ⟶ 5,610:
{{libheader|Wren-math}}
{{libheader|Wren-matrix}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./math" for Int
import "./matrix" for Matrix
 
var binomial = Fn.new { |n, k|
Line 5,358 ⟶ 5,651:
Fmt.mprint(pascalLowerTriangular.call(n), 2, 0)
System.print("\nPascal symmetric matrix:")
Fmt.mprint(pascalSymmetric.call(n), 2, 0)</langsyntaxhighlight>
 
{{out}}
Line 5,382 ⟶ 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}}
<langsyntaxhighlight lang="zkl">fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) }
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 5,393 ⟶ 5,770:
cols:=ns.len().toFloat().sqrt().toInt();
ns.pump(List,T(Void.Read,cols-1),List.create)
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn prettyPrint(m){ // m is a list of lists
fmt:=("%3d "*m.len() + "\n").fmt;
m.pump(String,'wrap(col){ fmt(col.xplode()) });
Line 5,401 ⟶ 5,778:
println("Upper:\n", pascal_upp(N):prettyPrint(_));
println("Lower:\n", pascal_low(N):prettyPrint(_));
println("Symmetric:\n",pascal_sym(N):prettyPrint(_));</langsyntaxhighlight>
{{out}}
<pre>
9,482

edits