Skip to content

Instantly share code, notes, and snippets.

@jesspoe
Last active June 13, 2019 23:15
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 jesspoe/33501e78122251ee6578673382a861eb to your computer and use it in GitHub Desktop.
Save jesspoe/33501e78122251ee6578673382a861eb to your computer and use it in GitHub Desktop.
a = [1, 1 ,1 ,1 ,0]
b = [5, 1 ,4 ,6 ,7, 5, 2, 0, 4]
c = [1, 1 ,4 ,6 ,7, 5, 2, 0, 4]
def dragon(array)
jump_array = [0]
max_jumps = array[0]
if jump_array.length == 1 && array[0] == 0
return "failure"
end
array.each_with_index do |number, index|
if max_jumps >= array.length
jump_array.push("out")
return jump_array
elsif array[max_jumps] != 0
jump_array.push(max_jumps)
new_max_jumps = array[max_jumps]
max_jumps = max_jumps + new_max_jumps
elsif array[max_jumps] == 0
max_jumps = max_jumps - 1
if array[max_jumps] == 1
return "failure"
elsif array[max_jumps] < (array.length - max_jumps)
jump_array.push(max_jumps)
jump_array.push("out")
elsif array[max_jumps] >= (array.length - max_jumps)
max_jumps = max_jumps - 1
end
end
end
end
def shortest_path(array)
# TODO: Handle empty array input here
shortest_path_from_index(array, 0) || 'failure'
end
def shortest_path_from_index(array, current_index)
return ['out'] if current_index >= array.length
max_jumps = array[current_index]
return nil if max_jumps == 0
shortest_path = nil
(current_index+1..current_index+max_jumps).each do |next_index|
path = shortest_path_from_index(array, next_index)
if path.nil?
# If path is nil, go to next iteration
next
elsif shortest_path.nil? || (path.length + 1) < shortest_path.length
# If shortest_path is nil, or if the new path is shorter, then it's our new shortest path
shortest_path = [current_index] + path
end
end
shortest_path
end
puts dragon(a)
puts dragon(b)
puts dragon(c)
puts "Shortest path for a: #{shortest_path(a)}"
puts "Shortest path for b: #{shortest_path(b)}"
puts "Shortest path for c: #{shortest_path(c)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment