prolog pascal triangle
hi is there anybody know how can i do the pascal nth row when i开发者_如何学运维 ask for :? pascal(2,Row). i get Row=[1,2,1] ??
please help me
Here is the code to compute the nth row.
The first part scans a row, to compute the next row. The first row must be prefixed with a 0, so that the first "1" in the next row is a sum, like the other elements. It recurses on the 2 lists:
pascal_next_row([X],[X]).
pascal_next_row([H,H2|T],[A|B]):-
pascal_next_row([H2|T],B),
A is H + H2.
The second part computes all the rows until the one which was asked. It recurses on N:
pascal(0, [1]) :- !.
pascal(N, R) :-
N1 is N-1,
pascal(N1, R1),
pascal_next_row([0|R1], R).
If you need the full triangle, all you have to do is change the second parameter to handle a list of rows, and collect them:
pascal(0, [[1]]) :- !.
pascal(N, [R, R1 | RN]) :-
N1 is N-1,
pascal(N1, [R1 | RN]),
pascal_next_row([0|R1], R).
This answer to a code golf has the implementation in prolog, just expand the names:
The Pascal Triangle is also known as the Tartaglia Triangle:
sumC([X,Y],[Z]) :- Z is X + Y.
sumC([X,Y|L], Z):- H is X + Y,
sumC([Y|L],L2),
Z = [H|L2].
tartaglia(1,[1]) :- ! .
tartaglia(2,[1,1]) :- !.
tartaglia(N, L) :- Ant is N - 1,
tartaglia(Ant,L2),
sumC(L2,R),
append([1|R],[1],L), !.
Using the helper predicate sumC, you can get it easily:
?- tartaglia(3,R).
R = [1, 2, 1].
?- tartaglia(2,R).
R = [1, 1].
?- tartaglia(1,R).
R = [1].
?- tartaglia(6,R).
R = [1, 5, 10, 10, 5, 1].
As said in my comment. You ask for the nth row. [1,2,1] from your example is the 3rd row.
精彩评论