Skip to content

Commit a86f56a

Browse files
committed
Solve day 2 part 2
1 parent 2cfaa72 commit a86f56a

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

day02/derivation.nix

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
echo "Usage: \$0 <path to input>"
1919
exit 1
2020
fi
21-
exec nix-instantiate --eval --strict --arg inputPath "\"\$(${coreutils.outPath}/bin/realpath \$1)\"" "\$(dirname "\$0")/../share/day02.nix"
21+
exec nix-instantiate --eval --show-trace --strict --arg inputPath "\"\$(${coreutils.outPath}/bin/realpath \$1)\"" "\$(dirname "\$0")/../share/day02.nix"
2222
EOF
2323
2424
chmod +x $out/bin/day02

day02/src/day02.nix

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
11
{ inputPath, lib ? import <nixpkgs/lib> }:
2-
let inherit (builtins) length readFile;
3-
inherit (lib.lists) all count filter head tail zipListsWith;
2+
let inherit (builtins) head tail length readFile;
3+
inherit (lib.lists) all any count filter range zipListsWith;
44
inherit (lib.strings) splitString toInt stringLength;
5+
inherit (lib.trivial) flip;
56
in
67
let abs = x: if x >= 0 then x else -x;
78
compose = f: g: x: f (g x);
9+
dropNth = n: xs: if n == 0 then tail xs else [(head xs)] ++ dropNth (n - 1) (tail xs);
10+
removeOne = r: map (flip dropNth r) (range 0 (length r - 1));
811
input = readFile inputPath;
912
isNonEmpty = s: stringLength s > 0;
1013
lines = filter isNonEmpty (splitString "\n" input);
1114
reports = map (compose (map toInt) (splitString " ")) lines;
12-
isSafe = r: let diffs = zipListsWith (x: y: x - y) r (tail r);
15+
isSafe1 = r: let diffs = zipListsWith (x: y: x - y) r (tail r);
1316
in (all (x: x > 0) diffs || all (x: x < 0) diffs)
1417
&& all (x: x >= 1 && x <= 3) (map abs diffs);
15-
part1 = count isSafe reports;
16-
in "Part 1: " + toString part1
18+
isSafe2 = compose (any isSafe1) removeOne;
19+
part1 = count isSafe1 reports;
20+
part2 = count isSafe2 reports;
21+
in "Part 1: " + toString part1 + ", Part 2: " + toString part2

0 commit comments

Comments
 (0)