commit 5cb1d122c0f1f461fe36828fc2f003e5373eafa4
parent 16930c5f191badf4725c261a4536b36c2ae1587b
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date: Mon, 5 Dec 2022 16:14:20 -0800
Solution to day 5, part 1.
Diffstat:
A | src/day_5.jl | | | 74 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 74 insertions(+), 0 deletions(-)
diff --git a/src/day_5.jl b/src/day_5.jl
@@ -0,0 +1,74 @@
+#!/usr/bin/env julia
+# https://adventofcode.com/2022/day/5
+using AdventOfCode
+
+example = readlines(IOBuffer("""
+ [D]
+ [N] [C]
+ [Z] [M] [P]
+ 1 2 3
+
+ move 1 from 2 to 1
+ move 3 from 1 to 3
+ move 2 from 2 to 1
+ move 1 from 1 to 2"""))
+input = readlines("data/day_5.txt")
+
+# This just splits the input (array of strings) into the starting stacks of
+# crates and the rearrangement procedure
+function split_input(input)
+ splitpoint = findfirst(input .== "")
+ (input[1:splitpoint-1], input[splitpoint+1:end])
+end
+
+# Read the map of the starting crate stacks and return an array of arrays
+function parse_stack(cratestack)
+ stacks = []
+ for line = cratestack[1:end-1]
+ crates = split(line, "")[2:4:end]
+ for (i, crate) = enumerate(crates)
+ if length(stacks) < i
+ push!(stacks, [])
+ end
+ if crate != " "
+ push!(stacks[i], crate)
+ end
+ end
+ end
+ reverse.(stacks)
+end
+
+# Apply an instruction to the crate stacks. Does nothing with invalid
+# instructions (doesn't throw warnings or errors either).
+function apply_instruction!(stacks, instruction)
+ m = match(r"move (\d+) from (\d+) to (\d+)", instruction)
+ if !isnothing(m)
+ (numtomove, from, to) = parse.(Int, m.captures)
+ while numtomove > 0
+ push!(stacks[to], pop!(stacks[from]))
+ numtomove -= 1
+ end
+ end
+ stacks
+end
+
+# Apply all the instructions to the crate stacks
+function apply_all_instructions!(stacks, instructions)
+ for instruction = instructions
+ apply_instruction!(stacks, instruction)
+ end
+ stacks
+end
+
+function part_1(input)
+ (cratestack, instructions) = split_input(input)
+ stacks = apply_all_instructions!(parse_stack(cratestack), instructions)
+ reduce(*, last.(stacks))
+end
+@assert part_1(example) == "CMZ"
+@info part_1(input)
+
+function part_2(input)
+ nothing
+end
+@info part_2(input)