Home

adventofnix @main - refs - log -
-
https://git.jolheiser.com/adventofnix.git
adventofnix / day01 / default.nix
- raw
 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
let
  pkgs = import <nixpkgs> { };
  input = builtins.readFile ./input;
  lines = builtins.filter (i: i != "") (pkgs.lib.strings.splitString "\n" input);
  pairs =
    builtins.foldl'
      (
        container: line:
        let
          parts = pkgs.lib.strings.splitString "   " line;
        in
        {
          left = container.left ++ [ (pkgs.lib.toInt (builtins.elemAt parts 0)) ];
          right = container.right ++ [ (pkgs.lib.toInt (builtins.elemAt parts 1)) ];
        }
      )
      {
        left = [ ];
        right = [ ];
      }
      lines;
  sorted = {
    left = builtins.sort (p: q: p < q) pairs.left;
    right = builtins.sort (p: q: p < q) pairs.right;
  };
  range = pkgs.lib.range 0 ((builtins.length sorted.left) - 1);
  part1 = builtins.foldl' (
    sum: idx:
    let
      l = builtins.elemAt sorted.left idx;
      r = builtins.elemAt sorted.right idx;
    in
    sum + (if l > r then l - r else r - l)
  ) 0 range;
  part2 = builtins.foldl' (
    score: idx:
    let
      l = builtins.elemAt sorted.left idx;
    in
    score + (l * (pkgs.lib.count (x: x == l) sorted.right))
  ) 0 range;
in
[
  part1
  part2
]