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

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