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

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