diff --git a/2024/README.md b/2024/README.md index 1a6de16..195afbe 100644 --- a/2024/README.md +++ b/2024/README.md @@ -2,9 +2,10 @@ | 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 | | | | [1]: ./lib/2024/1.ex +[2]: ./lib/2024/2.ex diff --git a/2024/lib/2024/2.ex b/2024/lib/2024/2.ex new file mode 100644 index 0000000..e34fb1f --- /dev/null +++ b/2024/lib/2024/2.ex @@ -0,0 +1,47 @@ +import AOC + +aoc 2024, 2 do + def p1(input) do + input + |> list_of_lists_of_numbers() + |> Enum.count(&safe?/1) + end + + def p2(input) do + input + |> list_of_lists_of_numbers() + |> Enum.count(&safe_with_dampener?(&1)) + end + + defp list_of_lists_of_numbers(input) do + input + |> String.split("\n") + |> Enum.map(fn line -> + line + |> String.split() + |> Enum.map(&String.to_integer/1) + end) + end + + defp safe?(report) do + diffs = differences(report) + + Enum.all?(diffs, &(1 <= &1 and &1 <= 3)) or + Enum.all?(diffs, &(-3 <= &1 and &1 <= -1)) + end + + def safe_with_dampener?(report) do + reports_with_a_single_level_removed = + for i <- 0..(length(report) - 1) do + {head, [_ | tail]} = Enum.split(report, i) + head ++ tail + end + + safe?(report) or + Enum.any?(reports_with_a_single_level_removed, &safe?/1) + end + + defp differences([_ | rest] = list) do + Enum.zip_with(list, rest, &(&1 - &2)) + end +end diff --git a/README.md b/README.md index c80289f..02a103b 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ | [2021] | **43/50** 🌟 | Elixir | | [2022] | **14/50** 🌟 | Elixir, Haskell | | [2023] | **19/50** 🌟 | Elixir, Haskell | -| [2024] | **2/50** 🌟 | Elixir | +| [2024] | **4/50** 🌟 | Elixir | [2015]: ./2015 [2017]: ./2017