Skip to content

Instantly share code, notes, and snippets.

@toddnestor
Last active December 13, 2016 00:54
Show Gist options
  • Save toddnestor/3b98433b08cd19e6fa15c3a837ba5d30 to your computer and use it in GitHub Desktop.
Save toddnestor/3b98433b08cd19e6fa15c3a837ba5d30 to your computer and use it in GitHub Desktop.
-module(numbers).
-export([fib/1, triangle_numbers/1, triangle_number/1, bsearch/2, pair_sum/2]).
fib(1)->
[0];
fib(2)->
[0,1];
fib(N)->
PrevFibs = fib(N-1),
lists:append(PrevFibs, [ lists:nth(length(PrevFibs) - 1, PrevFibs) + lists:last(PrevFibs) ] ).
triangle_numbers(1)->
[1];
triangle_numbers(N)->
PrevTriangles = triangle_numbers(N-1),
lists:append(PrevTriangles, [ lists:last(PrevTriangles) + N]).
triangle_number(N)->
(N + 1) * ( N / 2 ).
bsearch([], Target)->
false;
bsearch(Nums, Target)->
Pivot = (length(Nums) + 1) div 2,
case lists:nth(Pivot, Nums) of
Target ->
Pivot;
_ ->
case lists:nth(Pivot, Nums) > Target of
true ->
bsearch(lists:sublist(Nums, length(Nums) - Pivot), Target);
false ->
Searched = bsearch(lists:nthtail(Pivot, Nums), Target),
if
Searched == false ->
false;
true ->
Pivot + Searched
end
end
end.
all_equal(Num1, Num2, Num3)->
if
Num1 == Num2 ->
if
Num2 == Num3 ->
true;
true ->
false
end;
true ->
false
end.
pair_sum(Nums, Target)->
pair_sum(Nums, Target, 1, 2).
pair_sum(Nums, Target, Start, Current)->
NumsLength = length(Nums),
if
Start == NumsLength ->
[];
true ->
if
Current > NumsLength ->
pair_sum(Nums, Target, Start + 1, Start + 2);
true ->
NextPairSums = pair_sum(Nums, Target, Start, Current + 1),
PairSum = lists:nth(Start, Nums) + lists:nth(Current, Nums),
if
PairSum == Target ->
lists:append([[Start, Current]], NextPairSums);
true ->
NextPairSums
end
end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment