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

Day 06

2023/elixir/day06.livemd

Day 06

Part 1

test = """
Time:      7  15   30
Distance:  9  40  200
"""
input = """
Time:        35     93     73     66
Distance:   212   2060   1201   1044
"""
records =
  input
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    line |> String.split() |> Enum.drop(1) |> Enum.map(&(&1 |> Integer.parse() |> elem(0)))
  end)
  |> Enum.zip()
defmodule Race do
  def calculate_margin(time, record) do
    ranges = [1..(time - 1), (time - 1)..1]
    [first, last] = Enum.map(ranges, &Enum.find(&1, fn t -> t * (time - t) > record end))
    Range.size(first..last)
  end
end
records
|> Enum.map(fn {time, record} ->
  Race.calculate_margin(time, record)
end)
|> Enum.product()

Part 2

[time, record] =
  input
  |> String.split("\n", trim: true)
  |> Enum.map(fn line ->
    line |> String.split() |> Enum.drop(1) |> Enum.join() |> Integer.parse() |> elem(0)
  end)
Race.calculate_margin(time, record)