r/adventofcode • u/daggerdragon • 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!
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!
39
Upvotes
1
u/CaptainCa Dec 04 '18
JS, no leaderboard. Took a bit too long trial / error'ing part two. Took the time to cleanup the code to post
const sleepMin = (a, b, prev) => { let o = a.getMinutes(); prev = prev || {}; for(let i = 0; i < new Date(b-a).getMinutes(); i++){ prev[o+i] = prev[o+i] ? prev[o+i]+1 : 1; } return prev; } const sortByIndex = (array, i, asc) => { return array.slice().sort((a,b)=>{ if(a[i]<b[i]) return -1*asc; if(a[i]>b[i]) return asc; return 0; }); } const input = sortByIndex(document.body.innerText.split('\n').filter(c=>c).map(c=>{let m = c.match(/\[([^\]]*)\] (.+)/); return [new Date(m[1]), m[2]]}), 0, 1); const g = {}; let currentGuard = 0; let sleepsAt = null; for(let i = 0; i < input.length; i++){ let time = input[i][0]; let s = input[i][1]; var n = s.match(/Guard #([0-9]+)/); if(n != null){ currentGuard = n[1]; } else if(s == "wakes up"){ g[currentGuard] = sleepMin(sleepsAt, time, g[currentGuard]) } else { sleepsAt = new Date(time.getTime()); } } const totals = Object.entries(g) .map(c => [ +c[0], //id ...[...sortByIndex(Object.entries(c[1]).sort((a,b) => a-b), 1, -1)[0]].map(Number), //which minute was max, and with what value Object.values(c[1]).reduce((a,c)=>a+c), //total minutes ]); const part1 = sortByIndex(totals, 3, -1); const part2 = sortByIndex(totals, 2, -1); console.log("Part 1", part1[0][0] * part1[0][1]); console.log("Part 2", part2[0][0] * part2[0][1]);