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

Advent of Code 2024 - Day 02

2024/day-02.livemd

Advent of Code 2024 - Day 02

Mix.install([{:kino, github: "livebook-dev/kino"}])

kino_input = Kino.Input.textarea("Please paste your input file: ")

Part 1

input = Kino.Input.read(kino_input)

input
|> String.split("\n", trim: true)
|> Enum.map(&String.split/1)
|> Enum.map(fn report ->  Enum.map(report, &String.to_integer/1) end)
|> Enum.count(fn report -> 
  increasing = Enum.chunk_every(report, 2, 1, :discard)
    |> Enum.all?(fn [a, b] -> a < b &amp;&amp; abs(a - b) in 1..3 end)

  decreasing = Enum.chunk_every(report, 2, 1, :discard)
    |> Enum.all?(fn [a, b] -> a > b &amp;&amp; abs(a - b) in 1..3 end)

  increasing or decreasing
end)

Part 2

input = Kino.Input.read(kino_input)

safe_report? = fn report ->
  increasing = Enum.chunk_every(report, 2, 1, :discard)
    |> Enum.all?(fn [a, b] -> a < b &amp;&amp; abs(a - b) in 1..3 end)

  decreasing = Enum.chunk_every(report, 2, 1, :discard)
    |> Enum.all?(fn [a, b] -> a > b &amp;&amp; abs(a - b) in 1..3 end)

  increasing or decreasing
end

input
|> String.split("\n", trim: true)
|> Enum.map(&amp;String.split/1)
|> Enum.map(fn report -> Enum.map(report, &amp;String.to_integer/1) end)
|> Enum.count(fn report -> 
  safe_report?.(report) or
    Enum.with_index(report)
    |> Enum.any?(fn {_, index} ->
      report
      |> List.delete_at(index)
      |> safe_report?.()
  end)
end)