Advent of Code 2024 - Day 1Historian Hysteria
| Problem statement | Source code | Tags: Data structures
Part 1
After years of Haskell practice, I'm still getting used to what OCaml has and doesn't have, so this is a good warmup. Split each line, parse two numbers, then List.split (OCaml's unzip) to get two lists. Sort each of them, then zip them and sum the diffs.
Part 2
We want
\sum_{i=1}^n a_i \cdot #(b, a_i)where #(b, a_i) is the number of 's in the list . This is equivalent to
\sum_{a_i\in a} a_i \cdot #(a, a_i) \cdot #(b, a_i)where is the set of unique elements in the list . We can compute this by first counting the occurrences of each unique element in and , then summing over the unique elements in .
OCaml doesn't have a straightforward way to count occurrences (!) so I have to DIY via Map.Make (Int).