const{readFile}=require('./reader');const{SleepingSchedule,Guard,buildGuards}=require('./04-common');constfindZonkedGuard=guards=>{return[...guards.values()].reduce((zonkedGuard,guard)=>{if(guard.maxMinutesSlept>zonkedGuard.maxMinutesSlept){zonkedGuard=guard;}returnzonkedGuard;});};constfindMostAsleepMinute=guard=>{constminutesCount=Array.from({length:60},m=>0);for(leti=0;i<60;i++){for(letscheduleofguard.schedules){minutesCount[i]+=+(schedule.minutesSlept.indexOf(i)>-1);}}constmostAsleepMinuteCount=Math.max(...minutesCount);returnminutesCount.indexOf(mostAsleepMinuteCount);};(async()=>{constlines=awaitreadFile('04-input.txt');lines.sort();constguards=buildGuards(lines);constzonkedGuard=findZonkedGuard(guards);constmostAsleepMinute=findMostAsleepMinute(zonkedGuard);constsolution=+zonkedGuard.id*mostAsleepMinute;console.log(`The ID of the guard multiplied by the minute is ${solution}`);})();
04b.js
const{readFile}=require('./reader');const{SleepingSchedule,Guard,buildGuards}=require('./04-common');constfindMostAsleepMinute=guard=>{constminutesCount=Array.from({length:60},m=>0);for(leti=0;i<60;i++){for(letscheduleofguard.schedules){minutesCount[i]+=+(schedule.minutesSlept.indexOf(i)>-1);}}constmostAsleepMinuteCount=Math.max(...minutesCount);returnminutesCount.indexOf(mostAsleepMinuteCount);};constfindMostFrequentlySleptMinute=guards=>{constminutesMostSlept=[];// Finding the guard which slept the most minutes for every minutefor(leti=0;i<60;i++){constguardsWhichSleptThisMinute=newMap();for(letguardofguards.values()){letminutesThisGuardSlept=0;for(letscheduleofguard.schedules){minutesThisGuardSlept+=+(schedule.minutesSlept.indexOf(i)>-1);}guardsWhichSleptThisMinute.set(guard.id,minutesThisGuardSlept);}letzonkedGuardId;letmaxMinutesSlept=0;for(let[guardId,minutes]ofguardsWhichSleptThisMinute.entries()){if(minutes>maxMinutesSlept){maxMinutesSlept=minutes;zonkedGuardId=guardId;}}minutesMostSlept[i]={zonkedGuardId,maxMinutesSlept};}// Finding the guard which slept the most minutes totalletzonkedGuardIdTotal;letmaxMinutesSleptTotal=0;letminuteMostSleptTotal=-1;for(leti=0;i<60;i++){const{zonkedGuardId,maxMinutesSlept}=minutesMostSlept[i];if(maxMinutesSlept>maxMinutesSleptTotal){maxMinutesSleptTotal=maxMinutesSlept;zonkedGuardIdTotal=zonkedGuardId;minuteMostSleptTotal=i;}}return{zonkedGuardIdTotal,minuteMostSleptTotal}}(async()=>{constlines=awaitreadFile('04-input.txt');lines.sort();constguards=buildGuards(lines);const{zonkedGuardIdTotal,minuteMostSleptTotal}=findMostFrequentlySleptMinute(guards);constsolution=+zonkedGuardIdTotal*minuteMostSleptTotal;console.log(`The ID of the guard multiplied by the minute is ${solution}`);})();
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
JavaScript solution
reader.js
04-common.js
04a.js
04b.js