From 7a4646001cfaa8d4c2207fc377f323e7d0928c81 Mon Sep 17 00:00:00 2001 From: Tom van der Lee Date: Wed, 5 Dec 2018 07:39:54 +0100 Subject: More day4 --- 2018/aoc/day4.py | 26 ++++++++++++++++++++------ 2018/inputs/example.txt | 17 +++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 2018/inputs/example.txt diff --git a/2018/aoc/day4.py b/2018/aoc/day4.py index c0aad81..d0b6b74 100644 --- a/2018/aoc/day4.py +++ b/2018/aoc/day4.py @@ -1,14 +1,18 @@ import re +from collections import Counter from datetime import datetime +from functools import reduce timestamp_pattern = re.compile(r'\[(?P.+)\]') guard_pattern = re.compile(r'#(?P[0-9]+)') + def parse_shifts(shift_list: list) -> iter: shift = None felt_asleep = None for item in shift_list: + print(item) timestamp = datetime.strptime( timestamp_pattern \ .search(item) \ @@ -22,18 +26,28 @@ def parse_shifts(shift_list: list) -> iter: yield shift shift = { 'start': timestamp, - 'guard': guard_pattern.search(item).groupdict().get('id'), - 'sleepytime': 0 + 'guard': int(guard_pattern.search(item).groupdict().get('id')), + 'sleepytime': 0, + 'sleepy_minutes': [] } elif item.endswith('asleep'): felt_asleep = timestamp elif item.endswith('up'): - shift['sleepytime'] += int((timestamp - felt_asleep).seconds / 60) + shift['sleepy_minutes'] += list(range(felt_asleep.minute, timestamp.minute)) + shift['sleepytime'] += timestamp.minute - felt_asleep.minute felt_asleep = None +def main(input_file: list): + shifts = list(parse_shifts(sorted(input_file))) + shifts.sort(key=lambda s: s['sleepytime'], reverse=True) + most_sleepy_guard = shifts[0]['guard'] + minutes_slept = reduce(lambda m, s: m + ( + s['sleepy_minutes'] if s['guard'] == most_sleepy_guard else [] + ), shifts, []) + minutes_slept_most = Counter(minutes_slept).most_common() + print(minutes_slept_most) + + print(f'Guard {most_sleepy_guard} slept at minute {minutes_slept_most[0][0]}: {most_sleepy_guard * (minutes_slept_most[0][0] + 1)}') -def main(input_file: list): - for shift in parse_shifts(sorted(input_file)): - print(shift) diff --git a/2018/inputs/example.txt b/2018/inputs/example.txt new file mode 100644 index 0000000..62c3a7a --- /dev/null +++ b/2018/inputs/example.txt @@ -0,0 +1,17 @@ +[1518-11-01 00:00] Guard #10 begins shift +[1518-11-01 00:05] falls asleep +[1518-11-01 00:25] wakes up +[1518-11-01 00:30] falls asleep +[1518-11-01 00:55] wakes up +[1518-11-01 23:58] Guard #99 begins shift +[1518-11-02 00:40] falls asleep +[1518-11-02 00:50] wakes up +[1518-11-03 00:05] Guard #10 begins shift +[1518-11-03 00:24] falls asleep +[1518-11-03 00:29] wakes up +[1518-11-04 00:02] Guard #99 begins shift +[1518-11-04 00:36] falls asleep +[1518-11-04 00:46] wakes up +[1518-11-05 00:03] Guard #99 begins shift +[1518-11-05 00:45] falls asleep +[1518-11-05 00:55] wakes up \ No newline at end of file -- cgit v1.2.3