44 lines
1.2 KiB
Nix
44 lines
1.2 KiB
Nix
# nix eval -f ./day_1.nix -I 'input=(builtins.readFile ./puzzle_cache/day_1_1)' countZero
|
|
{ input ? (builtins.readFile ./puzzle_cache/day_1_0) }:
|
|
let
|
|
utils = import ./utils.nix;
|
|
inherit (utils) toIntBase10 mod;
|
|
|
|
# Split into non-empty lines
|
|
lines = builtins.filter (s: builtins.isString s && s != "") (builtins.split "\n" input);
|
|
|
|
# Parse a line like "L68" or "R14"
|
|
parseLine = line: {
|
|
dir = builtins.substring 0 1 line;
|
|
dist = toIntBase10 (builtins.substring 1 (builtins.stringLength line - 1) line);
|
|
};
|
|
|
|
rotations = map parseLine lines;
|
|
|
|
# Fold over the list to simulate the dial
|
|
step =
|
|
state: rot:
|
|
let
|
|
position =
|
|
if rot.dir == "L" then
|
|
mod (state.position - rot.dist) 100
|
|
else if rot.dir == "R" then
|
|
mod (state.position + rot.dist) 100
|
|
else
|
|
builtins.trace "Invalid direction: ${rot.dir}" state.position;
|
|
countZero = state.countZero + (if position == 0 then 1 else 0);
|
|
in
|
|
{
|
|
inherit position countZero;
|
|
};
|
|
|
|
initialState = {
|
|
position = 50;
|
|
countZero = 0;
|
|
};
|
|
|
|
finalState = builtins.foldl' step initialState rotations;
|
|
in
|
|
{
|
|
inherit (finalState) position countZero;
|
|
}
|