advent_of_code/elixir/livebook/2024/day5.livemd
2024-12-05 09:41:09 -05:00

1,014 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)
  do
  {a, b}
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 ->
  a_precedes_b = Enum.any?(rules, &(&1 == {a, b}))
  b_precedes_a = Enum.any?(rules, &(&1 == {b, a}))
  cond do 
    b_precedes_a -> false
    a_precedes_b -> true
    true -> true
  end
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

# 10495 too high