Published
Edited
Dec 10, 2020
Insert cell
Insert cell
Insert cell
findInvalid = (preambleSize, stream) => {
const preamble = stream.slice(0, preambleSize);
// let testCount = 0;

for (let i = preambleSize; i < stream.length; i++) {
let valid = false;
const target = stream[i];

for (let j = 0; j < preambleSize - 1 && !valid; j++) {
for (let k = j + 1; k < preambleSize && !valid; k++) {
// if (++testCount > 1000) throw "Infinite Loop";
if (preamble[j] + preamble[k] === target) {
valid = true;
}
}
}

if (!valid) {
return target;
}

preamble.shift();
preamble.push(target);
}
}
Insert cell
parse = input => input.split('\n').map(n => parseInt(n))
Insert cell
findInvalid(5, parse(testInput))
Insert cell
Insert cell
Insert cell
part1Answer = findInvalid(25, parse( input ))
Insert cell
Insert cell
findRangeThatSumsTo = (target, stream) => {
for (let i = 0; i < stream.length - 1; i++) {
let sum = stream[i];
for (let j = i + 1; j < stream.length && sum <= target; j++) {
sum += stream[j];
if (sum === target) {
const range = stream.slice(i, j + 1);
const smallest = Math.min.apply(null, range);
const largest = Math.max.apply(null, range);
return smallest + largest;
}
}
}
}
Insert cell
// Trying to do it with array functions, array.find() kind of simulates early return
// but we can't stop looking on the inner loop when sum > target

findRangeThatSumsTo2 = (target, stream) => {
let highIdx;

const lowIdx = stream.findIndex((firstVal, firstIdx) => {
let sum = firstVal;

const sumIdx = stream.slice(firstVal + 1).find((nextVal, nextIdx) => {
sum += nextVal;
return sum === target;
});

if (sumIdx) {
highIdx = sumIdx;
return true;
}
});

const range = stream.slice(lowIdx, highIdx + 1);
const smallest = Math.min.apply(null, range);
const largest = Math.max.apply(null, range);
return smallest + largest;
}
Insert cell
findRangeThatSumsTo(127, parse(testInput))
Insert cell
findRangeThatSumsTo( part1Answer, parse( input ) )
Insert cell
findRangeThatSumsTo2(127, parse(testInput))
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more