Created
August 31, 2010 02:48
-
-
Save limitedmage/558452 to your computer and use it in GitHub Desktop.
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
%% ITESM CEM, August 31, 2010. | |
%% Erlang Source File | |
%% Activity: Recursive Functions | |
%% Author: Juliana Pena, 1165536 | |
-module(recursion). | |
-export([but_last/1, merge/2, insert/2, sort/1, binary/1, bcd/1, prime_factors/1, compress/1, encode/1, decode/1]). | |
but_last([_]) -> []; | |
but_last([H|T]) -> [H|but_last(T)]. | |
insert(A, []) -> [A]; | |
insert(A, [H|T]) -> | |
if | |
H >= A -> [A, H | T]; | |
true -> [H | insert(A, T)] | |
end. | |
merge(A, []) -> A; | |
merge([], B) -> B; | |
merge([Ha|Ta], [Hb|Tb]) -> | |
if | |
Ha < Hb -> [Ha | merge(Ta, [Hb|Tb])]; | |
true -> [Hb | merge([Ha|Ta], Tb)] | |
end. | |
sort([]) -> []; | |
sort([H|T]) -> insert(H, sort(T)). | |
binary(0) -> []; | |
binary(N) -> binary(N div 2) ++ [N rem 2]. | |
bcd(N) when N < 10 -> | |
if | |
N == 0 -> ["0000"]; | |
N == 1 -> ["0001"]; | |
N == 2 -> ["0010"]; | |
N == 3 -> ["0011"]; | |
N == 4 -> ["0100"]; | |
N == 5 -> ["0101"]; | |
N == 6 -> ["0110"]; | |
N == 7 -> ["0111"]; | |
N == 8 -> ["1000"]; | |
N == 9 -> ["1001"] | |
end; | |
bcd(N) -> | |
bcd(N div 10) ++ bcd(N rem 10). | |
prime_factors(N) -> prime_helper(N, 2). | |
prime_helper(N, Factor) -> | |
if | |
N == 1 -> []; | |
Factor == N -> [N]; | |
N rem Factor == 0 -> [Factor | prime_helper(N div Factor, Factor)]; | |
true -> prime_helper(N, Factor + 1) | |
end. | |
compress([]) -> []; | |
compress([A]) -> [A]; | |
compress([First | T]) -> | |
[Second | _] = T, | |
if | |
First == Second -> compress(T); | |
true -> [First | compress(T)] | |
end. | |
encode([]) -> []; | |
encode([A]) -> [A]; | |
encode([H|T]) -> encode_helper({1, H}, T). | |
encode_helper({Count, Element}, []) -> [{Count, Element}]; | |
encode_helper({Count, Element}, [H | T]) -> | |
if | |
Element == H -> encode_helper({Count + 1, Element}, T); | |
true -> | |
if | |
Count > 1 -> [{Count, Element} | encode_helper({1, H}, T)]; | |
true -> [Element | encode_helper({1, H}, T)] | |
end | |
end. | |
decode([]) -> []; | |
decode([{Count, Element} | T]) -> | |
decode_helper({Count, Element}) ++ decode(T); | |
decode([A | T]) -> | |
[A | decode(T)]. | |
decode_helper({0, _}) -> []; | |
decode_helper({Count, Element}) -> | |
[Element | decode_helper({Count - 1, Element})]. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment