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

Day 6: Wait For It

2023/day_06.livemd

Day 6: Wait For It

Mix.install([:kino])

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

Part 1

Run in Livebook

https://adventofcode.com/2023/day/6

[time_str, record_distance_str] =
  input
  |> Kino.Input.read()
  |> String.split("\n", trim: true)
time = 15
record_distance = 40

time / 2 - :math.sqrt(-4 * record_distance + time ** 2) / 2
times =
  time_str
  |> String.trim_leading("Time:")
  |> String.split(~r/\s+/, trim: true)
  |> Enum.map(&String.to_integer/1)

record_distances =
  record_distance_str
  |> String.trim_leading("Distance:")
  |> String.split(~r/\s+/, trim: true)
  |> Enum.map(&String.to_integer/1)

Enum.zip(times, record_distances)
|> Enum.map(fn {time, record_distance} ->
  # speed: x
  # time: (t - x)
  # distance: x * (t - x)
  # distance > record_distance: x * (t -x) > r

  min_x = trunc(time / 2 - :math.sqrt(-4 * record_distance + time ** 2) / 2)

  time - (min_x * 2 + 1)
end)
|> Enum.product()

Part 2

https://adventofcode.com/2023/day/6#part2

times =
  time_str
  |> String.trim_leading("Time:")
  |> String.replace(" ", "")
  |> String.to_integer()
  |> then(&[&1])

record_distances =
  record_distance_str
  |> String.trim_leading("Distance:")
  |> String.replace(" ", "")
  |> String.to_integer()
  |> then(&[&1])

Enum.zip(times, record_distances)
|> Enum.map(fn {time, record_distance} ->
  # speed: x
  # time: (t - x)
  # distance: x * (t - x)
  # distance > record_distance: x * (t -x) > r

  min_x = trunc(time / 2 - :math.sqrt(-4 * record_distance + time ** 2) / 2)

  time - (min_x * 2 + 1)
end)
|> Enum.product()