Created
August 8, 2016 00:53
-
-
Save darkua/619d1798f13d3ff35bed52b156b1b442 to your computer and use it in GitHub Desktop.
get a list, and jump n[i] positions to next element until out of index, In a time complexity of O(N)
This file contains hidden or 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(var1). | |
-author("Sergio Veiga <[email protected]>"). | |
% get a list, and jump n[i] positions to next element until out of index | |
% In a time complexity of O(N) | |
% Has the graph loops? | |
% How many jumps to destination? | |
-export([ | |
calculate_jumps/1, | |
test/0 | |
]). | |
-spec calculate_jumps([integer()]) -> {ok, pos_integer()} | never. | |
calculate_jumps(A) -> | |
F = fun()->Numbers = list_to_tuple(A),loop(0, 1, Numbers) end, | |
{T,Res} = timer:tc(F), | |
io:format("In T:~p Res:~p\n",[T,Res]). | |
loop(Jumps, Position,_) when Position < 1 -> | |
{ ok, Jumps }; | |
loop(Jumps, Position, Numbers) when Position > size(Numbers) -> | |
{ ok, Jumps }; | |
loop(Jumps, _, Numbers) when Jumps > size(Numbers) -> | |
never; | |
loop(Jumps, Position, Numbers) -> | |
El = element(Position, Numbers), | |
NewPosition = Position + El, | |
loop(Jumps+1, NewPosition, Numbers). | |
test() -> | |
{ ok, 4 } = calculate_jumps([2,3,-1,1,3]), | |
never = calculate_jumps([1,1,-1,1]), | |
ok. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment