Created
December 5, 2018 20:51
-
-
Save morenoh149/df0bf5d902c8cc51ce4a5e3370f8c88c to your computer and use it in GitHub Desktop.
Advent of Code 2018 Day 4 solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import pprint | |
pp = pprint.PrettyPrinter(indent=2) | |
def Input(): | |
filename = './input.txt' | |
return open(filename) | |
lines = Input().read().split('\n') | |
# group lines by shift | |
shifts = [] | |
shift = [] | |
for line in lines: | |
if 'Guard #' in line: | |
if shift: | |
shifts.append(shift) | |
shift = [] | |
shift.append(line) | |
else: | |
shift.append(line) | |
shifts.append(shift) | |
# group shifts by elf | |
elfs = {} | |
for shift in shifts: | |
elfId = re.search('#\d+', shift[0]).group(0) | |
if elfId in elfs.keys(): | |
elfs[elfId].append(shift) | |
else: | |
elfs[elfId] = [shift] | |
# find sleepiest elf | |
sleepTotals = {} | |
for elfId in elfs: | |
elf = elfs[elfId] | |
for shift in elf: | |
sleepSum = 0 | |
#sleepBegin = 0 | |
for line in shift: | |
if 'asleep' in line: | |
sleepBegin = int(re.search(':\d+', line).group(0)[1:]) | |
if 'wake' in line: | |
sleepEnd = int(re.search(':\d+', line).group(0)[1:]) | |
sleepSum += sleepEnd - sleepBegin | |
if elfId in sleepTotals.keys(): | |
sleepTotals[elfId] += sleepSum | |
else: | |
sleepTotals[elfId] = sleepSum | |
# elf 1993 is sleepiest | |
# determine sleepiest minute | |
sleepiest = elfs['#1993'] | |
minutes = [0 for i in range(60)] | |
for shift in sleepiest: | |
for line in shift: | |
if 'asleep' in line: | |
sleepBegin = int(re.search(':\d+', line).group(0)[1:]) | |
if 'wake' in line: | |
sleepEnd = int(re.search(':\d+', line).group(0)[1:]) | |
for i in range(sleepBegin, sleepEnd + 1): | |
minutes[i] += 1 | |
sleepiestMinCount = max(minutes) | |
sleepiestMin = 0 | |
for i in range(len(minutes)): | |
if minutes[i] == sleepiestMinCount: | |
print('sleepiest min {}'.format(i)) | |
sleepiestMin = i | |
print('answer is {}'.format(1993 * sleepiestMin)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment