commit 7539928b528e483ce9f1fa715e095d2b550d3736
parent 1452c97c449d7c66ccc7010cd3fa88efca38e1d6
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date: Fri, 9 Dec 2022 20:58:57 -0800
Just a bit of code cleanup.
I mean, it's still ugly. But it's a bit less ugly.
Diffstat:
1 file changed, 9 insertions(+), 10 deletions(-)
diff --git a/src/day_9.jl b/src/day_9.jl
@@ -38,20 +38,19 @@ end
"""
Shift the tail one step based on the difference vector
-The tail can move up/down, left/right, or diagonally.
+The tail can move up/down, left/right, or diagonally. It moves at most one step
+(in either or both cardinal directions).
"""
-function shift_tail(diff_vec, head_position, tail_position)
+function shift_tail(diff_vec, tail_position)
tail_position .+ sign.(diff_vec)
end
function move_knots(instructions, num_knots=2)
knot_positions = [(0, 0) for _ in 1:num_knots]
- tail_visits = Set{Tuple{Int,Int}}()
- push!(tail_visits, knot_positions[end])
+ tail_visits = Set{Tuple{Int,Int}}([knot_positions[end]])
for instruction = instructions
- steps = parse(Int, instruction[3:end])
- for _ in 1:steps
+ for _ in 1:parse(Int, instruction[3:end]) # Number of steps
knot_positions[1] = shift_head(
knot_positions[1],
instruction[1]
@@ -62,8 +61,8 @@ function move_knots(instructions, num_knots=2)
knot_positions[i])
while !aretouching
knot_positions[i] = shift_tail(diff_vec,
- knot_positions[i-1],
knot_positions[i])
+
if i == lastindex(knot_positions)
push!(tail_visits, knot_positions[i])
end
@@ -72,8 +71,8 @@ function move_knots(instructions, num_knots=2)
knot_positions[i])
end
end
- end
- end
+ end # steps
+ end # instructions
tail_visits
end
@@ -113,9 +112,9 @@ function draw_map(tail_visits)
println(join(reverse([join(x, "") for x in eachrow(tailmap)]), "\n"))
end
-draw_map(move_knots(example2, 10))
function part_2(input)
length(move_knots(input, 10))
end
@assert part_2(example2) == 36
+draw_map(move_knots(example2, 10))
@info part_2(input)