advent-of-code/2024/day01/default.nix

44 lines
856 B
Nix
Raw Normal View History

2024-12-02 16:19:17 +01:00
{ pkgs, lib }:
with lib;
let
input = pipe (fileContents ./input.txt) [
(splitString "\n")
(map (split "[[:space:]]+"))
(map (x: {
fst = elemAt x 0;
snd = elemAt x 2;
}))
(x: {
fst = catAttrs "fst" x;
snd = catAttrs "snd" x;
})
];
abs = x: if x < 0 then -x else x;
answer1 = lib.pipe input [
(mapAttrs (_: xs: sort lessThan (map toInt xs)))
({ fst, snd }: zipListsWith (x: y: abs (x - y)) fst snd)
(foldl add 0)
toString
];
similarity = left: right: let
rightCount = foldl (acc: x: acc // { ${x} = (acc.${x} or 0) + 1; }) { } right;
in foldl add 0 (map (x: (toInt x) * rightCount.${x} or 0) left);
answer2 = lib.pipe input [
({ fst, snd }: similarity fst snd)
toString
];
in
pkgs.writeText "answers" ''
Task1:
${answer1}
Task2:
${answer2}
''