Pascal matrix generation: Difference between revisions
m
syntax highlighting fixup automation
(→{{header|PL/I}}: Second version added) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 48:
{{trans|Python}}
<
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 264:
=={{header|Action!}}==
<
RETURN (i*dim+j)
Line 355:
PascalSymmetric(mat,dim)
PrintMatrix(mat,dim)
RETURN</
{{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}}==
<
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;</
{{out}}
<pre>What dimension Pascal matrix would you like? 5
Line 489:
=={{header|ALGOL 68}}==
<
# 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</
{{out}}
<pre>
Line 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 639:
end
end.</
{{out}}
<pre>
Line 664:
=={{header|APL}}==
{{works with|Dyalog APL}}
<
lower ← ⍉(∘.!⍨¯1+⍳)
symmetric ← (⊢![1]∘.+⍨)¯1+⍳</
{{out}}
<pre style='line-height:normal'>
Line 680:
=={{header|AppleScript}}==
By composition of generic functions:
<
-- pascalMatrix :: ((Int, Int) -> (Int, Int)) -> Int -> [[Int]]
Line 1,015:
return lst
end tell
end zipWith</
{{Out}}
<pre>Lower
Line 1,039:
=={{header|AutoHotkey}}==
<
MsgBox, 262144, ,% ""
. "Pascal upper-triangular :`n" show(Pascal_Upper(n))
Line 1,103:
}
return obj
}</
{{out}}
<pre>Pascal upper-triangular :
Line 1,127:
=={{header|BASIC}}==
<
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</
{{out}}
<pre>Lower-triangular matrix:
Line 1,185:
=={{header|BCPL}}==
<
manifest $( size = 5 $)
Line 1,237:
writes("*NSymmetric matrix:*N")
symmetric(mat, size) ; writemat(mat, size, 2)
$)</
{{out}}
<pre>Upper-triangular matrix:
Line 1,261:
=={{header|C}}==
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 1,335:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,359:
=={{header|C sharp}}==
<
public static class PascalMatrixGeneration
Line 1,424:
}
}</
{{out}}
<pre>
Line 1,447:
=={{header|C++}}==
{{works with|GCC|version 7.2.0 (Ubuntu 7.2.0-8ubuntu3.2) }}
<
#include <vector>
Line 1,504:
std::cout << "PASCAL SYMMETRIC MATRIX" << std::endl;
print_matrix(pascal_symmetric(5));
}</
{{out}}
<pre>
Line 1,528:
=={{header|Clojure}}==
<
(reduce #(quot (* %1 (inc (- n %2))) %2)
1
Line 1,565:
(println)
(println "Symmetric:")
(run! println (pascal-symmetric n)))</
{{out}}
<pre>=> (pascal-matrix 5)
Line 1,590:
=={{header|CLU}}==
<
make_matrix = proc (gen: proctype (int,int,matrix) returns (int),
Line 1,644:
stream$putl(po, "\nSymmetric matrix:")
print_matrix(po, make_matrix(symmetric,5), 2)
end start_up</
{{out}}
<pre>Upper-triangular matrix:
Line 1,668:
=={{header|Common Lisp}}==
<
(dotimes (i n)
(setf (aref a i 0) 1))
Line 1,732:
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,762:
writefln("\nLower:\n%(%(%2d %)\n%)", pascalLow(n));
writefln("\nSymmetric:\n%(%(%2d %)\n%)", pascalSym(n));
}</
{{out}}
<pre>Upper:
Line 1,788:
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,833:
Pascal.lower_triangle(5)
IO.puts "Pascal symmetric matrix:"
Pascal.symmetic_triangle(5)</
{{out}}
Line 1,865:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(n,
LAMBDA(f,
Line 1,899:
)
)
)</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(f,
LAMBDA(a,
Line 1,914:
ID
=LAMBDA(x, x)</
{{Out}}
Line 2,129:
=={{header|Factor}}==
{{works with|Factor|0.99 2020-01-23}}
<
math.matrices prettyprint sequences ;
Line 2,144:
[ upper "Upper:" ]
[ symmetric "Symmetric:" ] tri
[ print simple-table. nl ] 2tri@</
{{out}}
<pre>
Line 2,170:
=={{header|Fermat}}==
<
Func Pasmat( n, t ) =
;{create a Pascal matrix of size n by n}
Line 2,193:
!;
Pasmat(5, 2);
!!([m);</
{{out}}<pre>
1, 1, 1, 1, 1,
Line 2,217:
The following program uses features of Fortran 2003.
<
implicit none
Line 2,294:
a = pascal_symmetric(n)
call print_matrix(a)
end program</
<syntaxhighlight lang="text"> Size?
5
Lower Pascal Matrix
Line 2,315:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</
=={{header|FreeBASIC}}==
<
sub print_matrix( M() as integer )
'displays a matrix
Line 2,373:
dim as integer Q(0 to 4, 0 to 9)
make_pascal( Q(), 2 )
print_matrix( Q() )</
{{out}}<pre>
Upper triangular
Line 2,403:
=={{header|Go}}==
{{trans|Kotlin}}
<
import (
Line 2,483:
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}</
{{out}}
Line 2,510:
=={{header|Haskell}}==
<
import System.Environment (getArgs)
import Text.Printf (printf)
Line 2,544:
printMat "Upper triangular" $ pascUp n
printMat "Symmetric" $ pascSym n
_ -> error "Usage: pascmat <number>"</
{{out}}
Line 2,578:
Or, in terms of binomial coefficients and coordinate transformations:
<
import Data.Bifunctor (bimap)
import Data.Ix (range)
Line 2,622:
<*> [matrixSize]
)
)</
{{Out}}
<pre>Lower
Line 2,647:
=={{header|J}}==
<
1 1 1 1 1
0 1 2 3 4
Line 2,664:
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70</
Explanation:
Line 2,674:
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,685:
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,692:
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,736:
print("Symmetric:", pascalSym(5));
}
}</
<pre>Upper:
Line 2,763:
{{Trans|Haskell}}
===ES6===
<
'use strict';
Line 3,052:
// MAIN ---
return main();
})();</
{{Out}}
<pre>Lower:
Line 3,077:
=={{header|jq}}==
{{works with|jq|1.4}}
<
# Note: 'transpose' is defined in recent versions of jq
Line 3,099:
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 3,118:
| 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 3,150:
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 3,177:
1 4 10 20 35
1 5 15 35 70
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun binomial(n: Int, k: Int): Int {
Line 3,211:
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
}</
{{out}}
Line 3,238:
=={{header|Lua}}==
<
local f = 1
for i = 2, n do
Line 3,284:
for _, form in pairs({"upper", "lower", "symmetric"}) do
show(pascalMatrix(form, 5))
end</
{{out}}
<pre>Upper:
Line 3,308:
=={{header|Maple}}==
<syntaxhighlight lang="maple">
PascalUT := proc(n::integer)
local M := Matrix(n,n):
Line 3,355:
Pascal(5);
</syntaxhighlight>
{{out}}<pre>
[1 1 1 1 1]
Line 3,392:
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,400:
Column[MapThread[
Labeled[Grid[#1@5], #2, Top] &, {{upperPascal, lowerPascal,
symPascal}, {"Upper", "Lower", "Symmetric"}}]]</
{{out}}
<pre>
Line 3,426:
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
Line 3,434:
=={{header|Nim}}==
Using the function “binom” from module “math” of standard library.
<
type SquareMatrix = seq[seq[Natural]]
Line 3,475:
print pascalLowerTriangular(5)
echo "\nSymmetric:"
print pascalSymmetric(5)</
{{out}}
Line 3,500:
=={{header|PARI/GP}}==
<
Pl(n)={matpascal(n-1)}
printf("%d",Pl(5))
</syntaxhighlight>
{{out}}
<pre>
Line 3,516:
[1 4 6 4 1]
</pre>
<
Pu(n)={Pl(n)~}
printf("%d",Pu(5))
</syntaxhighlight>
{{out}}
<pre>
Line 3,532:
[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,550:
=={{header|Pascal}}==
<
const N = 5;
Line 3,619:
writeln('');
readln;
end.</
{{out}}
<pre>Upper:
Line 3,643:
=={{header|Perl}}==
<
use warnings;
use strict;
Line 3,702:
pretty(lower(5, 5));
say '-' x 14;
pretty(symmetric(5, 5));</
{{out}}
<pre>1, 1, 1, 1, 1
Line 3,724:
=={{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,770:
<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,794:
=={{header|PicoLisp}}==
<
Low '(A B)
Upp '(B A)
Line 3,823:
(pascal 4 Low)
(pascal 4 Upp)
(pascal 4 Sym)</
{{out}}
<pre> 1 0 0 0 0
Line 3,845:
=={{header|PL/I}}==
Version I
<
pascal_lower: procedure(a);
Line 3,907:
end PASCAL_MATRIX;
</syntaxhighlight>
{{out}}
<pre>
Line 3,932:
</pre>
Version II
<
PASCAL_MATRIX: PROCEDURE OPTIONS (MAIN); /* derived from Fortran version 18 Decenber 2021 */
Line 3,997:
end PASCAL_MATRIX;
</syntaxhighlight>
{{trans|Rexx}}
<
pat: Proc Options(main);
Dcl (HBOUND,MAX,RIGHT) Builtin;
Line 4,086:
End;
End;</
{{out}}
<pre>Pascal upper triangular matrix
Line 4,110:
=={{header|PureBasic}}==
<
Define.i x=5, I, J
Line 4,163:
Input()
End</
{{out}}
<pre>Upper:
Line 4,191:
===Python: Procedural===
'''Summing adjacent values''':
<
def pascal_upp(n):
Line 4,220:
pp(pascal_low(n))
print("\nSymmetric:")
pp(pascal_sym(n))</
{{out}}
Line 4,247:
'''Using a binomial coefficient generator function''':
<
result = 1
for i in range(1, k+1):
Line 4,260:
def pascal_sym(n):
return [[binomialCoeff(i+j, i) for j in range(n)] for i in range(n)]</
{{out}}
Line 4,267:
===Python: Functional===
Defining binomial coefficients in terms of reduce:
<
from functools import reduce
Line 4,402:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Symmetric:
Line 4,426:
=={{header|R}}==
<
a <- matrix(0, n, n)
a[, 1] <- 1
Line 4,462:
}
a
}</
The results follow
<
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 0 0 0
Line 4,493:
[3,] 1 3 6 10 15
[4,] 1 4 10 20 35
[5,] 1 5 15 35 70</
=={{header|Racket}}==
<
(require math/number-theory)
Line 4,521:
(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,550:
{{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,586:
}
say '';
}</
{{out}}
<pre> 1 1 1 1 1
Line 4,609:
===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,643:
say $ || left(',', r\==s)left("]", r==s) /*show row. */
end /*r*/
return</
{{out|output|text= when using the default input:}}
<pre>
Line 4,670:
===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,705:
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,783:
see nl
next
</syntaxhighlight>
Output:
<pre>
Line 4,810:
=={{header|Ruby}}==
'''Summing adjacent values:'''
<
require 'pp'
Line 4,819:
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,842:
===Binomial coefficient:===
<
def binomial_coeff(n,k) (1..k).inject(1){|res,i| res * (n-i+1) / i} end
Line 4,857:
puts "\nPascal symmetric matrix:"
pp pascal_symmetric(5)</
{{out}}
Line 4,884:
=={{header|Scala}}==
<
object pascal{
Line 4,948:
}
}
</syntaxhighlight>
=={{header|Scheme}}==
Using SRFI-25:
<
(define-syntax dotimes
Line 5,004:
(display (array-ref a row col))
(display #\space))
(newline))))</
<
{{out}}
<pre>
Line 5,015:
0 0 0 0 1
</pre>
<
{{out}}
<pre>
Line 5,024:
1 4 6 4 1
</pre>
<
{{out}}
<pre>
Line 5,036:
=={{header|Sidef}}==
{{trans|Raku}}
<
var m = matrix
var s = m.len
Line 5,064:
functions.map { |f|
f(4).map { .map{ '%2s' % _ }.join(' ') }.join("\n")
}.join("\n\n").say</
{{out}}
<pre>
Line 5,090:
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 5,117:
return(s)
}
end</
One could trivially write functions for the upper matrix (same operations with transposed matrices).
Line 5,123:
immediately deduced:
<
: a
1 2 3 4 5
Line 5,153:
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 5,192:
pascal::$type 5
}
</syntaxhighlight>
{{out}}
<pre>
Line 5,219:
=={{header|VBA}}==
{{trans|Phix}}
<
Private Function pascal_upper(n As Integer)
Dim res As Variant: ReDim res(n, n)
Line 5,267:
Debug.Print "=== Pascal symmetrical matrix ==="
pp pascal_symmetric(5)
End Sub</
<pre>=== Pascal upper matrix ===
1 1 1 1 1
Line 5,288:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function pascal_upper(i,j)
WScript.StdOut.Write "Pascal Upper"
Line 5,354:
Call pascal_lower(0,4)
Call pascal_symmetric(0,4)
</syntaxhighlight>
{{Out}}
Line 5,384:
{{libheader|Wren-math}}
{{libheader|Wren-matrix}}
<
import "/math" for Int
import "/matrix" for Matrix
Line 5,425:
Fmt.mprint(pascalLowerTriangular.call(n), 2, 0)
System.print("\nPascal symmetric matrix:")
Fmt.mprint(pascalSymmetric.call(n), 2, 0)</
{{out}}
Line 5,453:
=={{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 5,460:
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 5,468:
println("Upper:\n", pascal_upp(N):prettyPrint(_));
println("Lower:\n", pascal_low(N):prettyPrint(_));
println("Symmetric:\n",pascal_sym(N):prettyPrint(_));</
{{out}}
<pre>
|