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

Advent of Code 2024 - Day 02

2024/02.livemd

Advent of Code 2024 - Day 02

Mix.install([
  {:req, "~> 0.5"}
])

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 ->
    String.split(row)
    |> Enum.map(&String.to_integer/1)
  end)

Helpers

defmodule Helpers do
  def ascending?([_]), do: true
  def ascending?([a, b | rest]) when a < b and abs(a - b) <= 3, do: ascending?([b] ++ rest)
  def ascending?(_), do: false

  def descending?([_]), do: true
  def descending?([a, b | rest]) when a > b and abs(a - b) <= 3, do: descending?([b] ++ rest)
  def descending?(_), do: false

  def safe?(report), do: ascending?(report) or descending?(report)
end

Part 1

reports
|> Stream.map(&amp;Helpers.safe?/1)
|> Enum.frequencies()

Part 2

reports
|> Stream.map(fn report ->
  report
  |> Stream.with_index()
  |> Stream.map(fn {_level, index} ->
    report
    |> List.delete_at(index)
    |> Helpers.safe?()
  end)
  |> Enum.any?()
end)
|> Enum.frequencies()

Run in Livebook