From ff7f326e1d162e3983b70e217db98b77dac8bae0 Mon Sep 17 00:00:00 2001 From: Grimmauld Date: Mon, 2 Dec 2024 22:36:05 +0100 Subject: [PATCH] alternative day 2 solution: zipListsWith for deltas, just two checks --- day2/default.nix | 17 ++++------------- utils.nix | 1 + 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/day2/default.nix b/day2/default.nix index e74c200..cee8a33 100644 --- a/day2/default.nix +++ b/day2/default.nix @@ -4,20 +4,11 @@ with builtins; with utils; let records = map (l: map toInt (splitWhitespace l)) (readLines ./input); - getMaxDelta = l: - (foldl' (prev: value: { - inherit value; - maxDelta = max prev.maxDelta (delta prev.value value); - }) { - value = head l; - maxDelta = 0; - } l).maxDelta; + getDeltas = r: zipListsWith sub (init r) (drop 1 r); isSafe = r: - let sorted = sort lessThan r; - in (r == sorted || r == (reverseList sorted)) && allUnique r - && (3 >= getMaxDelta r); - isSafeDampened = r: - any isSafe ([ r ] ++ (map (deleteAt r) (range 0 (length r)))); + let deltas = getDeltas r; + in (all (d: -3 <= d && d < 0) deltas) || (all (d: 3 >= d && d > 0) deltas); + isSafeDampened = r: any isSafe (map (deleteAt r) (listRange r)); in { part1 = count isSafe records; part2 = count isSafeDampened records; diff --git a/utils.nix b/utils.nix index bcc0236..5b041ad 100644 --- a/utils.nix +++ b/utils.nix @@ -9,4 +9,5 @@ with builtins; rec { deleteAt = l: i: (take i l) ++ (drop (i + 1) l); eq = x: y: x == y; greaterThan = x: y: x > y; + listRange = l: range 0 (length l); }