Published
Edited
Dec 15, 2020
Insert cell
Insert cell
testInput = [0,3,6];
Insert cell
step = (memo, last, stepNum) => {
const prevStepWithLast = memo.get(last);
memo.set(last, stepNum);
if (prevStepWithLast === undefined) return 0;
return stepNum - prevStepWithLast;
}
Insert cell
{
const memo = new Map([[0, 0], [3, 1]]);
let nextNum,
count = 2;
nextNum = step(memo, 6, count++); // 0
nextNum = step(memo, nextNum, count++); // 3
nextNum = step(memo, nextNum, count++); // 3
nextNum = step(memo, nextNum, count++); // 1
nextNum = step(memo, nextNum, count++); // 0
nextNum = step(memo, nextNum, count++); // 4
// nextNum = step(memo, nextNum, count++); // 0
return nextNum;
}
Insert cell
parseInput = input => {
const inputCopy = [...input];
const last = inputCopy.pop();
const memo = new Map(inputCopy.map((n, i) => [n, i]));
return [memo, last, inputCopy.length];
}
Insert cell
parseInput(testInput)
Insert cell
run = (input, maxSteps) => {
let [memo, nextNum, seedLength] = parseInput(input);
for (let i = seedLength; i < maxSteps - 1; i++) {
nextNum = step(memo, nextNum, i);
}
// return memo;
return nextNum;
}
Insert cell
run(testInput, 2020)
Insert cell
run([1,3,2], 2020)
Insert cell
run([2,1,3], 2020)
Insert cell
run([1,2,3], 2020)
Insert cell
Insert cell
run([19,0,5,1,10,13], 2020)
Insert cell
Insert cell
run2 = (input, maxSteps) => {
let [memo, nextNum, seedLength] = parseInput(input);
let sequence = [...input];
for (let i = seedLength; i < maxSteps - 1; i++) {
nextNum = step(memo, nextNum, i);
sequence.push( nextNum );
}
return
return memo;
return sequence;
}
Insert cell
// run([19, 0, 5, 1, 10, 13], 30000000)
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