aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/05
diff options
context:
space:
mode:
authorOscar Najera <hi@oscarnajera.com>2023-01-28 03:46:12 +0100
committerOscar Najera <hi@oscarnajera.com>2023-01-28 03:46:12 +0100
commit84ec86b63ac38423ce021448e379b87094f7d4ac (patch)
tree6574d8b2b5aef30845f38e279a4c389d9fa8897e /AoC2022/05
parent497dc1ea9de502761c00ead6de62abe6eeea67d6 (diff)
downloadscratch-84ec86b63ac38423ce021448e379b87094f7d4ac.tar.gz
scratch-84ec86b63ac38423ce021448e379b87094f7d4ac.tar.bz2
scratch-84ec86b63ac38423ce021448e379b87094f7d4ac.zip
more julia and formatted
Diffstat (limited to 'AoC2022/05')
-rw-r--r--AoC2022/05/solver.jl49
1 files changed, 49 insertions, 0 deletions
diff --git a/AoC2022/05/solver.jl b/AoC2022/05/solver.jl
new file mode 100644
index 0000000..78ff27e
--- /dev/null
+++ b/AoC2022/05/solver.jl
@@ -0,0 +1,49 @@
+using Test
+
+function parse_input()
+ stacks, instruct = open(f -> split(read(f, String), "\n\n"), "input")
+
+ stacks_reversed = reverse(split(stacks, "\n"))
+ number = parse.(Int, eachsplit(stacks_reversed[1]))
+ crates = Dict(i => Char[] for i ∈ number)
+
+ for line ∈ stacks_reversed[2:end]
+ for (i, c) ∈ enumerate(line[2:4:end])
+ if c != ' '
+ push!(crates[i], c)
+ end
+ end
+ end
+
+ instruction_regex = r"move (\d+) from (\d+) to (\d+)"
+ crates,
+ map(
+ l -> parse.(Int, match(instruction_regex, l).captures),
+ eachsplit(instruct, "\n", keepempty = false),
+ )
+end
+
+
+function single_move!(crates, amount, from, to)
+ for _ = 1:amount
+ push!(crates[to], pop!(crates[from]))
+ end
+end
+
+function bulk_move!(crates, amount, from, to)
+ l = length(crates[from])
+ push!(crates[to], splice!(crates[from], l-amount+1:l)...)
+end
+
+function solution(mover)
+ crates, instructions = parse_input()
+ for inst ∈ instructions
+ mover(crates, inst...)
+ end
+ join(crates[i][end] for i ∈ sort(collect(keys(crates))))
+end
+
+@testset "solution" begin
+ @test solution(single_move!) == "TPGVQPFDH"
+ @test solution(bulk_move!) == "DMRDFRHHH"
+end