adventofcode/2022/10/part1.js

63 lines
1.4 KiB
JavaScript

import * as R from "remeda";
import { readFile } from "../05/part1.js";
const readInput = (...args) =>
R.pipe(
readFile(...args),
(lines) => lines.split("\n"),
R.compact, // remove last line
R.map((line) => line.split(" ").map((v, i) => (i ? parseInt(v) : v)))
);
export const puzzleInput = readInput(import.meta.url, "input");
export const sample = readInput(import.meta.url, "sample");
export const sample2 = readInput(import.meta.url, "sample.2");
export const comsys = () => {
let cycle = 1;
let register = 1;
const scheduled = [];
return (instr) => {
if (instr && instr[0] === "addx") {
scheduled.push(0, instr[1]);
} else if (instr) {
scheduled.push(0);
}
cycle++;
register += scheduled.shift() ?? 0;
return { cycle, register };
};
};
export const gatherStrength = () => {
let strength = 0;
return ({ cycle, signal, register }) => {
if ((cycle - 20) % 40 === 0) {
strength += signal;
}
return { strength, cycle, signal, register };
};
};
export const addSignal = (input) => ({
...input,
signal: input.cycle * input.register,
});
export default (instructions) => {
const sys = comsys();
instructions = [...instructions];
return R.pipe(
R.range(0, 220),
R.map(() => sys(instructions.shift())),
R.map(addSignal),
R.map(gatherStrength()),
R.last,
R.prop("strength")
);
};