jsadvent/solutions/2016/2.js
2020-12-10 02:33:00 -06:00

72 lines
1.6 KiB
JavaScript

const { Glib, Vector } = require('../../lib');
const generatePad = (layout) => {
const PAD = {};
const rows = layout.split('\n');
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
const source = rows[i][j];
if (source.match(/\s/)) {
continue;
}
const NUM = {};
const pi = i - 1;
if (pi >= 0 && pi < rows.length) {
const target = rows[pi][j];
if (target !== ' ' && typeof target === 'string') NUM.U = target;
}
const ni = i + 1;
if (ni < rows.length) {
const target = rows[ni][j];
if (target !== ' ' && typeof target === 'string') NUM.D = target;
}
const pj = j - 1;
if (pj >= 0) {
const target = rows[i][pj];
if (target !== ' ' && typeof target === 'string') NUM.L = target;
}
const nj = j + 1;
if (nj < rows.length) {
const target = rows[i][nj];
if (target !== ' ' && typeof target === 'string') NUM.R = target;
}
PAD[source] = NUM;
}
}
return PAD;
};
const PAD1txt = `
123
456
789
`;
const PAD2txt = `
1
234
56789
ABC
D
`;
const solve = (input, PAD) =>
Glib.fromLines(input)
.reduce(
(code, line) =>
code +
line
.trim()
.split('')
.reduce((last, direction) => {
return PAD[last][direction] || last;
}, code[code.length - 1]),
'5',
)
.slice(1);
module.exports = {
'1': (input) => solve(input, generatePad(PAD1txt)),
'2': (input) => solve(input, generatePad(PAD2txt)),
};