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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more