aoc/2024/11/solution.nix

53 lines
1.2 KiB
Nix
Raw Normal View History

2024-12-11 22:14:48 +00:00
{lib, ...}: let
inherit (builtins) stringLength concatLists substring foldl' add attrValues;
inherit (lib.strings) toIntBase10;
in input: rec {
2024-12-11 12:18:32 +00:00
2024-12-12 22:17:35 +00:00
sum = foldl' add 0;
2024-12-11 22:14:48 +00:00
blinkStone = stone: count:
if toIntBase10 stone == 0 then [{ "1" = count; }]
2024-12-11 12:18:32 +00:00
else let
2024-12-11 22:14:48 +00:00
strStone = toString (toIntBase10 stone);
2024-12-11 12:18:32 +00:00
len = stringLength strStone;
2024-12-11 22:14:48 +00:00
left = (substring 0 (len / 2) strStone );
right = (substring (len / 2) (len / 2) strStone);
2024-12-11 12:18:32 +00:00
in
2024-12-11 22:14:48 +00:00
if lib.mod len 2 == 0 then
if left == right then [{${left} = count * 2;}] else [
{ ${left} = count; ${right} = count; }
]
else [{
${toString ((toIntBase10 stone) * 2024)} = count;
}]
2024-12-11 12:18:32 +00:00
;
2024-12-11 22:14:48 +00:00
bfast = stones: stones
2024-12-12 22:17:35 +00:00
|> builtins.mapAttrs blinkStone
2024-12-11 22:14:48 +00:00
|> attrValues
|> concatLists
2024-12-12 22:17:35 +00:00
|> builtins.zipAttrsWith (stone: sum)
2024-12-11 12:18:32 +00:00
;
2024-12-11 22:14:48 +00:00
bfastt = times: stones:
2024-12-12 22:17:35 +00:00
if times == 0 then stones |> attrValues |> sum
2024-12-11 22:14:48 +00:00
else bfastt (times - 1) (bfast stones)
2024-12-11 12:18:32 +00:00
;
2024-12-11 22:14:48 +00:00
initialStones = input
|> lib.trim
|> lib.splitString " "
|> map toIntBase10
|> toStones
2024-12-11 12:18:32 +00:00
;
2024-12-11 22:14:48 +00:00
toStones = numbers: numbers
|> map (number: {name = toString number; value = 1;})
|> builtins.listToAttrs
2024-12-11 12:18:32 +00:00
;
2024-12-11 22:14:48 +00:00
part1result = bfastt 25 initialStones;
part2result = bfastt 75 initialStones;
2024-12-11 12:18:32 +00:00
}