advent_of_code/elixir/livebook/2024/day5.livemd
2024-12-05 10:26:17 -05:00

959 B

AOC 2024 Day 5

Section

input = """
"""
[rules, updates] = input |> String.split("\n\n")
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
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
rule_sorter = fn a, b ->
  !(Map.get(rules, b, MapSet.new()) |> MapSet.member?(a))
end
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