diff --git a/2024/02/solution.nix b/2024/02/solution.nix index c04f85c..b467e75 100644 --- a/2024/02/solution.nix +++ b/2024/02/solution.nix @@ -23,6 +23,7 @@ } ) {safe = true;}; + abs = n: if n > 0 then n else -n; countSafety = lib.lists.count (level: level.safe); @@ -35,4 +36,42 @@ ; part1result = getPart1Result content; + + excluding = l: i: let + len = builtins.length l; + before = lib.sublist 0 (i) l; + after = lib.sublist (i + 1) (len - 1) l; + in before ++ after + ; + + dampLevels = l: let + len = builtins.length l; + range = lib.range 0 (len - 1); + toTest = map (excluding l) range + ; + in toTest; + + anySafety = builtins.any (level: level.safe); + + dampSafety = level: level + |> dampLevels + |> map isSafe + |> anySafety + ; + + isSafeWithDamp = level: + ( isSafe level ).safe || ( dampSafety level ) + ; + + countSafeWithDamp = levels: levels + |> map isSafeWithDamp + |> lib.count (a: a == true) + ; + + part2result = content + |> toLines + |> toLevels + |> countSafeWithDamp + ; + } diff --git a/2024/02/solution.test.nix b/2024/02/solution.test.nix index 70ef143..76fb34f 100644 --- a/2024/02/solution.test.nix +++ b/2024/02/solution.test.nix @@ -4,7 +4,7 @@ let solution = import ./solution.nix pkgs; example = (solution {file = ./example.txt;}); in [ - (describe "part1" [ + (describe "part 1" [ (it "gets file content" { expected = '' 7 6 4 2 1 @@ -72,4 +72,54 @@ in [ 1 3 6 7 9''; }) ]) + (describe "part 2" [ + + (it "excludes index" { + expected = [1 2 4 5]; + actual = example.excluding [1 2 7 4 5] 2; + }) + + (it "gets damp level" { + expected = [ + [2 7 4 5] + [1 7 4 5] + [1 2 4 5] + [1 2 7 5] + [1 2 7 4] + ]; + actual = [1 2 7 4 5] + |> example.dampLevels + ; + }) + + (it "gets damp safety" { + expected = true; + actual = example.dampSafety [1 2 7 4 5] + ; + }) + + (it "gets optional damp safety" { + expected = true; + actual = example.isSafeWithDamp [1 2 7 4 5] + ; + }) + + (it "counts optional damp safety" { + expected = 4; + actual = example.countSafeWithDamp [ + [7 6 4 2 1] + [1 2 7 8 9] + [9 7 6 2 1] + [1 3 2 4 5] + [8 6 4 4 1] + [1 3 6 7 9] + ]; + }) + + (it "counts optional damp safety from input" { + expected = 4; + actual = example.part2result; + }) + + ]) ]