Advent of Code 2024 - Day 02
Mix.install([
{:req, "~> 0.5"},
{:benchee, "~> 1.3"}
])
Input
opts = [headers: [{"cookie", "session=#{System.fetch_env!("LB_AOC_SESSION")}"}]]
puzzle_input = Req.get!("https://adventofcode.com/2024/day/2/input", opts).body
reports =
puzzle_input
|> String.split("\n", trim: true)
|> Enum.map(fn row ->
row
|> String.split()
|> Enum.map(&String.to_integer/1)
end)
Functions
valid_sequence? = fn sequence ->
pairs = Enum.chunk_every(sequence, 2, 1, :discard)
desc? =
Enum.all?(pairs, fn [a, b] ->
b > a and abs(a-b) <= 3
end)
asc? =
Enum.all?(pairs, fn [a, b] ->
a > b and abs(a-b) <= 3
end)
desc? or asc?
end
Puzzle 1
puzzle_1 = fn ->
Enum.count(reports, &valid_sequence?.(&1))
end
puzzle_1.()
Puzzle 2
puzzle_2 = fn ->
Enum.count(reports, fn report ->
valid_with_deletion? =
Enum.with_index(report)
|> Enum.map(fn {_el, i} ->
List.delete_at(report, i) |> valid_sequence?.()
end)
|> Enum.any?()
valid_with_deletion? or valid_sequence?.(report)
end)
end
puzzle_2.()
Benchmarks
Benchee.run(
%{
"puzzle_1" => fn -> puzzle_1.() end,
"puzzle_2" => fn -> puzzle_2.() end
})
Name |
ips |
average |
deviation |
median |
99th % |
puzzle_1 |
167.49 |
5.97 ms |
±8.91% |
5.85 ms |
7.06 ms |
puzzle_2 |
27.91 |
35.82 ms |
±17.06% |
32.57 ms |
56.68 ms |