2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,12 +1,37 @@
[[wp:Pascal's triangle|Pascal's triangle]] is an arithmetic and geometric figure first imagined by [[wp:Blaise Pascal|Blaise Pascal]].
[[wp:Pascal's triangle|Pascal's triangle]]   is an arithmetic and geometric figure first imagined by   [[wp:Blaise Pascal|Blaise Pascal]].
Its first few rows look like this:
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it. For example, the next row would be 1 (since the first element of each row doesn't have two elements above it), 4 (1 + 3), 6 (3 + 3), 4 (3 + 1), and 1 (since the last element of each row doesn't have two elements above it). Each row <tt>n</tt> (starting with row 0 at the top) shows the coefficients of the binomial expansion of (x + y)<sup>n</sup>.
1
1 1
1 2 1
1 3 3 1
where each element of each row is either 1 or the sum of the two elements right above it.
Write a function that prints out the first n rows of the triangle (with <tt>f(1)</tt> yielding the row consisting of only the element 1). This can be done either by summing elements from the previous rows or using a binary coefficient or combination function. Behavior for <tt>n <= 0</tt> does not need to be uniform, but should be noted.
For example, the next row of the triangle would be:
::: &nbsp; '''1''' &nbsp; (since the first element of each row doesn't have two elements above it)
::: &nbsp; '''4''' &nbsp; (1 + 3)
::: &nbsp; '''6''' &nbsp; (3 + 3)
::: &nbsp; '''4''' &nbsp; (3 + 1)
::: &nbsp; '''1''' &nbsp; (since the last element of each row doesn't have two elements above it)
'''See also:'''
So the triangle now looks like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Each row &nbsp; <tt> n </tt> &nbsp; (starting with row &nbsp; 0 &nbsp; at the top) shows the coefficients of the binomial expansion of &nbsp; <big><big> (x + y)<sup>n</sup>. </big></big>
;Task:
Write a function that prints out the first &nbsp; <tt> n </tt> &nbsp; rows of the triangle &nbsp; (with &nbsp; <tt> f(1) </tt> &nbsp; yielding the row consisting of only the element '''1''').
This can be done either by summing elements from the previous rows or using a binary coefficient or combination function.
Behavior for &nbsp; <big><tt> n ≤ 0 </tt></big> &nbsp; does not need to be uniform, but should be noted.
;See also:
* [[Evaluate binomial coefficients]]
<br><br>

View file

@ -0,0 +1,136 @@
-- pascal :: Int -> [[Int]]
on pascal(intRows)
script addRow
on nextRow(row)
script add
on lambda(a, b)
a + b
end lambda
end script
zipWith(add, [0] & row, row & [0])
end nextRow
on lambda(xs)
xs & {nextRow(item -1 of xs)}
end lambda
end script
foldr(addRow, {{1}}, range(1, intRows - 1))
end pascal
-- TEST
on run
set lstTriangle to pascal(7)
script spaced
on lambda(xs)
script rightAlign
on lambda(x)
text -4 thru -1 of (" " & x)
end lambda
end script
intercalate("", map(rightAlign, xs))
end lambda
end script
script indented
on lambda(a, x)
set strIndent to leftSpace of a
{rows:strIndent & x & linefeed & rows of a, leftSpace:leftSpace of a & " "}
end lambda
end script
rows of foldr(indented, {rows:"", leftSpace:""}, map(spaced, lstTriangle))
end run
-- GENERIC LIBRARY FUNCTIONS
-- foldr :: (a -> b -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from lng to 1 by -1
set v to lambda(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldr
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to lambda(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set nx to length of xs
set ny to length of ys
if nx < 1 or ny < 1 then
{}
else
set lng to cond(nx < ny, nx, ny)
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to lambda(item i of xs, item i of ys)
end repeat
return lst
end tell
end if
end zipWith
-- cond :: Bool -> (a -> b) -> (a -> b) -> (a -> b)
on cond(bool, f, g)
if bool then
f
else
g
end if
end cond
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- range :: Int -> Int -> [Int]
on range(m, n)
set lng to (n - m) + 1
set base to m - 1
set lst to {}
repeat with i from 1 to lng
set end of lst to i + base
end repeat
return lst
end range
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property lambda : f
end script
end if
end mReturn

View file

@ -0,0 +1,12 @@
(defun pascal-next-row (a)
(loop :for q :in a
:and p = 0 :then q
:as s = (list (+ p q))
:nconc s :into a
:finally (rplacd s (list 1))
(return a)))
(defun pascal (n)
(loop :for a = (list 1) :then (pascal-next-row a)
:repeat n
:collect a))

View file

@ -1 +1,2 @@
def pascal = { n -> (n <= 1) ? [1] : GroovyCollections.transpose([[0] + pascal(n - 1), pascal(n - 1) + [0]]).collect { it.sum() } }
def pascal
pascal = { n -> (n <= 1) ? [1] : [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }

View file

@ -1,70 +1,92 @@
(function (n) {
'use strict';
// A Pascal triangle of n rows
// n --> [[n]]
function pascalTriangle(n) {
// A Pascal triangle of n rows
// Sums of each consecutive pair of numbers
// [n] --> [n]
function pairSums(lst) {
return lst.reduce(function (acc, n, i, l) {
var iPrev = i ? i - 1 : 0;
return i ? acc.concat(l[iPrev] + l[i]) : acc
}, []);
// pascal :: Int -> [[Int]]
function pascal(n) {
return range(1, n - 1)
.reduce(function (a) {
var lstPreviousRow = a.slice(-1)[0];
return a
.concat(
[zipWith(
function (a, b) {
return a + b
},
[0].concat(lstPreviousRow),
lstPreviousRow.concat(0)
)]
);
}, [[1]]);
}
// Next line in a Pascal triangle series
// [n] --> [n]
function nextPascal(lst) {
return lst.length ? [1].concat(
pairSums(lst)
).concat(1) : [1];
// GENERIC FUNCTIONS
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
function zipWith(f, xs, ys) {
return xs.length === ys.length ? (
xs.map(function (x, i) {
return f(x, ys[i]);
})
) : undefined;
}
// Each row is a function of the preceding row
return n ? Array.apply(null, Array(n - 1)).reduce(
function (a, _, i) {
return a.concat([nextPascal(a[i])]);
}, [[1]]) : [];
}
// range :: Int -> Int -> [Int]
function range(m, n) {
return Array.apply(null, Array(n - m + 1))
.map(function (x, i) {
return m + i;
});
}
// TEST
var lstTriangle = pascalTriangle(n);
// TEST
var lstTriangle = pascal(n);
// FORMAT OUTPUT AS WIKI TABLE
// FORMAT OUTPUT AS WIKI TABLE
// [[a]] -> bool -> s -> s
function wikiTable(lstRows, blnHeaderRow, strStyle) {
return '{| class="wikitable" ' + (
strStyle ? 'style="' + strStyle + '"' : ''
) + lstRows.map(function (lstRow, iRow) {
var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');
// [[a]] -> bool -> s -> s
function wikiTable(lstRows, blnHeaderRow, strStyle) {
return '{| class="wikitable" ' + (
strStyle ? 'style="' + strStyle + '"' : ''
) + lstRows.map(function (lstRow, iRow) {
var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');
return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) {
return typeof v === 'undefined' ? ' ' : v;
}).join(' ' + strDelim + strDelim + ' ');
}).join('') + '\n|}';
}
return '\n|-\n' + strDelim + ' ' + lstRow.map(function (
v) {
return typeof v === 'undefined' ? ' ' : v;
})
.join(' ' + strDelim + strDelim + ' ');
})
.join('') + '\n|}';
}
var lstLastLine = lstTriangle.slice(-1)[0],
lngBase = (lstLastLine.length * 2) - 1,
nWidth = lstLastLine.reduce(function (a, x) {
var d = x.toString().length;
return d > a ? d : a;
}, 1) * lngBase;
var lstLastLine = lstTriangle.slice(-1)[0],
lngBase = (lstLastLine.length * 2) - 1,
nWidth = lstLastLine.reduce(function (a, x) {
var d = x.toString()
.length;
return d > a ? d : a;
}, 1) * lngBase;
return [
return [
wikiTable(
lstTriangle.map(function (lst) {
return lst.join(';;').split(';');
}).map(function (line, i) {
var lstPad = Array((lngBase - line.length) / 2);
return lstPad.concat(line).concat(lstPad);
}),
false,
'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
'em;table-layout:fixed;'
lstTriangle.map(function (lst) {
return lst.join(';;')
.split(';');
})
.map(function (line, i) {
var lstPad = Array((lngBase - line.length) / 2);
return lstPad.concat(line)
.concat(lstPad);
}),
false,
'text-align:center;width:' + nWidth + 'em;height:' + nWidth +
'em;table-layout:fixed;'
),
JSON.stringify(lstTriangle)

View file

@ -0,0 +1,50 @@
(() => {
'use strict';
// pascal :: Int -> [[Int]]
let pascal = n =>
range(1, n - 1)
.reduce(a => {
let lstPreviousRow = a.slice(-1)[0];
return a
.concat([zipWith((a, b) => a + b,
[0].concat(lstPreviousRow),
lstPreviousRow.concat(0)
)]);
}, [
[1]
]);
// GENERIC FUNCTIONS
// Int -> Int -> Maybe Int -> [Int]
let range = (m, n, step) => {
let d = (step || 1) * (n >= m ? 1 : -1);
return Array.from({
length: Math.floor((n - m) / d) + 1
}, (_, i) => m + (i * d));
},
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith = (f, xs, ys) =>
xs.length === ys.length ? (
xs.map((x, i) => f(x, ys[i]))
) : undefined;
// TEST
return pascal(7)
.reduceRight((a, x) => {
let strIndent = a.indent;
return {
rows: strIndent + x
.map(n => (' ' + n).slice(-4))
.join('') + '\n' + a.rows,
indent: strIndent + ' '
};
}, {
rows: '',
indent: ''
}).rows;
})();

View file

@ -0,0 +1,3 @@
f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
f(3);

View file

@ -1,3 +1,5 @@
sub pascal { [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... * }
sub pascal {
[1], { [0, |$_ Z+ |$_, 0] } ... *
}
.say for pascal[^10];

View file

@ -1,25 +1,25 @@
/*REXX program displays Pascal's triangle (centered/formatted); also known as:*/
/*────────── Yang Hui's, Khayyam─Pascal, Kyayyam, and/or Tartaglia's triangle.*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn .; if nn=='' then nn=10 /*use default if NN wasn't specified.*/
N=abs(nn) /*N is the number of rows in triangle.*/
@.=1; $.=@. /*default value for rows and for lines.*/
w=length(!(N-1) / !(N%2) / !(N-1-N%2)) /*W is the width of the biggest number*/
/* [↓] build rows of Pascals' triangle*/
do r=1 for N; rm=r-1 /*Note: the first column is always 1.*/
do c=2 to rm; cm=c-1 /*build the rest of the columns in row.*/
@.r.c= @.rm.cm + @.rm.c /*assign value to a specific row & col.*/
$.r = $.r right(@.r.c, w) /*and construct a line for output (row)*/
end /*c*/ /* [↑] C is the column being built.*/
if r\==1 then $.r=$.r right(1, w) /*for most rows, append a trailing "1".*/
end /*r*/ /* [↑] R is the row being built.*/
/* [↑] WIDTH: for nicely looking line.*/
width=length($.N) /*width of the last (output) line (row)*/
/*if NN<0, output is written to a file.*/
do r=1 for N /*show│write lines (rows) of triangle. */
if nn>0 then say center($.r, width) /*SAY, or*/
else call lineout 'PASCALS.'n, center($.r, width) /*write. */
end /*r*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────! subroutine (factorial)─────────────────*/
!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end; return !
/*REXX program displays (or writes to a file) Pascal's triangle (centered/formatted).*/
numeric digits 3000 /*be able to handle gihugeic triangles.*/
parse arg nn . /*obtain the optional argument from CL.*/
if nn=='' | nn=="," then nn=10 /*Not specified? Then use the default.*/
N=abs(nn) /*N is the number of rows in triangle.*/
w=length( !(N-1) / !(N%2) / !(N-1-N%2) ) /*W: the width of the biggest integer.*/
@.=1; $.=@.; unity=right(1, w) /*defaults rows & lines; aligned unity.*/
/* [↓] build rows of Pascals' triangle*/
do r=1 for N; rm=r-1 /*Note: the first column is always 1.*/
do c=2 to rm; cm=c-1 /*build the rest of the columns in row.*/
@.r.c= @.rm.cm + @.rm.c /*assign value to a specific row & col.*/
$.r = $.r right(@.r.c, w) /*and construct a line for output (row)*/
end /*c*/ /* [↑] C is the column being built.*/
if r\==1 then $.r=$.r unity /*for rows≥2, append a trailing "1".*/
end /*r*/ /* [↑] R is the row being built.*/
/* [↑] WIDTH: for nicely looking line.*/
width=length($.N) /*width of the last (output) line (row)*/
/*if NN<0, output is written to a file.*/
do r=1 for N; $$=center($.r, width) /*center this particular Pascals' row. */
if nn>0 then say $$ /*SAY if NN is positive, else */
else call lineout 'PASCALS.'n, $$ /*write this Pascal's row ───► a file.*/
end /*r*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; !=1; do j=2 to arg(1); !=!*j; end /*j*/; return ! /*compute factorial*/