advent_of_code/elixir/livebook/2024/day2.livemd
2024-12-02 09:37:43 -05:00

977 B

Day 2 AOC 2024

Mix.install([
  {:nx, "0.9.2"},
  {:req, "0.5.8"}
])

Section

input = """
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9
"""
is_safe? = fn report ->
  differences = report 
    |> Stream.chunk_every(2, 1, :discard) 
    |> Enum.map(fn [a, b] -> a - b end) 
  is_monotone? = differences |> Enum.all?(&(&1 < 0)) or differences |> Enum.all?(&(&1 > 0))
  is_gradual? = differences |> Stream.map(&(abs(&1))) |> Enum.all?(&(&1 >= 1 and &1 <= 3))
  is_monotone? and is_gradual?
end
can_be_dampened? = fn report ->
  Stream.with_index(report) |> Enum.any?(fn {_,i} ->
    List.delete_at(report, i) |> is_safe?.()
  end)
end
for line <- input |> String.trim() |> String.split("\n") do
  for c <- line |> String.split(" "),
    c = c |> String.to_integer() do
    c
  end
end
|> Stream.filter(fn report -> 
  is_safe?.(report) # or can_be_dampened?.(report)
end)
|> Enum.count