Published
Edited
Nov 13, 2019
3 stars
Insert cell
Insert cell
part1 = 521 * 24
Insert cell
part2 = 2969 * 47
Insert cell
Insert cell
rows = _.flatten(_.map(table, (minutes, guard) => {
return _.range(0, 60).map(minute => ({ guard, minute, count: minutes[minute] }))
}))
Insert cell
table = _.reduce(_.groupBy(spans, 'guard'), (table, spans, guard) => {
const minutes = table[guard] = table[guard] || []
for (let span of spans) {
for (let i = span.sleep; i < span.wake; i++) {
minutes[i] = (minutes[i] || 0) + 1
}
}
return table
}, {})
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
spans = _.flatten(shifts.map(logs => {
let fellAsleep = null
const spans = []
for (let log of logs) {
if (log.sleep) {
fellAsleep = log
} else {
if (fellAsleep) {
spans.push({ guard: log.guard, sleep: fellAsleep.minute, wake: log.minute })
fellAsleep = null
}
}
}
return spans
}))
Insert cell
shifts = {
const shifts = []
let guard = null
for (let log of logs) {
if (log.guard !== guard) {
shifts.unshift([])
guard = log.guard
}
shifts[0].push(log)
}
return shifts
}
Insert cell
logs = {
let guard = null
return lines.map(line => {
const [ time ] = line.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/)
guard = line.match(/Guard #(\d+)/) || guard
return {
time,
minute: +time.match(/:(\d{2})/)[1],
guard: guard[1],
sleep: !!line.match(/sleep/)
}
})
}
Insert cell
lines = input.split('\n').filter(n => n).sort()
Insert cell
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