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

52 lines
959 B
Markdown

# 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 ->
!(Map.get(rules, b, MapSet.new()) |> MapSet.member?(a))
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
```