jsadvent/solutions/2015/6.js
2020-12-12 00:59:44 -06:00

75 lines
1.7 KiB
JavaScript

const { Glib, Vector, twodee } = require('../../lib');
const COMMANDS = {
TURN_ON: Symbol('TURN_ON'),
TURN_OFF: Symbol('TURN_OFF'),
TOGGLE: Symbol('TOGGLE'),
};
const cmd = new Map([
['turn on', COMMANDS.TURN_ON],
['turn off', COMMANDS.TURN_OFF],
['toggle', COMMANDS.TOGGLE],
]);
const parse = (input) =>
Glib.fromLines(input).map((l) => {
const [
str,
command,
pt1,
pt2,
] = /^([^\d]+)(\d+,\d+) through (\d+,\d+)$/.exec(l);
return [
cmd.get(command.trim()),
twodee.Rectangle.fromPoints(
Vector.fromString(`(${pt1})`),
Vector.fromString(`(${pt2})`),
),
];
});
const ops1 = {
[COMMANDS.TURN_ON](map, pt) {
map.set(pt, 1n);
},
[COMMANDS.TURN_OFF](map, pt) {
map.set(pt, 0n);
},
[COMMANDS.TOGGLE](map, pt) {
map.update(pt, (v = 0n) => (v === 0n ? 1n : 0n));
},
};
const ops2 = {
[COMMANDS.TURN_ON](map, pt) {
map.update(pt, (v = 0n) => v + 1n);
},
[COMMANDS.TURN_OFF](map, pt) {
map.update(pt, (v = 0n) => (v <= 1n ? 0n : v - 1n));
},
[COMMANDS.TOGGLE](map, pt) {
map.update(pt, (v = 0n) => v + 2n);
},
};
module.exports = {
'1': (input) =>
parse(input)
.reduce((acc, [cmd, rect]) => {
// console.log(cmd, pt1.string, pt2.string);
rect.allPoints().forEach((pt) => ops1[cmd](acc, pt.string));
return acc;
}, new Map())
.glibValues.sum(),
'2': (input) =>
parse(input)
.reduce((acc, [cmd, rect]) => {
// console.log(cmd, pt1.string, pt2.string);
rect.allPoints().forEach((pt) => ops2[cmd](acc, pt.string));
return acc;
}, new Map())
.glibValues.sum(),
};