Last active
October 13, 2015 22:18
-
-
Save cupakromer/4264733 to your computer and use it in GitHub Desktop.
Array Jump solution
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
#define MAX_STEPS 100000 | |
#define NO_SOLUTION -1 | |
int arrayJump(int *A, int size) { | |
int *p = A, steps = 0; | |
while (++steps < MAX_STEPS && A <= (p+=*p) && p < A+size); | |
return steps >= MAX_STEPS ? NO_SOLUTION : steps; | |
} |
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
def array_jump(relative_moves) | |
absolute_moves = relative_moves.each_with_index | |
.map{ |step, index| step + index } | |
exit_indexes = absolute_moves.each_index | |
.select{ |idx| | |
absolute_moves[idx] < 0 || | |
absolute_moves[idx] >= absolute_moves.size } | |
exit_indexes.empty? ? no_solution | |
: jumps_by_traversal(absolute_moves, exit_indexes) | |
end | |
def jumps_by_traversal(moves, exits) | |
index = jumps = 0 | |
until exits.include? index do | |
jumps += 1 | |
index, tmp, moves[tmp] = moves[index], index, :in_loop | |
return infinite_loop if :in_loop == index | |
end | |
jumps + 1 | |
end | |
def no_solution() -1 end | |
def infinite_loop() no_solution end |
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
def array_jump(relative_moves) | |
absolute_moves = relative_moves.each_with_index | |
.map{ |step, index| step + index } | |
jumps_by_traversal absolute_moves | |
end | |
def jumps_by_traversal(moves) | |
index = jumps = 0 | |
begin | |
jumps += 1 | |
# Mark as seen and get next index | |
tmp, index, moves[tmp] = index, moves[index], :in_loop | |
return infinite_loop if :in_loop == index | |
end until index < 0 || index >= moves.size | |
jumps | |
end | |
def infinite_loop() -1 end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment