changeset 31:8590a79087a0

Day 16 part 1: only explore graph into certain depth
author Lewin Bormann <lbo@spheniscida.de>
date Mon, 19 Dec 2022 21:49:38 +0100
parents bf87eee356fc
children 05ddc45b4210
files 16/16.jl
diffstat 1 files changed, 14 insertions(+), 7 deletions(-) [+]
line wrap: on
line diff
--- a/16/16.jl	Mon Dec 19 21:42:08 2022 +0100
+++ b/16/16.jl	Mon Dec 19 21:49:38 2022 +0100
@@ -52,7 +52,6 @@
             valve.routes[neigh] = Peer(g[neigh].valve, 1);
         end
     end
-    #print_graph(g);
 
     count = 1;
     # While information propagates through the graph, keep updating.
@@ -68,32 +67,40 @@
         end
         @show count
     end
-    print_graph(g);
 end
 
 # Sort key
-function expected_total_flow(time::Int, node::Node, g::Dict{String,Node}, opened::Vector{String}=[])::Tuple{String,Int,Int}
+"""Return the total flow expected for node `node`, assuming it is opened at `time`, and the best path from it
+is followed (this works recursively).
+"""
+function expected_total_flow(time::Int, node::Node, g::Dict{String,Node}, opened::Vector{String}=[]; level=-1)::Tuple{String,Int,Int}
+    if level == 0
+        return ("", -1, -1);
+    end
     if in(node.valve.name, opened)
         return ("", -1, -1);
     end
     self = (30 - time - 1) * node.valve.flowrate;
     push!(opened, node.valve.name);
-    opts = [(vn, p.dist, expected_total_flow(time+1+p.dist, g[vn], g, opened)[3]) for (vn, p) in node.routes if p.valve.flowrate > 0];
+    opts = [(vn, p.dist, expected_total_flow(time+1+p.dist, g[vn], g, opened; level=level-1)[3]) for (vn, p) in node.routes if p.valve.flowrate > 0];
     pop!(opened);
     _, bestix = findmax(t -> t[3], opts);
     (opts[bestix][1], opts[bestix][2], opts[bestix][3]+self)
 end
 
+"""
+Starting at AA, check which node is best by exploring all possible paths up to a certain depth,
+visiting nodes by preference.
+"""
 function trace_best_path(g::Dict{String,Node}; init="AA")
-    opened = String[]; # check later if correct.
+    opened = String[];
     active_pressure_relief = 0;
     pressure_relieved = 0;
     time = 0;
     last = init;
-    total_pressure = 0;
     while length(g) > length(opened)
         @show (time, last, opened)
-        next, dist, score = expected_total_flow(time, g[last], g, opened);
+        next, dist, score = expected_total_flow(time, g[last], g, opened; level=7);
         @show (next, dist, score);
 
         if in(next, opened)