commit fe93b248b09c82fcbe1c2a3a58b0f04f86be6115
parent 8a420bc40d67bfefea99dd116692711ac41025ee
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date: Fri, 2 Dec 2022 12:18:12 -0800
Solution to day 2, part 1.
This code is pretty ugly. I'm using DataFrames because I want to learn
it, but there are certainly better approaches. It's also very slow, but
most of that is due to the naive implementation: there are only 9
possible combinations each with a unique score, so enumerating these
would be better.
Diffstat:
A | src/day_2.jl | | | 51 | +++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 51 insertions(+), 0 deletions(-)
diff --git a/src/day_2.jl b/src/day_2.jl
@@ -0,0 +1,51 @@
+#!/usr/bin/env julia
+# https://adventofcode.com/2022/day/2
+using AdventOfCode
+using DataFrames
+
+example = split("""
+ A Y
+ B X
+ C Z""", "\n")
+input = readlines("data/day_2.txt")
+
+# Note that this rearranges the input rows. Not sure if that will be a problem.
+# Maybe leftjoin needs to be told not to do that? IDK. Also Julia has the whack
+# negative modulus behavior. Finally, I don't know if this is idiomatic Julia
+# at all, I'm basically hacking dplyr into Julia and it's pretty ugly IMO.
+function parse_input(input)
+ scores = DataFrame(
+ a = ['A', 'B', 'C'],
+ b = ['X', 'Y', 'Z'],
+ score = 0:2
+ )
+ input |>
+ x->DataFrame(a = first.(x), b = last.(x)) |>
+ x->leftjoin(x, select(scores, "a", "score" => "score_a"),
+ on = :a) |>
+ x->leftjoin(x, select(scores, "b", "score" => "score_b"),
+ on = :b) |>
+ x->transform(x,
+ [:score_a, :score_b] =>
+ ByRow((a, b) -> (b-a+1) % 3) =>
+ :win_score) |>
+ x->transform(x,
+ :win_score =>
+ ByRow(a -> a < 0 ? a + 3 : a) =>
+ :win_score) |>
+ x->transform(x,
+ [:score_b, :win_score] =>
+ ByRow((a, b) -> a + 1 + 3 * b) =>
+ :round_score)
+end
+
+function part_1(input)
+ sum(parse_input(input)[:, :round_score])
+end
+@assert part_1(example) == 15
+@info part_1(input)
+
+function part_2(input)
+ nothing
+end
+@info part_2(input)