add day5 aoc 2024

This commit is contained in:
Caleb Webber 2024-12-05 09:41:09 -05:00
parent cf21b4cecc
commit 6f5f934166

View file

@ -0,0 +1,58 @@
# 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)
do
{a, b}
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 ->
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
```
```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
# 10495 too high
```