advent_of_code/2025/day_2.nix

66 lines
1.8 KiB
Nix

# nix eval -f ./day_2.nix part1
# nix eval -f ./day_2.nix part1 --arg input 'builtins.readFile ./puzzle_cache/day_2_1'
# nix eval -f ./day_2.nix part2
# nix eval -f ./day_2.nix part2 --arg input 'builtins.readFile ./puzzle_cache/day_2_1'
{
input ? (builtins.readFile ./puzzle_cache/day_2_0),
}:
with builtins;
with import ./utils.nix;
let
# part 1 simple repeat middle of word
isStrPatternSplit =
str:
let
strLen = stringLength str;
in
(
if mod strLen 2 == 0 then
let
half = strLen / 2;
firstHalf = substring 0 half str;
secondHalf = substring half strLen str;
in
firstHalf == secondHalf
else
false
);
# part 2 any repeat num
isStrPatternRepeated =
str:
let
strLen = stringLength str;
maxSplit = strLen / 2; # Only check up to half length since it must repeat at least twice
splits = genList (i: i + 1) maxSplit;
in
any (
split:
if mod strLen split == 0 then
let
parts = splitStringByLength str split;
in
all (e: e == elemAt parts 0) parts
else
false
) splits;
ranges = map (range: map (v: toIntBase10 v) (split "-" range)) (split "," input);
fullRanges = map (itr: map (v: toString v) (rangeInclusive (elemAt itr 0) (elemAt itr 1))) ranges;
getSumOfBadIdsGivenBadIdFunc =
badIdFunc:
let
invalidIds = flatten (
map (
range: (foldl' (invalidIds: id: invalidIds ++ (if badIdFunc id then [ id ] else [ ])) [ ] range)
) fullRanges
);
invalidIdNums = map (v: toIntBase10 v) invalidIds;
invalidIdSum = sum invalidIdNums;
in
invalidIdSum;
in
{
part1 = getSumOfBadIdsGivenBadIdFunc isStrPatternSplit;
part2 = getSumOfBadIdsGivenBadIdFunc isStrPatternRepeated;
}