Skip to content

Instantly share code, notes, and snippets.

@ggPeti
Created November 17, 2013 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ggPeti/7518886 to your computer and use it in GitHub Desktop.
Save ggPeti/7518886 to your computer and use it in GitHub Desktop.
A linear time solution for the ArrayHopper problem.
numbers = File.read(ARGV.first).split.map &:to_i
best_path = [0]
loop do
current_pos = best_path.last
max_hop = numbers[current_pos]
candidates = (1..max_hop).map { |hop| current_pos + hop }
if candidates.empty?
best_path = ["failure"]
break
end
if candidates.any? { |pos| pos >= numbers.length }
best_path << "out"
break
end
best_path << candidates.max_by { |pos| [numbers[pos] + pos, pos] }
end
puts best_path.join ", "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment