https://git.jolheiser.com/adventofnix.git
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
let pkgs = import <nixpkgs> { }; input = builtins.readFile ./input; lines = builtins.filter (i: i != "") (pkgs.lib.strings.splitString "\n" input); removeElem = idx: list: (if idx != 0 then (pkgs.lib.sublist 0 idx list) else [ ]) ++ ( if idx != (builtins.length list) then (pkgs.lib.sublist (idx + 1) ((builtins.length list) - idx) list) else [ ] ); reports = builtins.map ( l: let split = pkgs.lib.strings.splitString " " l; in builtins.map (s: pkgs.lib.toInt s) split ) lines; safe = report: let range = pkgs.lib.range 0 ((builtins.length report) - 1); asc = builtins.sort (p: q: p > q) report; desc = builtins.sort (p: q: p < q) report; tolerable = builtins.foldl' ( s: idx: let elem = builtins.elemAt report idx; prev = if idx != 0 then builtins.elemAt report (idx - 1) else 0; diff = if elem < prev then prev - elem else elem - prev; in if idx != 0 then s && (0 < diff && diff < 4) else true ) true range; in (report == asc || report == desc) && tolerable; part1 = builtins.foldl' (sum: report: if (safe report) then sum + 1 else sum) 0 reports; permutations = builtins.map ( r: let range = pkgs.lib.range 0 ((builtins.length r) - 1); in builtins.map (idx: removeElem idx r) range ) reports; part2 = builtins.foldl' ( sum: muts: let isSafe = builtins.foldl' (s: mut: s || (safe mut)) false muts; in if isSafe then sum + 1 else sum ) 0 permutations; in [ part1 part2 ]