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/siwica Dec 05 '18

My Python 3 solution for both parts:

import re
from collections import defaultdict
from datetime import datetime, timedelta


def date(line):
    return datetime.strptime(line[6:17], '%m-%d %H:%M')


with open("input.txt") as f:
    lines = sorted(f.readlines(), key=date)

sleep_times = defaultdict(lambda: [0]*60)
for line in lines:
    if 'Guard' in line:
        current_guard = int(re.search(r'#(\d+)', line).group(1))
    elif 'falls asleep' in line:
        sleep_start = date(line)
    elif 'wakes up' in line:
        sleep_end = date(line)
        while sleep_start < sleep_end:
            sleep_times[current_guard][sleep_start.minute] += 1
            sleep_start += timedelta(minutes=1)

for part, f in enumerate([sum, max], 1):
    guard_nr, minute = max(sleep_times.items(), key=lambda x: f(x[1]))
    minute_nr = minute.index(max(minute))
    print('Part {}: {}'.format(part, guard_nr * minute_nr))