From 6064163a1149cff77824210e5e16bd002ee09010 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A1bor=20Gergely?= <ggergely@kodfodrasz.net> Date: Mon, 30 Dec 2024 00:53:02 +0100 Subject: [PATCH] Day 7 Part 2 --- Kodfodrasz.AoC.Year2024.Tests/Day7Tests.fs | 17 ++++++++++++-- Kodfodrasz.AoC.Year2024/Day7.fs | 26 +++++++++++++++++++++- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/Kodfodrasz.AoC.Year2024.Tests/Day7Tests.fs b/Kodfodrasz.AoC.Year2024.Tests/Day7Tests.fs index 35f2908..49183f1 100644 --- a/Kodfodrasz.AoC.Year2024.Tests/Day7Tests.fs +++ b/Kodfodrasz.AoC.Year2024.Tests/Day7Tests.fs @@ -85,11 +85,24 @@ let ``Answer 1 for example input`` () = let expected: Result<_, string> = Ok 3749L actual = expected @> -[<Fact(Skip="TODO")>] +[<Fact>] +let ``Answer 2 helper function: check2`` () = + let input = parseInput exampleInput |> Result.get + + test <@ true = Day7.check2 input[0] @> + test <@ true = Day7.check2 input[1] @> + test <@ true = Day7.check2 input[3] @> + test <@ true = Day7.check2 input[4] @> + test <@ false = Day7.check2 input[5] @> + test <@ true = Day7.check2 input[6] @> + test <@ false = Day7.check2 input[7] @> + test <@ true = Day7.check2 input[8] @> + +[<Fact>] let ``Answer 2 for example input`` () = let input = parseInput exampleInput test <@ let actual = Result.bind answer2 input - let expected: Result<_, string> = Ok 31 + let expected: Result<_, string> = Ok 11387L actual = expected @> diff --git a/Kodfodrasz.AoC.Year2024/Day7.fs b/Kodfodrasz.AoC.Year2024/Day7.fs index 87621b7..c9292c3 100644 --- a/Kodfodrasz.AoC.Year2024/Day7.fs +++ b/Kodfodrasz.AoC.Year2024/Day7.fs @@ -57,8 +57,32 @@ let answer1 (data : parsedInput) = |> Array.sumBy(fun eqn -> eqn.TestValue) |> Ok +let check2 (eqn : CalibrationEquation) = + let concat (a: int64) (b:int64) = + sprintf "%i%i" a b |> int64 + + let rec check goal acc terms = + match terms with + | [] -> goal = acc + | head :: tail -> + if acc > goal then false + else + if (check goal (concat acc head) tail) then + true + elif (check goal (acc + head) tail) then + true + else + check goal (acc * head) tail + match eqn.Terms with + | [] -> false + | h :: t -> check eqn.TestValue h t + let answer2 (data : parsedInput) = - failwith "TODO" + data + |> List.toArray + |> Array.Parallel.filter check2 + |> Array.sumBy(fun eqn -> eqn.TestValue) + |> Ok type Solver() = inherit SolverBase("Bridge Repair")