Advent-of-Nix-2024/utils.nix

53 lines
1.8 KiB
Nix
Raw Normal View History

2024-12-01 15:50:11 +01:00
{ lib, ... }:
with lib;
with builtins; rec {
2024-12-02 10:00:36 +01:00
readLines = f: init (filter isString (split "\n" (readFile f)));
2024-12-03 10:51:06 +01:00
reSplit = re: s: filter isString (split re s);
matchAll = re: s: filter isList (split re s);
splitWhitespace = reSplit "[[:space:]]+";
2024-12-01 15:50:11 +01:00
abs = i: if i >= 0 then i else i * -1;
delta = x: y: abs (x - y);
listSum = foldl' add 0;
2024-12-04 13:12:45 +01:00
listSumWith = f: l: foldl' add 0 (map f l);
2024-12-02 10:05:27 +01:00
deleteAt = l: i: (take i l) ++ (drop (i + 1) l);
2024-12-01 15:59:47 +01:00
eq = x: y: x == y;
2024-12-02 10:00:36 +01:00
greaterThan = x: y: x > y;
2024-12-08 16:53:16 +01:00
listRange = l: genList identity (length l);
2024-12-04 13:12:45 +01:00
invert = f: x: !(f x);
2024-12-05 11:21:11 +01:00
elemAtMid = l: elemAt l ((length l) / 2);
removeAll = rl: (flip pipe) (map remove rl);
2024-12-05 17:32:08 +01:00
pipe' = flip pipe;
2024-12-07 00:34:32 +01:00
inRange = i: l: (i >= 0) && (i < length l);
2024-12-08 16:53:16 +01:00
identity = x: x;
2024-12-07 00:34:32 +01:00
transpose = l: map (i: map ((flip elemAt) i) l) (listRange (head l));
matVecMul = m: v: map (r: foldl' add 0 (zipListsWith mul v r)) m;
vecSum = zipListsWith add;
2024-12-08 16:53:16 +01:00
vecDiff = zipListsWith sub;
scalarVecMul = i: map (mul i);
scalarVecDiv = i: map ((flip div) i);
2024-12-07 00:34:32 +01:00
matIndex = i: pipe' (map (flip elemAt) i);
inRangeMatrix = i: m:
if i == [ ] then
true
else
(isList m) && (inRange (head i) m)
&& (inRangeMatrix (tail i) (elemAt m (head i)));
2024-12-08 16:53:16 +01:00
raycastUntil = pred: direction: pos:
if pred pos then
[ ]
else
[ pos ] ++ (raycastUntil pred direction (vecSum pos direction));
getMatrixIndices = m: let
makeLayers = m: if isList m then [ (listRange m) ] ++ (makeLayers (head m)) else [];
layers = makeLayers m;
in mapCartesianProduct (args@{...}: attrValues args) (listToAttrs (map (k: nameValuePair (toString k) (elemAt layers k)) (listRange layers)));
gcd = a: b: if a == 0 then b else if b == 0 then a else if a < b then gcd b a else gcd b (mod a b);
listGcd = l: foldl' gcd (head l) (tail l);
shortenVec = vec: scalarVecDiv (listGcd (map abs vec)) vec;
2024-12-01 15:50:11 +01:00
}