From 0f744688b1683451627ce6c36a91de85726eb742 Mon Sep 17 00:00:00 2001 From: Andrew Tomaka Date: Sun, 22 Dec 2024 19:40:54 -0500 Subject: [PATCH] start multiple paths --- 21/main.rb | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/21/main.rb b/21/main.rb index e220ba4..f1da4a1 100755 --- a/21/main.rb +++ b/21/main.rb @@ -74,6 +74,14 @@ def dijkstra_with_lookup(graph, movements, start_char, target_char) dijkstra(graph, movements, start, target) 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) queue = PriorityQueue.new dest = Hash.new @@ -90,22 +98,20 @@ def dijkstra(graph, movements, start, target) .map { @arrow_dirs[_1] } .map { |dx, dy| [node.first + dx, node.last + dy] } .each do |neighbor| - if dest[neighbor].nil? || moves + 1 < dest[neighbor] - dest[neighbor] = moves + 1 - prev[neighbor] = node - queue << [neighbor, moves + 1] + new_moves = moves + 1 + if dest[neighbor].nil? || new_moves < dest[neighbor] + dest[neighbor] = new_moves + prev[neighbor] = [node] + queue << [neighbor, new_moves] + elsif new_moves == dest[neighbor] + prev[neighbor] << node end end end - path = Array.new - u = target - while prev[u] - path.unshift(u) - u = prev[u] - end + paths = dijkstra_paths(prev, target) - return dest, path + return dest, paths.first end # calculate most efficient number pad paths @@ -145,6 +151,7 @@ robot_2 = input .map { _1.each_cons(2).to_a } .map { _1.map { |move| number_cache[move].join }.join("A") + "A" } +debugger robot_3 = robot_2 .map { _1.chars } @@ -158,7 +165,7 @@ me = robot_3 .map { _1.each_cons(2).to_a } .map { _1.map { |move| arrow_cache[move].join }.join("A") + "A" } -pp " >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A" +pp ">^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A" pp me me.each_with_index do |entry, i|