Published
Edited
Dec 8, 2018
Insert cell
Insert cell
data = input.split('\n').sort()
Insert cell
guardStatistics = {
let guard;
let timeSleep;
let timeWake;
// total minutes asleep by guard
let guardTotals = {};
// count of times a guard is asleep during a particular minute
let guardMinutes = {};

for (const line of data) {
const num = Number(line.match(/\d+/g).pop());
if (line.includes('Guard')) {
guard = num;
} else if (line.includes('falls asleep')) {
timeSleep = num;
} else {
timeWake = num;
guardTotals[guard] = (guardTotals[guard] || 0) + (timeWake - timeSleep);
guardMinutes[guard] = (guardMinutes[guard] || new Array(60).fill(0));
for (let i = timeSleep; i < timeWake; i++) {
guardMinutes[guard][i] += 1;
}
}
}
return [guardTotals, guardMinutes];
}
Insert cell
Insert cell
Insert cell
Insert cell
sleepiestGuard = Number(Object.entries(guardTotals)
.reduce((a, b) => a[1] > b[1] ? a : b)[0])
Insert cell
part1Minute = Number(Object.entries(guardMinutes[sleepiestGuard])
.reduce((a, b) => a[1] > b[1] ? a : b)[0])
Insert cell
sleepiestGuard * part1Minute
Insert cell
Insert cell
mostConsistentGuard = Number(Object.entries(guardMinutes)
.map(x => [x[0], Math.max(...x[1])])
.reduce((a, b) => a[1] > b[1] ? a : b)[0])
Insert cell
part2Minute = Number(Object.entries(guardMinutes[mostConsistentGuard])
.reduce((a, b) => a[1] > b[1] ? a : b)[0])
Insert cell
mostConsistentGuard * part2Minute
Insert cell
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