Created
May 19, 2011 20:16
-
-
Save mmccollow/981622 to your computer and use it in GitHub Desktop.
Generates a Pascal's Triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(pascal). | |
-export([triangle/1]). | |
% Generates a Pascal's Triangle | |
% 1. Start Erlang interpreter in folder with this file | |
% 2. Do: c(pascal). | |
% 3. Do: pascal:triangle(5). | |
% Which would create a Pascal's Triangle 5 lines deep. | |
% calculate factorial | |
fact(0) -> 1; | |
fact(N) when N > 0, is_integer(N) -> N * fact(N-1). | |
% calculate binomial coefficient of N choose R | |
bin_coef({N, R}) -> | |
fact(N) div (fact(N-R) * fact(R)). | |
% draw a line N integers wide | |
draw_line(0) -> | |
io:format("~B~n", [1]); | |
draw_line(1) -> | |
io:format("~B ~B~n",[1,1]); | |
draw_line(N) -> | |
Elements = lists:zip(lists:duplicate(N+1, N), lists:seq(0, N)), | |
Line = [bin_coef(L) || L <- Elements], | |
lists:map(fun(I) -> io:format("~B ", [I]) end, Line), | |
io:format("~n"). | |
% draw pascal's triangle | |
triangle(N) -> | |
Lines = lists:seq(0, N), | |
[draw_line(L) || L <- Lines]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment