Published
Edited
Dec 15, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function q1(input) {
let numbers = {};
let turn = 0;
let turns = input.slice();
while (turn < input.length) {
numbers[input[turn]] = [turn, turn];
turn++;
}
let distance = input[turn - 1];
while (turn < 2020) {
const lastSpoken = numbers[distance];
distance =
lastSpoken[lastSpoken.length - 1] - lastSpoken[lastSpoken.length - 2];
const dLastSpoken = numbers[distance];
if (dLastSpoken) dLastSpoken.push(turn);
else numbers[distance] = [turn, turn];
turns.push(distance);
turn++;
}
return { distance, turns, numbers };
}
Insert cell
testAnswers = testInputs.map(q1)
Insert cell
Insert cell
answer1 = q1(input)
Insert cell
Insert cell
function* q2(input) {
const t0 = performance.now();
let numbers = {};
let turn = 0;
while (turn < input.length) {
numbers[input[turn]] = [turn, turn];
turn++;
}
let distance = input[turn - 1];
// 30000000
while (turn < 30000000) {
const lastSpoken = numbers[distance];
distance = lastSpoken[0] - lastSpoken[1];
const dLastSpoken = numbers[distance];
if (dLastSpoken) {
dLastSpoken[1] = dLastSpoken[0];
dLastSpoken[0] = turn;
} else numbers[distance] = [turn, turn];
turn++;
if (turn % 500000 === 0)
yield { turn, distance, numbers, time: (performance.now() - t0) / 1000 };
}
yield { turn, distance, numbers, time: (performance.now() - t0) / 1000 };
}
Insert cell
answer2 = {
await visibility();
return q2(input);
}
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