Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

🎄 Year 2024 🔔 Day 02

elixir/notebooks/2024/day02.livemd

🎄 Year 2024 🔔 Day 02

Setup

input =
  File.read!("#{__DIR__}/../../../inputs/2024/day02.txt")
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    line
    |> String.split(" ", trim: true)
    |> Enum.map(&String.to_integer/1)
  end)

Part 1

input
|> Enum.map(fn line ->
  steps =
    line
    |> Enum.chunk_every(2, 1, :discard)
    |> Enum.map(fn [a, b] -> a - b end)

  all_asc = Enum.all?(steps, fn step -> step > 0 end)
  all_desc = Enum.all?(steps, fn step -> step < 0 end)
  any_safe_step = Enum.all?(steps, fn step -> abs(step) >= 1 &amp;&amp; abs(step) <= 3 end)
  (all_asc || all_desc) &amp;&amp; any_safe_step
end)
|> Enum.count(fn e -> e end)

Part 2

input
|> Enum.map(fn line ->
  -1..4
  |> Enum.map(&amp;List.delete_at(line, &amp;1))
  |> Enum.any?(fn line ->
    steps =
      line
      |> Enum.chunk_every(2, 1, :discard)
      |> Enum.map(fn [a, b] -> a - b end)

    all_asc = Enum.all?(steps, fn step -> step > 0 end)
    all_desc = Enum.all?(steps, fn step -> step < 0 end)
    any_safe_step = Enum.all?(steps, fn step -> abs(step) >= 1 &amp;&amp; abs(step) <= 3 end)
    (all_asc || all_desc) &amp;&amp; any_safe_step
  end)
end)
|> Enum.count(fn e -> e end)