Advent of Code 2024 Day13

For every input, there is only one or zero solution, so that is not a coding question, it checks if you know basic math. :D

type Day13(lines: string[]) =
    let lines =
        String.Join("", lines)
        |> split2Int64ByReg @"(\d+)"
        |> Array.concat
        |> fun nums -> nums |> Array.splitInto (nums.Length / 6)

    let getMinCost (ai, aj) (bi, bj) (ti, tj) =
        // a * ai + b * bi = ti
        // a * aj + b * bj = tj
        // solve a, b
        // because for every a, b, t only have one or zero int solution
        let d = ai * bj - aj * bi
        let a = (ti * bj - tj * bi) / d
        let b = (tj * ai - ti * aj) / d

        if a * ai + b * bi = ti && a * aj + b * bj = tj then
            Some(a * 3L + b)
        else
            None

    member this.Q1() =
        lines
        |> Array.toList
        |> List.choose (fun nums -> getMinCost (nums[0], nums[1]) (nums[2], nums[3]) (nums[4], nums[5]))
        |> List.sum

    member this.Q2() =
        lines
        |> Array.toList
        |> List.choose (fun nums ->
            getMinCost (nums[0], nums[1]) (nums[2], nums[3]) (10000000000000L + nums[4], 10000000000000L + nums[5]))
        |> List.sum

You can find the source code at https://github.com/zangruizhe/AoC