AoC day 4

This commit is contained in:
Ben
2018-12-04 18:28:41 +00:00
parent 947bb1bd98
commit 06e6461ecb
9 changed files with 2412 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
--- Part Two ---
Strategy 2: Of all guards, which guard is most frequently asleep on the same minute?
In the example above, Guard #99 spent minute 45 asleep more than any other guard or minute - three times in total. (In all other cases, any guard spent any minute asleep at most twice.)
What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 99 * 45 = 4455.)

View File

@@ -0,0 +1,68 @@
class Guard {
constructor (id) {
this.id = id;
this.minutesAsleep = Array.from({ length: 60 }).map(() => 0);
this.fellAsleepAt = null;
}
sleep (fellAsleepAt) {
this.fellAsleepAt = fellAsleepAt;
}
awake (awokeAt) {
for (let i = this.fellAsleepAt; i < awokeAt; i++) {
this.minutesAsleep[i] += 1;
}
}
get sleepiestMinute () {
return this.minutesAsleep
.map((value, index) => ({ index, value }))
.sort((a, b) => b.value - a.value)[0].index;
}
}
const sleep = (input) => {
const guards = {};
const schedule = input
.split('\n')
.map((x) => x.trim())
.sort()
.map((x) => {
const parts = x.match(/\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})\] (.*)/);
return {
minute: +parts[5],
message: parts[6],
};
});
let currentGuard = null;
for (let i = 0; i < schedule.length; i++) {
const { message, minute } = schedule[i];
if (/Guard/.test(message)) {
const parts = message.match(/Guard #(\d+) begins shift/);
const guardId = +parts[1];
const guard = guards[guardId] ? guards[guardId] : new Guard(guardId);
currentGuard = guards[guardId] = guard;
} else if (message === 'falls asleep') {
currentGuard.sleep(minute);
} else if (message === 'wakes up') {
currentGuard.awake(minute);
}
}
const sleepiestGuard = Object
.keys(guards)
.map((guardId) => guards[guardId])
.sort((a, b) => b.minutesAsleep[b.sleepiestMinute] -
a.minutesAsleep[a.sleepiestMinute])[0];
return sleepiestGuard.id * sleepiestGuard.sleepiestMinute;
};
const fs = require('fs');
console.log(sleep(fs.readFileSync("input.txt").toString()));

File diff suppressed because it is too large Load Diff