Created
February 22, 2017 09:06
-
-
Save oscherler/fe2465c53657522e71e479f9278f20bc to your computer and use it in GitHub Desktop.
Recursion exercise in Erlang.
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( pieces ). | |
% I export fac and binomial so I can play in the shell. | |
-export( [ fac/1, binomial/2, pieces/2, test2d/0, test3d/0 ] ). | |
% Hopefully tail-recursive factorial. I’ve been reading ahead ;) | |
fac( N ) -> | |
fac( 1, N ). | |
fac( Acc, 0 ) -> | |
Acc; | |
fac( Acc, N ) when N > 0 -> | |
fac( Acc * N, N - 1 ). | |
% Binomial that accepts K > N (probably doesn’t follow the let it fail philosophy) | |
binomial( N, K ) when N >= 0, K > N -> | |
0; | |
binomial( N, K ) when N >= 0 -> | |
fac:fac( N ) / ( fac:fac( K ) * ( fac:fac( N - K ) ) ). | |
% Function derived from https://en.wikipedia.org/wiki/Cake_number | |
pieces( 0, Cuts ) -> | |
binomial( Cuts, 0 ); | |
pieces( Dimensions, Cuts ) -> | |
binomial( Cuts, Dimensions ) + pieces( Dimensions - 1, Cuts ). | |
testSequence( Expected, Function ) -> | |
Result = lists:map( Function, lists:seq( 0, length( Expected ) - 1 ) ), | |
Result == Expected. | |
% Expected values from https://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence | |
test2d() -> | |
Expected = [ 1, 2, 4, 7, 11, 16, 22, 29, 37 ], | |
testSequence( Expected, fun( N ) -> pieces( 2, N ) end ). | |
% Expected values from https://en.wikipedia.org/wiki/Cake_number | |
test3d() -> | |
Expected = [ 1, 2, 4, 8, 15, 26, 42, 64, 93 ], | |
testSequence( Expected, fun( N ) -> pieces( 3, N ) end ). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment