adventofcode/2022/10/part1.js

63 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-12-10 22:54:56 +00:00
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 = () => {
2022-12-10 23:25:50 +00:00
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);
2022-12-10 22:54:56 +00:00
}
2022-12-10 23:25:50 +00:00
cycle++;
register += scheduled.shift() ?? 0;
return { cycle, register };
};
};
2022-12-10 22:54:56 +00:00
export const gatherStrength = () => {
2022-12-10 23:25:50 +00:00
let strength = 0;
return ({ cycle, signal, register }) => {
if ((cycle - 20) % 40 === 0) {
strength += signal;
2022-12-10 22:54:56 +00:00
}
2022-12-10 23:25:50 +00:00
return { strength, cycle, signal, register };
};
};
2022-12-10 22:54:56 +00:00
export const addSignal = (input) => ({
2022-12-10 23:25:50 +00:00
...input,
signal: input.cycle * input.register,
2022-12-10 22:54:56 +00:00
});
export default (instructions) => {
2022-12-10 23:25:50 +00:00
const sys = comsys();
2022-12-10 22:54:56 +00:00
2022-12-10 23:25:50 +00:00
instructions = [...instructions];
2022-12-10 22:54:56 +00:00
2022-12-10 23:25:50 +00:00
return R.pipe(
R.range(0, 220),
R.map(() => sys(instructions.shift())),
R.map(addSignal),
R.map(gatherStrength()),
R.last,
R.prop("strength")
);
2022-12-10 22:54:56 +00:00
};