Advent of Code 2024 - Day 5Print Queue
| Problem statement | Source code | Tags: Brute force
This problem pays tribute to 2017 day 1 (unimplemented).
Part 1
I parse my input to two things: orders, a (int * int) list saying that a should come before b, and lists, a int list list.
If a list is valid, then for each order (a, b), a must come before b in the list. Instead of searching for a and b for each order, I can build a map from each element to its index in the list, and then check that index(a) < index(b) for each order.
Finding the middle element is just List.nth lst (List.length lst / 2).
Part 2
To be honest, I'm not too fond of this problem, because there's no guarantee that the given order is total and consistent. In the end, I implemented a very dumb (IMO) solution that just fixes violations one by one. Each time, I pull an order, and if it's violated, swap the two elements. But one pass may not be enough, since fixing one order may break another. So I repeat this process until no more changes are needed.
Now finding the middle element is slightly more complicated, since we have to invert the map from element to index back to a list of elements. I just do a search for the element with index List.length num_to_ind / 2 in the map.