diff options
| author | Alexandre Jesus <adbjesus@gmail.com> | 2024-12-03 00:26:58 +0000 | 
|---|---|---|
| committer | Alexandre Jesus <adbjesus@gmail.com> | 2024-12-03 00:41:29 +0000 | 
| commit | 6da10b268dd639594cb5a8cc6e9bbb86ce4beb5e (patch) | |
| tree | 12242f658c49c0cbcf4f8bf987f0f8a52ee51f2f /src | |
| download | aoc2024-6da10b268dd639594cb5a8cc6e9bbb86ce4beb5e.tar.gz aoc2024-6da10b268dd639594cb5a8cc6e9bbb86ce4beb5e.zip | |
Days 1 and 2
Diffstat (limited to 'src')
| -rw-r--r-- | src/day01.exs | 20 | ||||
| -rw-r--r-- | src/day02.exs | 36 | 
2 files changed, 56 insertions, 0 deletions
| diff --git a/src/day01.exs b/src/day01.exs new file mode 100644 index 0000000..b9b346d --- /dev/null +++ b/src/day01.exs @@ -0,0 +1,20 @@ +[l1, l2] = IO.read(:stdio, :eof) +|> String.split([" ", "\n"], trim: true) +|> Enum.map(&String.to_integer/1) +|> Enum.with_index() +|> Enum.split_with(fn {_v, i} -> rem(i, 2) == 0 end) +|> Tuple.to_list() +|> Enum.map(fn l -> Enum.map(l, fn {v, _i} -> v end) end) +|> Enum.map(&Enum.sort/1) + +ans1 = Enum.zip(l1, l2) +|> Enum.map(fn {v1, v2} -> abs(v1 - v2) end) +|> Enum.sum() + +IO.puts(ans1) + +c2 = Enum.frequencies(l2) + +ans2 = Enum.map(l1, &(&1 * Map.get(c2, &1, 0))) |> Enum.sum() + +IO.puts(ans2) diff --git a/src/day02.exs b/src/day02.exs new file mode 100644 index 0000000..ae7bfde --- /dev/null +++ b/src/day02.exs @@ -0,0 +1,36 @@ +defmodule Day02 do +  def parse_report(line) do +    line +    |> String.trim() +    |> String.split(" ") +    |> Enum.map(&String.to_integer/1) +  end + +  def is_report_safe(report) do +    diffs = report +    |> Enum.chunk_every(2, 1, :discard) +    |> Enum.map(fn [a, b] -> b - a end) + +    Enum.all?(diffs, fn x -> 1 <= x and x <= 3 end) or +      Enum.all?(diffs, fn x -> -3 <= x and x <= -1 end) +  end + +  def is_report_safe_with_dampener(report) do +    is_report_safe(report) or +      Enum.any?(0..Enum.count(report)-1, +                fn i -> List.delete_at(report, i) |> is_report_safe() end) +  end +end + +reports = IO.stream(:stdio, :line) +|> Enum.map(&Day02.parse_report/1) + +ans1 = reports +|> Enum.count(&Day02.is_report_safe/1) + +IO.puts(ans1) + +ans2 = reports +|> Enum.count(&Day02.is_report_safe_with_dampener/1) + +IO.puts(ans2) | 
