3 ms·
5 minute Erlang version: -module(pascal). -export([tri/1]). tri(Depth) -> tri(Depth,[[1]]). calc_row_rest([_]) -> [1]; calc_row_rest([X,Y |
by chops 15y ago
5 minute Erlang version:
-module(pascal).
-export([tri/1]).
tri(Depth) ->
tri(Depth,[[1]]).
calc_row_rest([_]) ->
[1];
calc_row_rest([X,Y | Rest]) ->
[X + Y | calc_row_rest([Y | Rest])].
calc_row(Acc) ->
[1 | calc_row_rest(Acc)].
tri(X,_) when X =< 0 ->
[];
tri(1,Acc) ->
lists:reverse(Acc);
tri(Depth,Acc) ->
NewRow = calc_row(hd(Acc)),
tri(Depth-1,[NewRow | Acc]).
Returns a list of the pascal triangle rows:
> pascal:tri(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]]