From 925e0b1a5133e4eb0c8fa7261043b2b4d8fa8949 Mon Sep 17 00:00:00 2001 From: Tyler Beckman Date: Wed, 11 Dec 2024 18:08:29 -0700 Subject: [PATCH] Impl d1p1 in nix --- day1/part1.nix | 46 ++++++++++++++++++++++++++++++++++++++++++++++ flake.lock | 6 +++--- 2 files changed, 49 insertions(+), 3 deletions(-) create mode 100644 day1/part1.nix diff --git a/day1/part1.nix b/day1/part1.nix new file mode 100644 index 0000000..9330a69 --- /dev/null +++ b/day1/part1.nix @@ -0,0 +1,46 @@ +let + # Import nixpkgs lib and input file + inherit ((builtins.getFlake (builtins.toString ./..)).inputs.nixpkgs) lib; + input = builtins.readFile (builtins.toString ./input.txt); + + # Define functions + abs = n: if n < 0 then (-n) else n; + + # Do parsing + parsed = ( # Define function to sort lines into two lists + lib.lists.foldr + (cur: acc: { + first = acc.first ++ [(lib.strings.toIntBase10 (builtins.elemAt cur 0))]; + second = acc.second ++ [(lib.strings.toIntBase10 (builtins.elemAt cur 1))]; + }) + { first = []; second = []; } + ) ( # Call with input split on newlines and 3 spaces; formatted like [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] + lib.lists.forEach + (lib.strings.splitString "\n" input) + (e: lib.strings.splitString " " e) + ); + sorted = { + first = lib.lists.sort (a: b: a < b) parsed.first; + second = lib.lists.sort (a: b: a < b) parsed.second; + }; + reorganized = ( + lib.lists.imap0 + (i: e: [ e (builtins.elemAt sorted.second i) ]) + sorted.first + ); + + output = ( + ( + lib.lists.foldr + ( + cur: acc: + acc + ( + abs ( + (builtins.elemAt cur 0) - (builtins.elemAt cur 1) + ) + ) + ) + 0 + ) reorganized + ); +in output \ No newline at end of file diff --git a/flake.lock b/flake.lock index a632061..c52050c 100644 --- a/flake.lock +++ b/flake.lock @@ -20,11 +20,11 @@ }, "nixpkgs": { "locked": { - "lastModified": 1733015953, - "narHash": "sha256-t4BBVpwG9B4hLgc6GUBuj3cjU7lP/PJfpTHuSqE+crk=", + "lastModified": 1733759999, + "narHash": "sha256-463SNPWmz46iLzJKRzO3Q2b0Aurff3U1n0nYItxq7jU=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "ac35b104800bff9028425fec3b6e8a41de2bbfff", + "rev": "a73246e2eef4c6ed172979932bc80e1404ba2d56", "type": "github" }, "original": {