Advent of Code 2024 - Day 2
Section
inputs = File.read!(File.cwd!() <> "/advent-of-code/2024/day02.input")
|> String.split("\r\n")
|> Enum.map(fn line -> String.split(line) |> Enum.map(&String.to_integer/1) end)
direction_ok? = fn ns ->
(ns == Enum.sort(ns, :asc)) or (ns == Enum.sort(ns, :desc))
end
deltas_ok? = fn ns ->
Enum.zip(ns, Enum.drop(ns, 1))
|> Enum.all?(fn {a, b} -> 1 <= abs(a-b) and abs(a-b) <= 3 end)
end
defmodule Day2 do
def test(xs) do
direction_ok?(xs) and deltas_ok?(xs)
end
def direction_ok?(ns) do
(ns == Enum.sort(ns, :asc)) or (ns == Enum.sort(ns, :desc))
end
def deltas_ok?(ns) do
Enum.zip(ns, Enum.drop(ns, 1))
|> Enum.all?(fn {a, b} -> 1 <= abs(a-b) and abs(a-b) <= 3 end)
end
end
inputs
|> Enum.filter(&Day2.test/1)
|> Enum.count()
inputs
|> Stream.map(fn xs -> Enum.map(0..(length(xs)-1), &List.delete_at(xs, &1)) end)
|> Stream.map(fn xs -> Enum.filter(xs, fn ys -> Day2.test(ys) end) end)
|> Enum.count(&Enum.any?/1)
#650 too high
#633 too low
# Failed at: [1,2,3,2,4]
# Why? Because we were calling List.delete so deleting the second 2 was actually deleting
# first 2