2024 day 3 part 2

This commit is contained in:
tristan 2024-12-03 15:28:09 +00:00
parent 070f5ea6ee
commit 3d6e027de1
2 changed files with 61 additions and 0 deletions

View file

@ -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)
;
}

View file

@ -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;
})
])
]