changeset 14:4bad3ee77ef2

Day 09 part 2
author Lewin Bormann <lbo@spheniscida.de>
date Sun, 11 Dec 2022 11:15:16 +0100
parents dfed6e6ea69b
children 6fd4445cbd22
files 09/09.jl
diffstat 1 files changed, 36 insertions(+), 10 deletions(-) [+]
line wrap: on
line diff
--- a/09/09.jl	Sun Dec 11 10:48:43 2022 +0100
+++ b/09/09.jl	Sun Dec 11 11:15:16 2022 +0100
@@ -8,6 +8,15 @@
 L 5
 R 2";
 
+const test_input2::String = "R 5
+U 8
+L 8
+D 3
+R 17
+D 10
+L 25
+U 20";
+
 @enum Direction begin
     U
     D
@@ -42,6 +51,7 @@
 end
 
 function wheretogo(H::Tuple{Int,Int}, T::Tuple{Int,Int})::Vector{Direction}
+    # This might have a more elegant solution...
     if H == T
         []
     elseif H[1]==T[1]
@@ -64,8 +74,14 @@
             snd = (H[1]-T[1]) > 0 ? R : L;
             (H[2]-T[2]) > 0 ? ([U, snd]) : ([D, snd])
         end
+    elseif abs(H[1]-T[1])==abs(H[2]-T[2]) && abs(H[1]-T[1]) > 1
+        [(H[1]>T[1] ? R : L), (H[2]>T[2] ? U : D)]
     else
-        []
+        if abs(H[1]-T[1])+abs(H[2]-T[2]) == 2
+            []
+        else
+            error("unhandled case: ", H, T)
+        end
     end
 end
 
@@ -81,20 +97,24 @@
     end
 end
 
-function process1(v::Vector{Step})::Int
+function process1(v::Vector{Step}; ntails=1)::Int
     H = (0, 0);
-    T = (0, 0);
-    visited = Set{Tuple{Int,Int}}([T])
+    T = [(0,0) for i in 1:ntails];
+    visited = Set{Tuple{Int,Int}}([H])
 
     for step in v
         for i = 1:step.n
             H = apply(H, step.direction);
-            wtg = wheretogo(H, T);
-            for w in wtg::Vector{Direction}
-                T = apply(T, w);
+            # Tail follow
+            pred = H
+            for (i,t) in enumerate(T)
+                wtg = wheretogo(pred, t);
+                for w in wtg::Vector{Direction}
+                    T[i] = apply(T[i], w);
+                end
+                pred = T[i];
             end
-            @show T
-            push!(visited, T);
+            push!(visited, pred);
         end
     end
     length(visited)
@@ -104,5 +124,11 @@
 println(process1(parse_input(split(test_input, '\n'))));
 println("part 1:");
 open("09/input.txt"; read=true) do fh
-    println(process1(parse_input(eachline(fh))));
+    @time println(process1(parse_input(eachline(fh))));
 end
+
+println("part 2:");
+println(process1(parse_input(split(test_input2, '\n')); ntails=9));
+open("09/input.txt"; read=true) do fh
+    @time println(process1(parse_input(eachline(fh)); ntails=9));
+end