1
0
Fork 0

start multiple paths

This commit is contained in:
Andrew Tomaka 2024-12-22 19:40:54 -05:00
parent 45056ce1fa
commit 0f744688b1
Signed by: atomaka
GPG key ID: 61209BF70A5B18BE

View file

@ -74,6 +74,14 @@ def dijkstra_with_lookup(graph, movements, start_char, target_char)
dijkstra(graph, movements, start, target) dijkstra(graph, movements, start, target)
end end
def dijkstra_paths(prev, target, current_path = [])
return [current_path.reverse] if prev[target].nil?
prev[target].flat_map do |parent|
dijkstra_paths(prev, parent, current_path + [target])
end
end
def dijkstra(graph, movements, start, target) def dijkstra(graph, movements, start, target)
queue = PriorityQueue.new queue = PriorityQueue.new
dest = Hash.new dest = Hash.new
@ -90,22 +98,20 @@ def dijkstra(graph, movements, start, target)
.map { @arrow_dirs[_1] } .map { @arrow_dirs[_1] }
.map { |dx, dy| [node.first + dx, node.last + dy] } .map { |dx, dy| [node.first + dx, node.last + dy] }
.each do |neighbor| .each do |neighbor|
if dest[neighbor].nil? || moves + 1 < dest[neighbor] new_moves = moves + 1
dest[neighbor] = moves + 1 if dest[neighbor].nil? || new_moves < dest[neighbor]
prev[neighbor] = node dest[neighbor] = new_moves
queue << [neighbor, moves + 1] prev[neighbor] = [node]
queue << [neighbor, new_moves]
elsif new_moves == dest[neighbor]
prev[neighbor] << node
end end
end end
end end
path = Array.new paths = dijkstra_paths(prev, target)
u = target
while prev[u]
path.unshift(u)
u = prev[u]
end
return dest, path return dest, paths.first
end end
# calculate most efficient number pad paths # calculate most efficient number pad paths
@ -145,6 +151,7 @@ robot_2 = input
.map { _1.each_cons(2).to_a } .map { _1.each_cons(2).to_a }
.map { _1.map { |move| number_cache[move].join }.join("A") + "A" } .map { _1.map { |move| number_cache[move].join }.join("A") + "A" }
debugger
robot_3 = robot_2 robot_3 = robot_2
.map { _1.chars } .map { _1.chars }