advent_of_code/elixir/lib/Y2021/day1.exs
2025-04-13 14:21:57 -04:00

51 lines
923 B
Elixir

test_input = [
199,
200,
208,
210,
200,
207,
240,
269,
260,
263
]
# part 1 solution
solve = fn input ->
input
|> Stream.chunk_every(2, 1, :discard)
|> Stream.map(fn [a,b] -> b - a end)
|> Stream.filter(fn a -> a > 0 end)
|> Enum.count()
end
# transform problem for part 2
window_sum = fn input ->
input
|> Stream.chunk_every(3, 1, :discard)
|> Stream.map(&Enum.sum/1)
end
# verify solution for test input
if not(solve.(test_input) == 7) or not(solve.(test_input |> window_sum.()) == 5) do
raise "solution doesn't solve test input"
end
# parse input from text data to solve
parse = fn input ->
input
|> Stream.map(&String.trim/1)
|> Stream.reject(&(&1 == ""))
|> Stream.map(&String.to_integer/1)
end
File.stream!("./day1.txt")
|> parse.()
|> then(fn i ->
p1 = i |> solve.()
p2 = i |> window_sum.() |> solve.()
"p1: #{p1}\tp2: #{p2}"
end)
|> IO.puts()