Skip to content

Instantly share code, notes, and snippets.

@Dalecarlia
Last active December 8, 2018 17:44
Show Gist options
  • Save Dalecarlia/336127dc858e8896ca9249f21cd04528 to your computer and use it in GitHub Desktop.
Save Dalecarlia/336127dc858e8896ca9249f21cd04528 to your computer and use it in GitHub Desktop.
var fs = require('fs'),
path = require('path'),
input = path.join(__dirname, 'input.txt');
fs.readFile(input, {encoding: 'utf-8'}, function(err, data) {
findSleepyGuard(data.split('\r\n'));
});
var guardWhoSleepsMost;
var mostSlept = 0;
var mostSleptMinute = -1
function findSleepyGuard(arr) {
var sortedArray = arr.sort();
var guards = new Map();
var currentGuard;
sortedArray.forEach(entry => {
if(entry[25] == "#") {
currentGuard = entry.substr(26,4).trim()
}
if(entry[19] == 'f' || entry[19] == 'w') {
var list = [];
if(guards.has(currentGuard)) {
list = list.concat(guards.get(currentGuard));
}
list.push(entry.substr(15,2));
guards.set(currentGuard, list);
}
});
findGuardWhoSleepsMost(guards);
console.log("Guard " + guardWhoSleepsMost + " slept the most with " + mostSlept + " minutes, where the most slept minute was " + mostSleptMinute + " And the answer is " + mostSleptMinute*parseInt(guardWhoSleepsMost));
}
function findGuardWhoSleepsMost(guardMap) {
guardMap.forEach((value, key) => {
var timeSlept = 0;
var sleepMinutes = [];
for(var i = 0; i < value.length; i += 2) {
timeSlept += value[i+1] - 1 - value[i];
for(var j = value[i]; j < value[i+1] - 1; j++) {
if(!sleepMinutes[j])
sleepMinutes[j] = 0;
sleepMinutes[j]++;
}
}
if(timeSlept >= mostSlept) {
mostSlept = timeSlept;
guardWhoSleepsMost = key;
mostSleptMinute = max(sleepMinutes);
}
});
}
function max(arr) {
var res = 0;
var minute = -1;
for(var i = 0; i < arr.length; i++) {
if(!arr[i]) continue;
if(arr[i] > res) {
res = arr[i];
minute = i;
}
}
return minute;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment