Published
Edited
Dec 10, 2020
Insert cell
Insert cell
Insert cell
answer1 = {
loop: for (let i = 25; i < input.length; i++) {
const val = input[i];
for (let j = i - 25; j < i; j++) {
const vk = input[j];
for (let k = j + 1; k < i; k++) {
if (vk + input[k] === val) continue loop;
}
}
return { i, val };
}
}
Insert cell
Insert cell
answer2 = {
const sIdx = answer1.i;
const sum = answer1.val;

const ranges = new Set();
let rIdx = -1;
// Kind of like the "Sieve of Eratosthenes", with ranges instead of primes
// Start with finding all ranges [n, n+1] that add up to less than sum
// Then from those ranges, find all ranges [n, n+2] that sum up to... etc.
// Repeat until we find the range that equals the sum.
for (let i = 0; i + 1 < sIdx && rIdx < 0; i++) {
const rangeSum = input[i] + input[i + 1];
if (rangeSum < sum) ranges.add({ i, r0: input[i], sum: rangeSum });
}
// extend range lengths and
let rangeLength = 2;
while (ranges.size > 1) {
for (let range of ranges) {
const iEnd = range.i + rangeLength;
// range can't extend over sum
if (iEnd >= sIdx) {
ranges.delete(range);
} else {
const rEnd = input[iEnd];
range.sum += rEnd;
if (range.sum > sum) {
// out of range
ranges.delete(range);
} else if (range.sum === sum) {
return { i: range.i, sum: range.r0 + rEnd };
}
}
}
rangeLength++;
}
}
Insert cell
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