Published
Edited
Dec 14, 2020
Insert cell
Insert cell
testInput = `939
7,13,x,x,59,x,31,19`
Insert cell
parse = input => {
const [timestamp, busIds] = input.split('\n');
const busses = busIds
.split(',')
.filter(b => b !== 'x')
.map(n => parseInt(n));
return [parseInt(timestamp), busses];
}
Insert cell
parse(testInput)
Insert cell
Insert cell
nextBus = (timestamp, busId) => {
if (timestamp % busId === 0) {
return timestamp;
}
return timestamp + busId - (timestamp % busId);
}
Insert cell
1006726 % 19
Insert cell
part1 = input => {
const [timestamp, busIds] = parse(input);
return busIds.reduce((closest, busId) =>
nextBus(timestamp, busId) < nextBus(timestamp, closest) ? busId : closest
);
}
Insert cell
part1(testInput)
Insert cell
input = `1006726
23,x,x,x,x,x,x,x,x,x,x,x,x,41,x,x,x,x,x,x,x,x,x,647,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,13,19,x,x,x,x,x,x,x,x,x,29,x,557,x,x,x,x,x,37,x,x,x,x,x,x,x,x,x,x,17`
Insert cell
{
const bus = part1(input);
const [timestamp] = parse(input);
return bus * (nextBus(timestamp, bus) - timestamp);
}
Insert cell
Insert cell
part2 = input => {
const MAX_STEPS = 200000000;
const [timecode, busCodes] = input.split('\n');
const busses = busCodes.split(',').reduce((memo, bus, idx) => {
if (bus !== 'x') memo.push([idx, parseInt(bus)]);
return memo;
}, []);
// return 19 - (1068781 % 19);
// return busses.map(([delta, busId]) => {
// if (1068781 % busId) {
// return busId - (1068781 % busId) === delta;
// } else {
// return 1068781 % busId === delta;
// }
// });
const step = busses.reduce((best, bus) => (bus[1] > best[1] ? bus : best));
for (let i = step[1] - step[0]; i < MAX_STEPS; i += step[1]) {
// for (let i = 0; i < MAX_STEPS; i += busses[0][1]) {
if (
busses.every(([delta, busId]) => {
if (i % busId) {
return busId - (i % busId) === delta;
} else {
return i % busId === delta;
}
})
) {
return i;
}
// if (i > 1068781) throw `Too many steps: ${i}`;
}
}
Insert cell
part2(testInput)
Insert cell
part2(input)
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