From 3d6e027de197e028e2cbd9646fddf6b727a77c3d Mon Sep 17 00:00:00 2001 From: tristan Date: Tue, 3 Dec 2024 15:28:09 +0000 Subject: [PATCH] 2024 day 3 part 2 --- 2024/03/solution.nix | 40 +++++++++++++++++++++++++++++++++++++++ 2024/03/solution.test.nix | 21 ++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/2024/03/solution.nix b/2024/03/solution.nix index 55c3209..dd2a50b 100644 --- a/2024/03/solution.nix +++ b/2024/03/solution.nix @@ -15,4 +15,44 @@ part1result = content |> muls |> mul; + conditionsAndMuls = memory: let + mulMatcher = ''mul\(([0-9]{0,3}),([0-9]{0,3})\)''; + conditionMatcher = ''(do|don't)\(\)''; + in memory + |> builtins.split "${mulMatcher}|${conditionMatcher}" + |> builtins.filter builtins.isList + |> map toInstruction + ; + + toInstruction = matches: let + elem = builtins.elemAt matches; + numOrZero = v: if isNull v + then 0 + else lib.strings.toInt v; + in { + cmd = let todo = elem 2; in + if isNull todo then "mul" else todo; + a = numOrZero (elem 0); + b = numOrZero (elem 1); + }; + + conditionalMul = builtins.foldl' + ({mul, acc}: n: { + acc = acc + mul * n.a * n.b; + mul = if n.cmd == "do" then 1 + else if n.cmd == "don't" then 0 + else mul; + }) + { + mul = 1; + acc = 0; + } + ; + + part2result = content + |> conditionsAndMuls + |> conditionalMul + |> (r: r.acc) + ; + } diff --git a/2024/03/solution.test.nix b/2024/03/solution.test.nix index 8df9f9f..ffe72d6 100644 --- a/2024/03/solution.test.nix +++ b/2024/03/solution.test.nix @@ -12,6 +12,17 @@ let ["11" "8"] ["8" "5"] ]; + td2 = '' + xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) + ''; + ti2 = [ + { a = 2; b = 4; cmd = "mul"; } + { a = 0; b = 0; cmd = "don't"; } + { a = 5; b = 5; cmd = "mul"; } + { a = 11; b = 8; cmd = "mul"; } + { a = 0; b = 0; cmd = "do"; } + { a = 8; b = 5; cmd = "mul"; } + ]; in [ (describe "part 1" [ (it "gets content" { @@ -31,4 +42,14 @@ in [ expected = 161; }) ]) + (describe "part 2" [ + (it "gets all instructions" { + actual = example.conditionsAndMuls td2; + expected = ti2; + }) + (it "conditional multiplies" { + actual = (example.conditionalMul ti2).acc; + expected = 48; + }) + ]) ]