pub fn y22d13(input: &str, part: u32) -> u32
Expand description
The solution for the day thirteen challenge.
We take the usual input as a string and whether we’re solving for part 1
(sum of the indices that are in order) or part 2
(product of the indices
of the two extra data packets that we add).
We start by splitting the input every three lines so that we check each
pair if it’s ordered or not, we also add the string representation of both
to our vector that we’ll sort later if we’re computing part 2
. If we’re
computing part 1
then we need to parse the input into a Data
representation and then check if the pairs are ordered. If they are then
we add one to our index and then add that to the sum of ordered indices.
After going through all of the pairs and we’re doing part 1
then we’re
done - just return the result. Otherwise we’re doing part two and we need
to add the extra data packets and then sort all of them. As explained above
I implemented a simple insertion sort (while additionally parsing the input
for each comparison pass because of the state mutation) to achieve this.
After sorting we do one final loop through the input to calculate the
product of the indices of the extra packets we added and then we’re done.
§Example
// probably read this from the input file...
let input = "[1,2]\n[3,[4]]\n\n[[5]]\n[]\n";
assert_eq!(y22d13(input, 1), 1);
assert_eq!(y22d13(input, 2), 18);