diff --git a/2024/README.md b/2024/README.md index e49d199..c27a947 100644 --- a/2024/README.md +++ b/2024/README.md @@ -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 diff --git a/2024/lib/2024/5.ex b/2024/lib/2024/5.ex new file mode 100644 index 0000000..3860e4c --- /dev/null +++ b/2024/lib/2024/5.ex @@ -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 diff --git a/README.md b/README.md index 2289258..1640c5d 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,8 @@ | [2021] | **43/50** 🌟 | Elixir | | [2022] | **14/50** 🌟 | Elixir, Haskell | | [2023] | **19/50** 🌟 | Elixir, Haskell | -| [2024] | **8/50** 🌟 | Elixir | -| **Total** | **162** 🌟 | | +| [2024] | **10/50** 🌟 | Elixir | +| **Total** | **162** 🌟| | [2015]: ./2015 [2017]: ./2017