1
0
Fork 0

solve 2024 day 5

This commit is contained in:
sloane 2024-12-05 07:42:30 -05:00
parent aecafff267
commit a9dae7f820
Signed by: sloanelybutsurely
SSH key fingerprint: SHA256:8SBnwhl+RY3oEyQxy1a9wByPzxWM0x+/Ejc+sIlY5qQ
3 changed files with 71 additions and 3 deletions

View file

@ -2,7 +2,7 @@
| S | M | T | W | T | F | S |
| :-: | :-: | :-: | :-: | :-: | :-: | :-: |
| [1] | [2] | [3] | [4] | 5 | 6 | 7 |
| [1] | [2] | [3] | [4] | [5] | 6 | 7 |
| 8 | 9 | 10 | 11 | 12 | 13 | 14 |
| 15 | 16 | 17 | 18 | 19 | 20 | 21 |
| 22 | 23 | 24 | 25 | | | |
@ -11,3 +11,4 @@
[2]: ./lib/2024/2.ex
[3]: ./lib/2024/3.ex
[4]: ./lib/2024/4.ex
[5]: ./lib/2024/5.ex

67
2024/lib/2024/5.ex Normal file
View file

@ -0,0 +1,67 @@
import AOC
aoc 2024, 5 do
def p1(input) do
{rules, updates} = parse_input(input)
updates
|> Enum.filter(&sorted?(&1, rules))
|> Enum.map(&median/1)
|> Enum.sum()
end
def p2(input) do
{rules, updates} = parse_input(input)
updates
|> Enum.reject(&sorted?(&1, rules))
|> Enum.map(fn update ->
Enum.sort(update, &sort_update(&1, &2, rules))
end)
|> Enum.map(&median/1)
|> Enum.sum()
end
def sorted?(update, rules) do
update == Enum.sort(update, &sort_update(&1, &2, rules))
end
def median(update) do
Enum.at(update, div(length(update), 2))
end
def sort_update(a, b, rules) do
a_before = Map.get(rules, a, [])
b in a_before
end
## input parsing
def parse_input(input) do
[rules_str, updates_str] = String.split(input, "\n\n")
rules = parse_rules(rules_str)
updates = parse_updates(updates_str)
{rules, updates}
end
def parse_rules(rules_str) do
rules_str
|> String.split("\n", trim: true)
|> Enum.group_by(
&String.to_integer(binary_part(&1, 0, 2)),
&String.to_integer(binary_part(&1, 3, 2))
)
end
def parse_updates(updates_str) do
updates_str
|> String.split("\n", trim: true)
|> Enum.map(fn line ->
line
|> String.split(",")
|> Enum.map(&String.to_integer/1)
end)
end
end

View file

@ -15,7 +15,7 @@
| [2021] | **43/50** 🌟 | Elixir |
| [2022] | **14/50** 🌟 | Elixir, Haskell |
| [2023] | **19/50** 🌟 | Elixir, Haskell |
| [2024] | **8/50** 🌟 | Elixir |
| [2024] | **10/50** 🌟 | Elixir |
| **Total** | **162** 🌟| |
[2015]: ./2015