Created
November 17, 2013 22:09
-
-
Save ggPeti/7518886 to your computer and use it in GitHub Desktop.
A linear time solution for the ArrayHopper problem.
This file contains 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
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