tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,8 @@
[[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>.
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.

View file

@ -0,0 +1,2 @@
---
note: Arithmetic operations

View file

@ -0,0 +1,19 @@
PRIO MINLWB = 8, MAXUPB = 8;
OP MINLWB = ([]INT a,b)INT: (LWB a<LWB b|LWB a|LWB b),
MAXUPB = ([]INT a,b)INT: (UPB a>UPB b|UPB a|UPB b);
OP + = ([]INT a,b)[]INT:(
[a MINLWB b:a MAXUPB b]INT out; FOR i FROM LWB out TO UPB out DO out[i]:= 0 OD;
out[LWB a:UPB a] := a; FOR i FROM LWB b TO UPB b DO out[i]+:= b[i] OD;
out
);
INT width = 4, stop = 9;
FORMAT centre = $n((stop-UPB row+1)*width OVER 2)(q)$;
FLEX[1]INT row := 1; # example of rowing #
FOR i WHILE
printf((centre, $g(-width)$, row, $l$));
# WHILE # i < stop DO
row := row[AT 1] + row[AT 2]
OD

View file

@ -0,0 +1 @@
{A0, A.!A}

View file

@ -0,0 +1 @@
{A0, A.!A} 3

View file

@ -0,0 +1,7 @@
$ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j<i;j++){c*=(i-j)/(j+1);r=r" "c};print r}}'
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

View file

@ -0,0 +1,34 @@
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
procedure Pascals_Triangle is
type Row is array(Positive range <>) of Integer;
type Row_Access is access Row;
type Triangle is array(Positive range <>) of Row_Access;
function General_Triangle(Depth : Positive) return Triangle is
Result : Triangle(1..Depth);
begin
for I in Result'range loop
Result(I) := new Row(1..I);
for J in 1..I loop
if J = Result(I)'First or else J = Result(I)'Last then
Result(I)(J) := 1;
else
Result(I)(J) := Result(I - 1)(J - 1) + Result(I - 1)(J);
end if;
end loop;
end loop;
return Result;
end General_Triangle;
procedure Print(Item : Triangle) is
begin
for I in Item'range loop
for J in 1..I loop
Put(Item => Item(I)(J), Width => 3);
end loop;
New_Line;
end loop;
end Print;
begin
Print(General_Triangle(7));
end Pascals_Triangle;

View file

@ -0,0 +1,22 @@
n := 8, p0 := "1" ; 1+n rows of Pascal's triangle
Loop %n% {
p := "p" A_Index, %p% := v := 1, q := "p" A_Index-1
Loop Parse, %q%, %A_Space%
If (A_Index > 1)
%p% .= " " v+A_LoopField, v := A_LoopField
%p% .= " 1"
}
; Triangular Formatted output
VarSetCapacity(tabs,n,Asc("`t"))
t .= tabs "`t1"
Loop %n% {
t .= "`n" SubStr(tabs,A_Index)
Loop Parse, p%A_Index%, %A_Space%
t .= A_LoopField "`t`t"
}
Gui Add, Text,, %t% ; Show result in a GUI
Gui Show
Return
GuiClose:
ExitApp

View file

@ -0,0 +1,16 @@
DIM i AS Integer
DIM row AS Integer
DIM nrows AS Integer
DIM values(100) AS Integer
INPUT "Number of rows: "; nrows
values(1) = 1
PRINT TAB((nrows)*3);" 1"
FOR row = 2 TO nrows
PRINT TAB((nrows-row)*3+1);
FOR i = row TO 1 STEP -1
values(i) = values(i) + values(i-1)
PRINT USING "##### "; values(i);
NEXT i
PRINT
NEXT row

View file

@ -0,0 +1,13 @@
nrows% = 10
colwidth% = 4
@% = colwidth% : REM Set column width
FOR row% = 1 TO nrows%
PRINT SPC(colwidth%*(nrows% - row%)/2);
acc% = 1
FOR element% = 1 TO row%
PRINT acc%;
acc% = acc% * (row% - element%) / element% + 0.5
NEXT
PRINT
NEXT row%

View file

@ -0,0 +1,18 @@
( out$"Number of rows? "
& get':?R
& -1:?I
& whl
' ( 1+!I:<!R:?I
& 1:?C
& -1:?K
& !R+-1*!I:?tabs
& whl'(!tabs+-1:>0:?tabs&put$\t)
& whl
' ( 1+!K:~>!I:?K
& put$(!C \t\t)
& !C*(!I+-1*!K)*(!K+1)^-1:?C
)
& put$\n
)
&
)

View file

@ -0,0 +1,18 @@
blsq ) {1}{1 1}{^^2CO{p^?+}m[1+]1[+}15E!#s<-spbx#S
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
1 16 120 560 1820 4368 8008 11440 12870 11440 8008 4368 1820 560 120 16 1

View file

@ -0,0 +1,26 @@
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
void genPyrN(int rows) {
if (rows < 0) return;
// save the last row here
std::vector<int> last(1, 1);
std::cout << last[0] << std::endl;
for (int i = 1; i <= rows; i++) {
// work on the next row
std::vector<int> thisRow;
thisRow.reserve(i+1);
thisRow.push_back(last.front()); // beginning of row
std::transform(last.begin(), last.end()-1, last.begin()+1, std::back_inserter(thisRow), std::plus<int>()); // middle of row
thisRow.push_back(last.back()); // end of row
for (int j = 0; j <= i; j++)
std::cout << thisRow[j] << " ";
std::cout << std::endl;
last.swap(thisRow);
}
}

View file

@ -0,0 +1,22 @@
#include <stdio.h>
void pascaltriangle(unsigned int n)
{
unsigned int c, i, j, k;
for(i=0; i < n; i++) {
c = 1;
for(j=1; j <= 2*(n-1-i); j++) printf(" ");
for(k=0; k <= i; k++) {
printf("%3d ", c);
c = c * (i-k)/(k+1);
}
printf("\n");
}
}
int main()
{
pascaltriangle(8);
return 0;
}

View file

@ -0,0 +1,18 @@
#include <stdio.h>
#define D 32
int pascals(int *x, int *y, int d)
{
int i;
for (i = 1; i < d; i++)
printf("%d%c", y[i] = x[i - 1] + x[i],
i < d - 1 ? ' ' : '\n');
return D > d ? pascals(y, x, d + 1) : 0;
}
int main()
{
int x[D] = {0, 1, 0}, y[D] = {0};
return pascals(x, y, 0);
}

View file

@ -0,0 +1,16 @@
void triangleC(int nRows) {
if (nRows <= 0) return;
int *prevRow = NULL;
for (int r = 1; r <= nRows; r++) {
int *currRow = malloc(r * sizeof(int));
for (int i = 0; i < r; i++) {
int val = i==0 || i==r-1 ? 1 : prevRow[i-1] + prevRow[i];
currRow[i] = val;
printf(" %4d", val);
}
printf("\n");
free(prevRow);
prevRow = currRow;
}
free(prevRow);
}

View file

@ -0,0 +1,12 @@
(defn pascal [n]
(let [newrow (fn newrow [lst ret]
(if lst
(recur (rest lst)
(conj ret (+ (first lst) (or (second lst) 0))))
ret))
genrow (fn genrow [n lst]
(when (< 0 n)
(do (println lst)
(recur (dec n) (conj (newrow lst []) 1)))))]
(genrow n [1])))
(pascal 4)

View file

@ -0,0 +1,8 @@
(defn nextrow [row]
(vec (concat [1] (map #(apply + %) (partition 2 1 row)) [1] )))
(defn pascal [n]
(assert (and (integer? n) (pos? n)))
(let [triangle (take n (iterate nextrow [1]))]
(doseq [row triangle]
(println row))))

View file

@ -0,0 +1,7 @@
(def pascal
(iterate
(fn [prev-row]
(->>
(concat [[(first prev-row)]] (partition 2 1 prev-row) [[(last prev-row)]])
(map (partial apply +) ,,,)))
[1]))

View file

@ -0,0 +1,28 @@
pascal = (n) ->
width = 6
for r in [1..n]
s = ws (width/2) * (n-r) # center row
output = (n) -> s += pad width, n
cell = 1
output cell
# Compute binomial coefficients as you go
# across the row.
for c in [1...r]
cell *= (r-c) / c
output cell
console.log s
ws = (n) ->
s = ''
s += ' ' for i in [0...n]
s
pad = (cnt, n) ->
s = n.toString()
# There is probably a better way to do this.
cnt -= s.length
right = Math.floor(cnt / 2)
left = cnt - right
ws(left) + s + ws(right)
pascal(7)

View file

@ -0,0 +1,12 @@
(defun pascal (n)
(genrow n '(1)))
(defun genrow (n l)
(when (< 0 n)
(print l)
(genrow (1- n) (cons 1 (newrow l)))))
(defun newrow (l)
(if (> 2 (length l))
'(1)
(cons (+ (car l) (cadr l)) (newrow (cdr l)))))

View file

@ -0,0 +1,25 @@
int[][] pascalsTriangle(in int rows) pure nothrow {
auto tri = new int[][rows];
foreach (r; 0 .. rows) {
int v = 1;
foreach (c; 0 .. r+1) {
tri[r] ~= v;
v = (v * (r - c)) / (c + 1);
}
}
return tri;
}
void main() {
immutable t = pascalsTriangle(10);
assert(t == [[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]);
}

View file

@ -0,0 +1,12 @@
import std.stdio, std.algorithm, std.range;
auto pascal(in int n) /*pure nothrow*/ {
auto p = [[1]];
foreach (_; 1 .. n)
p ~= zip(p[$-1] ~ 0, 0 ~ p[$-1]).map!q{a[0] + a[1]}().array();
return p;
}
void main() {
writeln(pascal(5));
}

View file

@ -0,0 +1,42 @@
import std.stdio, std.string, std.array, std.format;
string Pascal(alias dg, T, T initValue)(int n) {
string output;
void append(in T[] l) {
output ~= " ".replicate((n - l.length + 1) * 2);
foreach (e; l)
output ~= format("%4s", format("%4s", e));
output ~= "\n";
}
if (n > 0) {
T[][] lines = [[initValue]];
append(lines[0]);
foreach (i; 1 .. n) {
lines ~= lines[i - 1] ~ initValue; // length + 1
foreach (int j; 1 .. lines[i-1].length)
lines[i][j] = dg(lines[i-1][j], lines[i-1][j-1]);
append(lines[i]);
}
}
return output;
}
string delegate(int n) genericPascal(alias dg, T, T initValue)() {
mixin Pascal!(dg, T, initValue);
return &Pascal;
}
void main() {
auto pascal = genericPascal!((int a, int b) => a + b, int, 1)();
static char xor(char a, char b) { return a == b ? '_' : '*'; }
auto sierpinski = genericPascal!(xor, char, '*')();
foreach (i; [1, 5, 9])
writef(pascal(i));
// an order 4 sierpinski triangle is a 2^4 lines generic
// Pascal triangle with xor operation
foreach (i; [16])
writef(sierpinski(i));
}

View file

@ -0,0 +1,15 @@
procedure Pascal(r : Integer);
var
i, c, k : Integer;
begin
for i:=0 to r-1 do begin
c:=1;
for k:=0 to i do begin
Print(Format('%4d', [c]));
c:=(c*(i-k)) div (k+1);
end;
PrintLn('');
end;
end;
Pascal(9);

View file

@ -0,0 +1,20 @@
def pascalsTriangle(n, out) {
def row := [].diverge(int)
out.print("<table style='text-align: center; border: 0; border-collapse: collapse;'>")
for y in 1..n {
out.print("<tr>")
row.push(1)
def skip := n - y
if (skip > 0) {
out.print(`<td colspan="$skip"></td>`)
}
for x => v in row {
out.print(`<td>$v</td><td></td>`)
}
for i in (1..!y).descending() {
row[i] += row[i - 1]
}
out.println("</tr>")
}
out.print("</table>")
}

View file

@ -0,0 +1,7 @@
def out := <file:triangle.html>.textWriter()
try {
pascalsTriangle(15, out)
} finally {
out.close()
}
makeCommand("yourFavoriteWebBrowser")("triangle.html")

View file

@ -0,0 +1,8 @@
-import(lists).
-export([pascal/1]).
pascal(1)-> [[1]];
pascal(N) ->
L = pascal(N-1),
[H|_] = L,
[lists:zipwith(fun(X,Y)->X+Y end,[0]++H,H++[0])|L].

View file

@ -0,0 +1,10 @@
sequence row
row = {}
for m = 1 to 10 do
row = row & 1
for n = length(row)-1 to 2 by -1 do
row[n] += row[n-1]
end for
print(1,row)
puts(1,'\n')
end for

View file

@ -0,0 +1,7 @@
USING: grouping kernel math sequences ;
: (pascal) ( seq -- newseq )
dup last 0 prefix 0 suffix 2 <clumps> [ sum ] map suffix ;
: pascal ( n -- seq )
1 - { { 1 } } swap [ (pascal) ] times ;

View file

@ -0,0 +1,2 @@
5 pascal .
{ { 1 } { 1 1 } { 1 2 1 } { 1 3 3 1 } { 1 4 6 4 1 } }

View file

@ -0,0 +1,29 @@
class Main
{
Int[] next_row (Int[] row)
{
new_row := [1]
(row.size-1).times |i|
{
new_row.add (row[i] + row[i+1])
}
new_row.add (1)
return new_row
}
Void print_pascal (Int n) // no output for n <= 0
{
current_row := [1]
n.times
{
echo (current_row.join(" "))
current_row = next_row (current_row)
}
}
Void main ()
{
print_pascal (10)
}
}

View file

@ -0,0 +1,11 @@
: init ( n -- )
here swap cells erase 1 here ! ;
: .line ( n -- )
cr here swap 0 do dup @ . cell+ loop drop ;
: next ( n -- )
here swap 1- cells here + do
i @ i cell+ +!
-1 cells +loop ;
: pascal ( n -- )
dup init 1 .line
1 ?do i next i 1+ .line loop ;

View file

@ -0,0 +1,8 @@
: PascTriangle
cr dup 0
?do
1 over 1- i - 2* spaces i 1+ 0 ?do dup 4 .r j i - * i 1+ / loop cr drop
loop drop
;
13 PascTriangle

View file

@ -0,0 +1,26 @@
PROGRAM Pascals_Triangle
CALL Print_Triangle(8)
END PROGRAM Pascals_Triangle
SUBROUTINE Print_Triangle(n)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n
INTEGER :: c, i, j, k, spaces
DO i = 0, n-1
c = 1
spaces = 3 * (n - 1 - i)
DO j = 1, spaces
WRITE(*,"(A)", ADVANCE="NO") " "
END DO
DO k = 0, i
WRITE(*,"(I6)", ADVANCE="NO") c
c = c * (i - k) / (k + 1)
END DO
WRITE(*,*)
END DO
END SUBROUTINE Print_Triangle

View file

@ -0,0 +1,19 @@
Pascal := function(n)
local i, v;
v := [1];
for i in [1 .. n] do
Display(v);
v := Concatenation([0], v) + Concatenation(v, [0]);
od;
end;
Pascal(9);
# [ 1 ]
# [ 1, 1 ]
# [ 1, 2, 1 ]
# [ 1, 3, 3, 1 ]
# [ 1, 4, 6, 4, 1 ]
# [ 1, 5, 10, 10, 5, 1 ]
# [ 1, 6, 15, 20, 15, 6, 1 ]
# [ 1, 7, 21, 35, 35, 21, 7, 1 ]
# [ 1, 8, 28, 56, 70, 56, 28, 8, 1 ]

View file

@ -0,0 +1,9 @@
10 INPUT "Number of rows? ",R
20 FOR I=0 TO R-1
30 C=1
40 FOR K=0 TO I
50 PRINT USING "####";C;
60 C=C*(I-K)/(K+1)
70 NEXT
80 PRINT
90 NEXT

View file

@ -0,0 +1,42 @@
package main
import "fmt"
func printTriangle(n int) {
// degenerate cases
if n <= 0 {
return
}
fmt.Println(1)
if n == 1 {
return
}
// iterate over rows, zero based
a := make([]int, (n+1)/2)
a[0] = 1
for row, middle := 1, 0; row < n; row++ {
// generate new row
even := row&1 == 0
if even {
a[middle+1] = a[middle] * 2
}
for i := middle; i > 0; i-- {
a[i] += a[i-1]
}
// print row
for i := 0; i <= middle; i++ {
fmt.Print(a[i], " ")
}
if even {
middle++
}
for i := middle; i >= 0; i-- {
fmt.Print(a[i], " ")
}
fmt.Println("")
}
}
func main() {
printTriangle(4)
}

View file

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

View file

@ -0,0 +1,4 @@
def count = 15
(1..count).each { n ->
printf ("%2d:", n); (0..(count-n)).each { print " " }; pascal(n).each{ printf("%6d ", it) }; println ""
}

View file

@ -0,0 +1,4 @@
zapWith :: (a -> a -> a) -> [a] -> [a] -> [a]
zapWith f xs [] = xs
zapWith f [] ys = ys
zapWith f (x:xs) (y:ys) = f x y : zapWith f xs ys

View file

@ -0,0 +1,2 @@
extendWith f [] = []
extendWith f xs@(x:ys) = x : zapWith f xs ys

View file

@ -0,0 +1 @@
pascal = iterate (extendWith (+)) [1]

View file

@ -0,0 +1,2 @@
*Main> take 6 pascal
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]

View file

@ -0,0 +1,5 @@
-- generate next row from current row
nextRow row = zipWith (+) ([0] ++ row) (row ++ [0])
-- returns the first n rows
pascal = iterate nextRow [1]

View file

@ -0,0 +1,5 @@
fac = product . enumFromTo 1
binCoef n k = (fac n) `div` ((fac k) * (fac $ n - k))
pascal n = map (binCoef $ n - 1) [0..n-1]

View file

@ -0,0 +1,11 @@
*Main> putStr $ unlines $ map unwords $ map (map show) $ pascal 10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

View file

@ -0,0 +1,15 @@
CALL Pascal(30)
SUBROUTINE Pascal(rows)
CHARACTER fmt*6
WRITE(Text=fmt, Format='"i", i5.5') 1+rows/4
DO row = 0, rows-1
n = 1
DO k = 0, row
col = rows*(rows-row+2*k)/4
WRITE(Row=row+1, Column=col, F=fmt) n
n = n * (row - k) / (k + 1)
ENDDO
ENDDO
END

View file

@ -0,0 +1,17 @@
Pro Pascal, n
;n is the number of lines of the triangle to be displayed
r=[1]
print, r
for i=0, (n-2) do begin
pascalrow,r
endfor
End
Pro PascalRow, r
for i=0,(n_elements(r)-2) do begin
r[i]=r[i]+r[i+1]
endfor
r= [1, r]
print, r
End

View file

@ -0,0 +1,20 @@
link math
procedure main(A)
every n := !A do { # for each command line argument
n := integer(\n) | &null
pascal(n)
}
end
procedure pascal(n) #: Pascal triangle
/n := 16
write("width=", n, " height=", n) # carpet header
fw := *(2 ^ n)+1
every i := 0 to n - 1 do {
writes(repl(" ",fw*(n-i)/2))
every j := 0 to n - 1 do
writes(center(binocoef(i, j),fw) | break)
write()
}
end

View file

@ -0,0 +1,6 @@
!~/~ i.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

View file

@ -0,0 +1,6 @@
([: ":@-.&0"1 !~/~)@i. 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

View file

@ -0,0 +1,6 @@
(-@|. |."_1 [: ":@-.&0"1 !~/~)@i. 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

View file

@ -0,0 +1,21 @@
import java.util.ArrayList;
...//class definition, etc.
public static void genPyrN(int rows){
if(rows < 0) return;
//save the last row here
ArrayList<Integer> last = new ArrayList<Integer>();
last.add(1);
System.out.println(last);
for(int i= 1;i <= rows;++i){
//work on the next row
ArrayList<Integer> thisRow= new ArrayList<Integer>();
thisRow.add(last.get(0)); //beginning
for(int j= 1;j < i;++j){//loop the number of elements in this row
//sum from the last row
thisRow.add(last.get(j - 1) + last.get(j));
}
thisRow.add(last.get(0)); //end
last= thisRow;//save this row
System.out.println(thisRow);
}
}

View file

@ -0,0 +1,27 @@
public class Pas{
public static void main(String[] args){
//usage
pas(20);
}
public static void pas(int rows){
for(int i = 0; i < rows; i++){
for(int j = 0; j <= i; j++){
System.out.print(ncr(i, j) + " ");
}
System.out.println();
}
}
public static long ncr(int n, int r){
return fact(n) / (fact(r) * fact(n - r));
}
public static long fact(int n){
long ans = 1;
for(int i = 2; i <= n; i++){
ans *= i;
}
return ans;
}
}

View file

@ -0,0 +1,19 @@
public class Pascal {
private static void printPascalLine (int n) {
if (n < 1)
return;
int m = 1;
System.out.print("1 ");
for (int j=1; j<n; j++) {
m = m * (n-j)/j;
System.out.print(m);
System.out.print(" ");
}
System.out.println();
}
public static void printPascal (int nRows) {
for(int i=1; i<=nRows; i++)
printPascalLine(i);
}
}

View file

@ -0,0 +1,71 @@
// Pascal's triangle object
function pascalTriangle (rows) {
// Number of rows the triangle contains
this.rows = rows;
// The 2D array holding the rows of the triangle
this.triangle = new Array();
for (var r = 0; r < rows; r++) {
this.triangle[r] = new Array();
for (var i = 0; i <= r; i++) {
if (i == 0 || i == r)
this.triangle[r][i] = 1;
else
this.triangle[r][i] = this.triangle[r-1][i-1]+this.triangle[r-1][i];
}
}
// Method to print the triangle
this.print = function(base) {
if (!base)
base = 10;
// Private method to calculate digits in number
var digits = function(n,b) {
var d = 0;
while (n >= 1) {
d++;
n /= b;
}
return d;
}
// Calculate max spaces needed
var spacing = digits(this.triangle[this.rows-1][Math.round(this.rows/2)],base);
// Private method to add spacing between numbers
var insertSpaces = function(s) {
var buf = "";
while (s > 0) {
s--;
buf += " ";
}
return buf;
}
// Print the triangle line by line
for (var r = 0; r < this.triangle.length; r++) {
var l = "";
for (var s = 0; s < Math.round(this.rows-1-r); s++) {
l += insertSpaces(spacing);
}
for (var i = 0; i < this.triangle[r].length; i++) {
if (i != 0)
l += insertSpaces(spacing-Math.ceil(digits(this.triangle[r][i],base)/2));
l += this.triangle[r][i].toString(base);
if (i < this.triangle[r].length-1)
l += insertSpaces(spacing-Math.floor(digits(this.triangle[r][i],base)/2));
}
print(l);
}
}
}
// Display 4 row triangle in base 10
var tri = new pascalTriangle(4);
tri.print();
// Display 8 row triangle in base 16
tri = new pascalTriangle(8);
tri.print(16);

View file

@ -0,0 +1,9 @@
pascal:{(x-1){+':0,x,0}\1}
pascal 6
(1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1)

View file

@ -0,0 +1,19 @@
input "How much rows would you like? "; n
dim a$(n)
for i= 0 to n
c = 1
o$ =""
for k =0 to i
o$ =o$ ; c; " "
c =c *(i-k)/(k+1)
next k
a$(i)=o$
next i
maxLen = len(a$(n))
for i= 0 to n
print space$((maxLen-len(a$(i)))/2);a$(i)
next i
end

View file

@ -0,0 +1,12 @@
10 CLS
20 INPUT "Number of rows? ", rows:GOSUB 40
30 END
40 FOR i=0 TO rows-1
50 c=1
60 FOR k=0 TO i
70 PRINT USING "####";c;
80 c=c*(i-k)/(k+1)
90 NEXT
100 PRINT
110 NEXT
120 RETURN

View file

@ -0,0 +1,7 @@
to pascal :n
if :n = 1 [output [1]]
localmake "a pascal :n-1
output (sentence first :a (map "sum butfirst :a butlast :a) last :a)
end
for [i 1 10] [print pascal :i]

View file

@ -0,0 +1,14 @@
function nextrow(t)
local ret = {}
t[0], t[#t+1] = 0, 0
for i = 1, #t do ret[i] = t[i-1] + t[i] end
return ret
end
function triangle(n)
t = {1}
for i = 1, n do
print(unpack(t))
t = nextrow(t)
end
end

View file

@ -0,0 +1 @@
pascal(n);

View file

@ -0,0 +1 @@
binomCoeff = diag(rot90(pascal(n)))',

View file

@ -0,0 +1,2 @@
Column[StringReplace[ToString /@ Replace[MatrixExp[SparseArray[
{Band[{2,1}] -> Range[n-1]},{n,n}]],{x__,0..}->{x},2] ,{"{"|"}"|","->" "}], Center]

View file

@ -0,0 +1,12 @@
sjoin(v, j) := apply(sconcat, rest(join(makelist(j, length(v)), v)))$
display_pascal_triangle(n) := for i from 0 thru 6 do disp(sjoin(makelist(binomial(i, j), j, 0, i), " "));
display_pascal_triangle(6);
/* "1"
"1 1"
"1 2 1"
"1 3 3 1"
"1 4 6 4 1"
"1 5 10 10 5 1"
"1 6 15 20 15 6 1" */

View file

@ -0,0 +1,18 @@
vardef bincoeff(expr n, k) =
save ?;
? := (1 for i=(max(k,n-k)+1) upto n: * i endfor )
/ (1 for i=2 upto min(k, n-k): * i endfor); ?
enddef;
def pascaltr expr c =
string s_;
for i := 0 upto (c-1):
s_ := "" for k=0 upto (c-i): & " " endfor;
s_ := s_ for k=0 upto i: & decimal(bincoeff(i,k))
& " " if bincoeff(i,k)<9: & " " fi endfor;
message s_;
endfor
enddef;
pascaltr(4);
end

View file

@ -0,0 +1,5 @@
factorial is recur [ 0 =, 1 first, pass, product, -1 +]
combination is fork [ > [first, second], 0 first,
/ [factorial second, * [factorial - [second, first], factorial first] ]
]
pascal is transpose each combination cart [pass, pass] tell

View file

@ -0,0 +1,2 @@
|loaddefs 'pascal.nial'
|pascal 5

View file

@ -0,0 +1,10 @@
(* generate next row from current row *)
let next_row row =
List.map2 (+) ([0] @ row) (row @ [0])
(* returns the first n rows *)
let pascal n =
let rec loop i row =
if i = n then []
else row :: loop (i+1) (next_row row)
in loop 0 [1]

View file

@ -0,0 +1,13 @@
function pascaltriangle(h)
for i = 0:h-1
for k = 0:h-i
printf(" ");
endfor
for j = 0:i
printf("%3d ", bincoeff(i, j));
endfor
printf("\n");
endfor
endfunction
pascaltriangle(4);

View file

@ -0,0 +1,31 @@
declare
fun {NextLine Xs}
{List.zip 0|Xs {Append Xs [0]}
fun {$ Left Right}
Left + Right
end}
end
fun {Triangle N}
{List.take {Iterate [1] NextLine} N}
end
fun lazy {Iterate I F}
I|{Iterate {F I} F}
end
%% Only works nicely for N =< 5.
proc {PrintTriangle T}
N = {Length T}
in
for
Line in T
Indent in N-1..0;~1
do
for _ in 1..Indent do {System.printInfo " "} end
for L in Line do {System.printInfo L#" "} end
{System.printInfo "\n"}
end
end
in
{PrintTriangle {Triangle 5}}

View file

@ -0,0 +1,15 @@
pascals_triangle(N)= {
my(row=[],prevrow=[]);
for(x=1,N,
if(x>5,break(1));
row=eval(Vec(Str(11^(x-1))));
print(row));
prevrow=row;
for(y=6,N,
for(p=2,#prevrow,
row[p]=prevrow[p-1]+prevrow[p]);
row=concat(row,1);
prevrow=row;
print(row);
);
}

View file

@ -0,0 +1,23 @@
function pascalsTriangle($num){
$c = 1;
$triangle = Array();
for($i=0;$i<=$num;$i++){
$triangle[$i] = Array();
if(!isset($triangle[$i-1])){
$triangle[$i][] = $c;
}else{
for($j=0;$j<count($triangle[$i-1])+1;$j++){
$triangle[$i][] = (isset($triangle[$i-1][$j-1]) && isset($triangle[$i-1][$j])) ? $triangle[$i-1][$j-1] + $triangle[$i-1][$j] : $c;
}
}
}
return $triangle;
}
$tria = pascalsTriangle(8);
foreach($tria as $val){
foreach($val as $value){
echo $value . ' ';
}
echo '<br>';
}

View file

@ -0,0 +1,15 @@
declare (t, u)(40) fixed binary;
declare (i, n) fixed binary;
t,u = 0;
get (n);
if n <= 0 then return;
do n = 1 to n;
u(1) = 1;
do i = 1 to n;
u(i+1) = t(i) + t(i+1);
end;
put skip edit ((u(i) do i = 1 to n)) (col(40-2*n), (n+1) f(4));
t = u;
end;

View file

@ -0,0 +1,11 @@
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1

View file

@ -0,0 +1,21 @@
Program PascalsTriangle(output);
procedure Pascal(r : Integer);
var
i, c, k : Integer;
begin
for i := 0 to r-1 do
begin
c := 1;
for k := 0 to i do
begin
write(c:3);
c := (c * (i-k)) div (k+1);
end;
writeln;
end;
end;
begin
Pascal(9)
end.

View file

@ -0,0 +1,7 @@
multi pascal (1) { [1] }
multi pascal (Int $n where 2..*) {
my @rows = pascal $n - 1;
@rows, [0, @rows[*-1][] Z+ @rows[*-1][], 0 )];
}
say .perl for pascal 10;

View file

@ -0,0 +1,8 @@
sub pascal ($n where $n >= 1) {
# Prints out $n rows of Pascal's triangle.
say my @last = 1;
for 1 .. $n - 1 -> $row {
my @this = map { @last[$_] + @last[$_ + 1] }, 0 .. $row - 2;
say @last = 1, @this, 1;
}
}

View file

@ -0,0 +1,3 @@
sub pascal { [1], -> @p { [0, @p Z+ @p, 0] } ... * }
.say for pascal[^10];

View file

@ -0,0 +1,3 @@
constant Pascal = [1], -> @p { [0, @p Z+ @p, 0] } ... *;
.say for Pascal[^10];

View file

@ -0,0 +1,13 @@
sub pascal
# Prints out $n rows of Pascal's triangle. It returns undef for
# failure and 1 for success.
{my $n = shift;
$n < 1 and return undef;
print "1\n";
$n == 1 and return 1;
my @last = (1);
foreach my $row (1 .. $n - 1)
{my @this = map {$last[$_] + $last[$_ + 1]} 0 .. $row - 2;
@last = (1, @this, 1);
print join(' ', @last), "\n";}
return 1;}

View file

@ -0,0 +1,3 @@
use bignum;
sub pascal { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 }
print "@{[map -+-$_, pascal $_]}\n" for 0..22;

View file

@ -0,0 +1,8 @@
(de pascalTriangle (N)
(for I N
(space (* 2 (- N I)))
(let C 1
(for K I
(prin (align 3 C) " ")
(setq C (*/ C (- I K) K)) ) )
(prinl) ) )

View file

@ -0,0 +1,64 @@
$Infinity = 1
$NewNumbers = $null
$Numbers = $null
$Result = $null
$Number = $null
$Power = $args[0]
Write-Host $Power
For(
$i=0;
$i -lt $Infinity;
$i++
)
{
$Numbers = New-Object Object[] 1
$Numbers[0] = $Power
For(
$k=0;
$k -lt $NewNumbers.Length;
$k++
)
{
$Numbers = $Numbers + $NewNumbers[$k]
}
If(
$i -eq 0
)
{
$Numbers = $Numbers + $Power
}
$NewNumbers = New-Object Object[] 0
Try
{
For(
$j=0;
$j -lt $Numbers.Length;
$j++
)
{
$Result = $Numbers[$j] + $Numbers[$j+1]
$NewNumbers = $NewNumbers + $Result
}
}
Catch [System.Management.Automation.RuntimeException]
{
Write-Warning "Value was too large for a Decimal. Script aborted."
Break;
}
Foreach(
$Number in $Numbers
)
{
If(
$Number.ToString() -eq "+unendlich"
)
{
Write-Warning "Value was too large for a Decimal. Script aborted."
Exit
}
}
Write-Host $Numbers
$Infinity++
}

View file

@ -0,0 +1,36 @@
pascal(N) :-
pascal(1, N, [1], [[1]|X]-X, L),
maplist(my_format, L).
pascal(Max, Max, L, LC, LF) :-
!,
make_new_line(L, NL),
append_dl(LC, [NL|X]-X, LF-[]).
pascal(N, Max, L, NC, LF) :-
build_new_line(L, NL),
append_dl(NC, [NL|X]-X, NC1),
N1 is N+1,
pascal(N1, Max, NL, NC1, LF).
build_new_line(L, R) :-
build(L, 0, X-X, R).
build([], V, RC, RF) :-
append_dl(RC, [V|Y]-Y, RF-[]).
build([H|T], V, RC, R) :-
V1 is V+H,
append_dl(RC, [V1|Y]-Y, RC1),
build(T, H, RC1, R).
append_dl(X1-X2, X2-X3, X1-X3).
% to have a correct output !
my_format([H|T]) :-
write(H),
maplist(my_writef, T),
nl.
my_writef(X) :-
writef(' %5r', [X]).

View file

@ -0,0 +1,18 @@
?- pascal(15).
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
1 12 66 220 495 792 924 792 495 220 66 12 1
1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
1 15 105 455 1365 3003 5005 6435 6435 5005 3003 1365 455 105 15 1
true.

View file

@ -0,0 +1,17 @@
Procedure pascaltriangle( n.i)
For i= 0 To n
c = 1
For k=0 To i
Print(Str( c)+" ")
c = c * (i-k)/(k+1);
Next ;k
PrintN(" "); nächste zeile
Next ;i
EndProcedure
OpenConsole()
Parameter.i = Val(ProgramParameter(0))
pascaltriangle(Parameter);
Input()

View file

@ -0,0 +1,9 @@
def pascal(n):
"""Prints out n rows of Pascal's triangle.
It returns False for failure and True for success."""
row = [1]
k = [0]
for x in range(max(n,0)):
print row
row=[l+r for l,r in zip(row+k,k+row)]
return n>=1

View file

@ -0,0 +1,17 @@
def scan(op, seq, it):
a = []
result = it
a.append(it)
for x in seq:
result = op(result, x)
a.append(result)
return a
def pascal(n):
def nextrow(row, x):
return [l+r for l,r in zip(row+[0,],[0,]+row)]
return scan(nextrow, range(n-1), [1,])
for row in pascal(4):
print(row)

View file

@ -0,0 +1,9 @@
(define iterate
_ _ 0 -> []
F V N -> [V|(iterate F (F V) (1- N))])
(define next-row
R -> (MAPCAR + [0|R] (append R [0])))
(define pascal
N -> (iterate next-row [1] N))

View file

@ -0,0 +1,10 @@
pascalTriangle <- function(h) {
for(i in 0:(h-1)) {
s <- ""
for(k in 0:(h-i)) s <- paste(s, " ", sep="")
for(j in 0:i) {
s <- paste(s, sprintf("%3d ", choose(i, j)), sep="")
}
print(s)
}
}

View file

@ -0,0 +1,3 @@
pascalTriangle <- function(h) {
lapply(0:h, function(i) choose(i, 0:i))
}

View file

@ -0,0 +1,28 @@
/*REXX program to display Pascal's triangle, neatly centered/formatted.*/
/*AKA: Yang Hui's ▲, Khayyam-Pascal ▲, Kyayyam ▲, Tartaglia's ▲ */
numeric digits 1000 /*let's be able to handle big ▲. */
arg nn .; if nn=='' then nn=10; n=abs(nn)
a. = 1 /*if NN < 0, output is to a file.*/
mx = !(n-1) / !(n%2) / !(n-1-n%2) /*MX =biggest number in triangle.*/
w = length(mx) /* W =width of biggest number. */
line. = 1
do row=1 for n; prev=row-1
a.row.1 = 1
do j=2 to row-1; jm=j-1
a.row.j = a.prev.jm + a.prev.j
line.row = line.row right(a.row.j,w)
end /*j*/
if row\==1 then line.row=line.row right(1,w) /*append the last "1".*/
end /*row*/
width=length(line.n) /*width of last line in triangle.*/
do L=1 for n /*show lines in Pascal's triangle*/
if nn>0 then say center(line.L,width) /*either SAY or write.*/
else call lineout 'PASCALS.'n, center(line.L,width)
end /*L*/
exit /*stick a fork in it, we're done.*/
/*─────────────────────────────────────! (factorial) subroutine─────────*/
!: procedure; arg x;!=1;do j=2 to x;!=!*j;end;return ! /*calc. factorial*/

View file

@ -0,0 +1,14 @@
#lang racket
(define (pascal n)
(define (next-row current-row)
(map + (cons 0 current-row)
(append current-row '(0))))
(let-values
([(previous-rows final-row)
(for/fold ([triangle null]
[row '(1)])
([row-number (in-range 1 n)])
(values (cons row triangle)
(next-row row)))])
(reverse (cons final-row previous-rows))))

View file

@ -0,0 +1,12 @@
DEFINT values(100) = {0,1}
INPUT "Number of rows: "; nrows
PRINT SPACE$((nrows)*3);" 1"
FOR row = 2 TO nrows
PRINT SPACE$((nrows-row)*3+1);
FOR i = row TO 1 STEP -1
values(i) = values(i) + values(i-1)
PRINT FORMAT$("%5d ", values(i));
NEXT i
PRINT
NEXT row

View file

@ -0,0 +1,10 @@
INPUT "Number of rows: "; nrows
FOR row = 0 TO nrows-1
c = 1
PRINT SPACE$((nrows-row)*3);
FOR i = 0 TO row
PRINT FORMAT$("%5d ", c);
c = c * (row - i) / (i+1)
NEXT i
PRINT
NEXT row

View file

@ -0,0 +1,6 @@
2 elements i j
: pascalTriangle
cr dup
[ dup !j 1 swap 1+ [ !i dup putn space @j @i - * @i 1+ / ] iter cr drop ] iter drop
;
13 pascalTriangle

View file

@ -0,0 +1,27 @@
def pascal(n = 1)
return if n < 1
# set up a new array of arrays with the first value
p = [[1]]
# for n - 1 number of times,
(n - 1).times do |i|
# inject a new array starting with [1]
p << p[i].inject([1]) do |result, elem|
# if we've reached the end, tack on a 1.
# else, tack on current elem + previous elem
if p[i].length == result.length
result << 1
else
result << elem + p[i][result.length]
end
end
end
# and return the triangle.
p
end

View file

@ -0,0 +1,3 @@
def next_row row ; ([0] + row).zip(row + [0]).collect {|l,r| l + r }; end
def pascal n ; ([nil] * n).inject([1]) {|x,y| y = next_row x } ; end

Some files were not shown because too many files have changed in this diff Show more