From 6da10b268dd639594cb5a8cc6e9bbb86ce4beb5e Mon Sep 17 00:00:00 2001 From: Alexandre Jesus Date: Tue, 3 Dec 2024 00:26:58 +0000 Subject: Days 1 and 2 --- src/day02.exs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 src/day02.exs (limited to 'src/day02.exs') 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) -- cgit v1.2.3