You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
1.4 KiB
JavaScript
71 lines
1.4 KiB
JavaScript
const { readInput } = require("./util");
|
|
|
|
const { lines } = readInput("input");
|
|
|
|
class Buffer {
|
|
constructor(size = 25) {
|
|
this.buffer = [];
|
|
this.size = size;
|
|
}
|
|
|
|
push(val) {
|
|
this.buffer.push(val);
|
|
if (this.buffer.length > this.size) {
|
|
this.buffer.shift();
|
|
}
|
|
}
|
|
|
|
isValid(val) {
|
|
if (this.buffer.length < this.size) {
|
|
return true;
|
|
}
|
|
for (let a = 0; a < this.buffer.length; a++) {
|
|
const wanted = val - this.buffer[a];
|
|
for (let b = a + 1; b < this.buffer.length; b++) {
|
|
if (this.buffer[b] === wanted) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
let weakness = null;
|
|
const buffer = new Buffer(25);
|
|
for (const line of lines) {
|
|
const val = parseInt(line);
|
|
// console.log(buffer.buffer, val, buffer.isValid(val));
|
|
if (!buffer.isValid(val)) {
|
|
weakness = val;
|
|
break;
|
|
}
|
|
buffer.push(parseInt(line));
|
|
}
|
|
|
|
const stream = lines.map((line) => parseInt(line));
|
|
|
|
let lower = 0;
|
|
let upper = 0;
|
|
let sum = stream[0];
|
|
|
|
while (sum !== weakness && lower < stream.length) {
|
|
while (sum > weakness) {
|
|
sum -= stream[upper];
|
|
upper--;
|
|
}
|
|
while (sum < weakness) {
|
|
upper++;
|
|
sum += stream[upper];
|
|
}
|
|
sum -= stream[lower];
|
|
lower++;
|
|
}
|
|
|
|
const range = stream.slice(lower, upper + 1);
|
|
const [min, max] = [Math.min(...range), Math.max(...range)];
|
|
console.log({ lower, upper, range, min, max });
|
|
|
|
console.log("Solution:");
|
|
console.log(min + max);
|