add 2021 day 1

This commit is contained in:
Caleb Webber 2025-04-13 14:21:48 -04:00
parent d0d8f86ee8
commit 6a55ccc72e
3 changed files with 58 additions and 0 deletions

4
elixir/.formatter.exs Normal file
View file

@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]

3
elixir/.gitignore vendored
View file

@ -26,3 +26,6 @@ aoc-*.tar
/tmp/
.session
# Input files
*.txt

51
elixir/lib/Y2021/day1.exs Normal file
View file

@ -0,0 +1,51 @@
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()