jsadvent/solutions/2020/9.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2020-12-10 08:33:00 +00:00
const { Glib, BNMath: Math, Vector, twodee } = require('../../lib');
const invalid = (input, preamble = 25) => {
for (let i = preamble; i < input.length; i++) {
const current = input[i];
let solved = false;
dance: for (let j = i - preamble; j < i; j++) {
for (let k = j + 1; k < i; k++) {
if (input[j] + input[k] === current) {
solved = true;
break dance;
}
}
}
if (!solved) {
return current;
}
}
throw new Error('no invalid found');
};
const parse = (input) => Glib.fromLines(input).toInts().array;
module.exports = {
'1': (input) => invalid(parse(input)),
'2': (input) => {
input = parse(input);
const target = invalid(input);
dance: for (let i = 0; i < input.length - 1; i++) {
for (let j = i + 1; j < input.length; j++) {
const sum = input.slice(i, j).glib.sum();
if (sum === target) {
return input
.slice(i, j)
.glib.minMax()
.glib.sum();
} else if (sum > target) {
continue dance;
}
}
}
},
};