Advent-of-Nix-2024/day9/default.nix

61 lines
1.8 KiB
Nix
Raw Permalink Normal View History

2024-12-09 14:55:22 +01:00
{ lib, utils, ... }:
with lib;
with builtins;
with utils;
let
disk = map toIntBase10 (stringToCharacters (head (readLines ./input)));
2024-12-31 11:26:01 +01:00
files = genList (id:
let baseIndex = id * 2;
in {
size = elemAt disk baseIndex;
freeAfter = if (baseIndex + 1) < (length disk) then
elemAt disk (baseIndex + 1)
else
0;
inherit id;
}) ((length disk) / 2 + 1);
2024-12-09 14:55:22 +01:00
totalSize = listSumWith (getAttr "size") files;
2024-12-31 11:26:01 +01:00
# totalFree = listSumWith (getAttr "freeAfter") files;
2024-12-09 14:55:22 +01:00
2024-12-31 11:26:01 +01:00
diskExpanded = concatLists (map
(f: (genList (const f.id) f.size) ++ (genList (const null) f.freeAfter))
files);
# diskSemiExpanded = concatLists (map (f: [ (genList (const f.id) f.size) f.freeAfter ]) files);
2024-12-09 14:55:22 +01:00
2024-12-31 11:26:01 +01:00
toMove = reverseList (filter (invert isNull) (drop totalSize diskExpanded));
# base = take totalSize diskExpanded;
2024-12-09 14:55:22 +01:00
2024-12-31 11:26:01 +01:00
compress = files': toMove':
let f = head files';
in if toMove' == [ ] then
(genList (const f.id) f.size)
else
(genList (const f.id) f.size) ++ (take f.freeAfter toMove')
++ (compress (tail files') (drop f.freeAfter toMove'));
2024-12-09 14:55:22 +01:00
2024-12-31 11:26:01 +01:00
compressed = take totalSize (compress files toMove);
# compressed = compress files toMove;
2024-12-09 14:55:22 +01:00
checksum = imap0 mul compressed;
in {
2024-12-31 11:26:01 +01:00
# part1 = listSum checksum;
2024-12-09 14:55:22 +01:00
# inherit files;
2024-12-31 11:26:01 +01:00
# test = listSumLog (sublist 0 50000 checksum);
part1 = listSumLog checksum;
2024-12-09 14:55:22 +01:00
# inherit chunks;
# inherit compressed;
2024-12-31 11:26:01 +01:00
# lenCompressed = length compressed;
# compressedHead = head compressed;
# inherit totalSize totalFree;
# inherit diskExpanded;
# moveLen = length toMove;
# nullsInBase = count isNull base;
# inherit disk;
2024-12-09 14:55:22 +01:00
# sumTest = listSumLog [1 2 3 4 5];
2024-12-31 11:26:01 +01:00
2024-12-09 14:55:22 +01:00
diskSize = listSum disk; # TOO DAMN LARGE FOR LINEAR RECURSION!
fileCount = length files; # TOO DAMN LARGE FOR LINEAR RECURSION!
}