r/adventofcode • • Dec 04 '18

SOLUTION MEGATHREAD -πŸŽ„- 2018 Day 4 Solutions -πŸŽ„-

--- Day 4: Repose Record ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 4

Transcript:

Today’s puzzle would have been a lot easier if my language supported ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

38 Upvotes

340 comments sorted by

View all comments

1

u/hayden592 Dec 05 '18

Javascript runs in the browser. Having a little trouble with part 2

input = document.querySelector('pre').textContent.split('\n');
//remove last empty string
input.pop();

input.sort((a,b) => new Date(a.match(/(\d+.*\:\d+)/g)[0]) - new Date(b.match(/(\d+.*\:\d+)/g)[0]))

parseLog = (log) => (log.match(/(\d+.*\:\d+)|(\d+|falls|wakes)/g));
isGuard = (action) => (action.match(/\d+/g));
getMins = (nap) => (nap.split(':')[1]);

currentGuard;
sleepiest;
sleepStudy = input.reduce((a, c)=> {
  parsed = parseLog(c);
  if (isGuard(parsed[1])) { 
    currentGuard = parsed[1];
    if(!a[currentGuard]) {
      a[currentGuard] = { totalSleep: 0, timeSleptAtMinute: new Array(60).fill(0), naps: [] };
    }
  } else {
    if (a[currentGuard].naps.length === 1) {
      end = getMins(parsed[0]);
      start = getMins(a[currentGuard].naps.pop());
      a[currentGuard].totalSleep += end-start;
      // i think there is a problem in here preventing me from solving part2
      for(i=start; i<end; i++){
        a[currentGuard].timeSleptAtMinute[i]++;
      }
      if (!a[sleepiest]) {
        sleepiest = currentGuard;
      }
      sleepiest = ( a[currentGuard].totalSleep >= a[sleepiest].totalSleep) ? currentGuard : sleepiest;
    } else {
      a[currentGuard].naps.push(parsed[0]);
    }
  }
  return a;
}, {});


console.log('part1', sleepiest* sleepStudy[sleepiest].timeSleptAtMinute.indexOf(Math.max(...sleepStudy[sleepiest].timeSleptAtMinute)));

// this should work
part2 = Object.keys(sleepStudy).reduce((a, c) => {
  guard = c;
  minutes = Math.max(...sleepStudy[c].timeSleptAtMinute);
  index = sleepStudy[c].timeSleptAtMinute.indexOf(minutes);
  return (minutes >= a.minutes) ? {guard, minutes, index } : a;
}, {guard: '', minutes: 0, index: 0})
console.log('part2', part2.guard * part2.index)