# AOC 2024 Day 5 ## Section ```elixir input = """ """ ``` ```elixir [rules, updates] = input |> String.split("\n\n") ``` ```elixir rules = for rule <- rules |> String.split("\n"), [a, b] = rule |> String.split("|"), a = String.to_integer(a), b = String.to_integer(b), reduce: %{} do acc -> Map.update(acc, a, MapSet.new([b]), fn c -> MapSet.put(c, b) end) end ``` ```elixir updates = for update <- updates |> String.trim() |> String.split("\n"), update = update |> String.trim() |> String.split(",") do for page <- update, page = String.to_integer(page) do page end end ``` ```elixir rule_sorter = fn a, b -> b_precedes_a = Map.get(rules, b, MapSet.new()) |> MapSet.member?(a) cond do b_precedes_a -> false true -> true end end ``` ```elixir for update <- updates, sorted = Enum.sort(update, rule_sorter), sorted != update, reduce: 0 do acc -> len = sorted |> Enum.count mid_idx = floor(len / 2) acc + Enum.at(sorted, mid_idx) end ```