add day2 2024
This commit is contained in:
parent
32055baff4
commit
9754128162
1 changed files with 55 additions and 0 deletions
55
elixir/livebook/2024/day2.livemd
Normal file
55
elixir/livebook/2024/day2.livemd
Normal file
|
@ -0,0 +1,55 @@
|
|||
# Day 2 AOC 2024
|
||||
|
||||
```elixir
|
||||
Mix.install([
|
||||
{:nx, "0.9.2"},
|
||||
{:req, "0.5.8"}
|
||||
])
|
||||
```
|
||||
|
||||
## Section
|
||||
|
||||
|
||||
|
||||
```elixir
|
||||
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
|
||||
"""
|
||||
```
|
||||
|
||||
```elixir
|
||||
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
|
||||
```
|
||||
|
||||
```elixir
|
||||
can_be_dampened? = fn report ->
|
||||
Stream.with_index(report) |> Enum.any?(fn {_,i} ->
|
||||
List.delete_at(report, i) |> is_safe?.()
|
||||
end)
|
||||
end
|
||||
```
|
||||
|
||||
```elixir
|
||||
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
|
||||
```
|
Loading…
Add table
Reference in a new issue