Skip to content

Instantly share code, notes, and snippets.

@cupakromer
Last active October 13, 2015 22:18
Show Gist options
  • Save cupakromer/4264733 to your computer and use it in GitHub Desktop.
Save cupakromer/4264733 to your computer and use it in GitHub Desktop.
Array Jump solution
#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;
}
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
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