Skip to content

Instantly share code, notes, and snippets.

@Szer
Last active December 7, 2023 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Szer/98bef3ec3d321cc5a3634c8489155211 to your computer and use it in GitHub Desktop.
Save Szer/98bef3ec3d321cc5a3634c8489155211 to your computer and use it in GitHub Desktop.
Advent of Code 2023 6
open System
let input = """Time: 7 15 30
Distance: 9 40 200""" |> (fun s -> s.Split('\n', StringSplitOptions.RemoveEmptyEntries))
type Race =
{ time : int64
distance : int64 }
let splitInts (s: string) = s.Split([|' '|], StringSplitOptions.RemoveEmptyEntries) |> Array.map int
let parseRaces (input: string array) =
let times = input[0].Substring(6) |> splitInts
let distances = input.[1].Substring(9) |> splitInts
Array.zip times distances |> Array.map (fun (t, d) -> { time = t; distance = d })
let parseRace (input: string array) =
let time =
input[0].Substring(6)
|> fun x -> x.Split([|' '|], StringSplitOptions.RemoveEmptyEntries)
|> String.Concat
|> int64
let distances =
input.[1].Substring(9)
|> fun x -> x.Split([|' '|], StringSplitOptions.RemoveEmptyEntries)
|> String.Concat
|> int64
{ time = time
distance = distances }
let amountOfWinCombos race =
let T = race.time
let D = race.distance
// amount of win combos are actually all integers values of X which satisfy the following equation:
// x^2 - T * x + D < 0
// where T - time, D - distance
let sqrtDiscriminant = T * T - 4L * D |> float |> sqrt
let x1 = (float T + sqrtDiscriminant) / 2.
let x2 = (float T - sqrtDiscriminant) / 2.
// we need to exclude roots of the equation, and floor/ceil won't work if roots of the equation are integers
let x1Floor =
if x1 = int x1 then int64 x1 - 1L
else floor x1 |> int64
let x2Ceil =
if x2 = int x2 then int64 x2 + 1L
else ceil x2 |> int64
x1Floor - x2Ceil + 1L
let part1 =
parseRaces input
|> Seq.map amountOfWinCombos
|> Seq.reduce (*) // 288
let part2 =
parseRace input
|> amountOfWinCombos // 71503
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment