commit 5e7795bf910a8778d153bad8fa4e6f00fc72e1c9
parent 5cb1d122c0f1f461fe36828fc2f003e5373eafa4
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date: Mon, 5 Dec 2022 16:28:23 -0800
Solution to day 5, part 2.
Diffstat:
1 file changed, 30 insertions(+), 1 deletion(-)
diff --git a/src/day_5.jl b/src/day_5.jl
@@ -68,7 +68,36 @@ end
@assert part_1(example) == "CMZ"
@info part_1(input)
+## Part 2
+
+# Need a new function for applying instructions. Wish I was smarter about Julia
+# polymorphism, but whatever.
+
+# Apply an instruction to the crate stacks. Does nothing with invalid
+# instructions (doesn't throw warnings or errors either).
+function apply_instruction_2!(stacks, instruction)
+ m = match(r"move (\d+) from (\d+) to (\d+)", instruction)
+ if !isnothing(m)
+ (numtomove, from, to) = parse.(Int, m.captures)
+ push!(stacks[to], stacks[from][end-numtomove+1:end]...)
+ deleteat!(stacks[from],
+ lastindex(stacks[from])-numtomove+1:lastindex(stacks[from]))
+ end
+ stacks
+end
+
+# Apply all the instructions to the crate stacks
+function apply_all_instructions_2!(stacks, instructions)
+ for instruction = instructions
+ apply_instruction_2!(stacks, instruction)
+ end
+ stacks
+end
+
function part_2(input)
- nothing
+ (cratestack, instructions) = split_input(input)
+ stacks = apply_all_instructions_2!(parse_stack(cratestack), instructions)
+ reduce(*, last.(stacks))
end
+@assert part_2(example) == "MCD"
@info part_2(input)