Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

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,29 @@
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Produce a pascal's triangle of depth N
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Prolog is declarative. The predicate pascal/3 below says that to produce
% a row of depth N, we can do so by first producing the row at depth(N-1),
% and then adding the paired values in that row. The triangle is produced
% by prepending the row at N-1 to the preceding rows as recursion unwinds.
% The triangle produced by pascal/3 is upside down and lacks the last row,
% so pascal/2 prepends the last row to the triangle and reverses it.
% Finally, pascal/1 produces the triangle, iterates each row and prints it.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pascal_row([V], [V]). % No more value pairs to add
pascal_row([V0, V1|T], [V|Rest]) :- % Add values from preceding row
V is V0 + V1, !, pascal_row([V1|T], Rest). % Drops initial value (1).
pascal(1, [1], []). % at depth 1, this row is [1] and no preceding rows.
pascal(N, [1|ThisRow], [Last|Preceding]) :- % Produce a row of depth N
succ(N0, N), % N is the successor to N0
pascal(N0, Last, Preceding), % Get the previous row
!, pascal_row(Last, ThisRow). % Calculate this row from the previous
pascal(N, Triangle) :-
pascal(N, Last, Rows), % Retrieve row at depth N and preceding rows
!, reverse([Last|Rows], Triangle). % Add last row to triangle and reverse order
pascal(N) :-
pascal(N, Triangle), member(Row, Triangle), % Iterate and write each row
write(Row), nl, fail.
pascal(_).

View file

@ -0,0 +1,6 @@
?- pascal(5).
[1]
[1,1]
[1,2,1]
[1,3,3,1]
[1,4,6,4,1]