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

2023 Day 06

livebooks/2023/06.livemd

2023 Day 06

Mix.install([
  {:req, "~> 0.4.5"},
  {:vega_lite, "~> 0.1.8"},
  {:kino_vega_lite, "~> 0.1.11"}
])

alias VegaLite, as: Vl

defmodule AOC do
  @aoc_session System.fetch_env!("LB_AOC_SESSION")

  def day(day, year) when day in 1..25 do
    headers = [cookie: "session=#{@aoc_session}"]
    req = Req.new(base_url: "https://adventofcode.com/#{year}/day/#{day}", headers: headers)
    input = Req.get!(req, url: "/input").body

    if input =~ "Please don't repeatedly request this endpoint before it unlocks",
      do: {:error, "Day #{day} hasn't been unlocked yet"},
      else: {:ok, %{req: req, input: input}}
  end

  def submit(answer, %{req: req}, part \\ :part_1) when part in [:part_1, :part_2] do
    part = if part == :part_2, do: 2, else: 1

    if !part_already_completed?(part, req) do
      body = Req.post!(req, url: "/answer", form: [level: part, answer: answer]).body

      cond do
        body =~ "That's the right answer" -> {:correct, answer}
        body =~ "your answer is too low" -> {:too_low, answer}
        body =~ "your answer is too high" -> {:too_high, answer}
        :else -> {:incorrect, answer}
      end
    else
      {:already_completed_part, answer}
    end
  end

  defp part_already_completed?(part, req) do
    body = Req.get!(req).body

    cond do
      body =~ "Both parts of this puzzle are complete!" -> true
      body =~ "The first half of this puzzle is complete!" -> part == 1
      :else -> false
    end
  end

  def nums(str) do
    Regex.scan(~r/\d+/, str) |> Enum.map(fn [x] -> String.to_integer(x) end)
  end
end

{:ok, day} = AOC.day(6, 2023)

Day

Part 1

test_input = """
Time:      7  15   30
Distance:  9  40  200
"""
defmodule P1 do
  def solve(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&AOC.nums/1)
    |> Enum.zip()
    |> Enum.map(&num_winners_closed_form/1)
    |> Enum.product()
  end

  def num_winners_brute_force({time, record}),
    do: Enum.count(0..time, &(time * &1 - &1 * &1 > record))

  @doc """
    iex> P1.num_winners_closed_form({7, 9})
    4

    iex> P1.num_winners_closed_form({30, 200})
    9
  """
  def num_winners_closed_form({time, record}) do
    lowest_winner = ceil(0.001 + (time - :math.sqrt(time * time - 4 * record)) / 2)
    lowest_winner..(time - lowest_winner) |> Enum.count()
  end
end

day.input |> P1.solve()

Part 2

defmodule P2 do
  def solve(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&extract_number/1)
    |> List.to_tuple()
    |> P1.num_winners_closed_form()
  end

  @doc """
    iex> P2.extract_number("Time:      7  15   30")
    71530
  """
  def extract_number(str) do
    str |> String.split(" ", trim: true) |> Enum.drop(1) |> Enum.join() |> String.to_integer()
  end
end

day.input |> P2.solve()