Skip to content

Instantly share code, notes, and snippets.

@synio-wesley
Created December 4, 2018 11:24
Show Gist options
  • Save synio-wesley/10087748d38b09c195d95d9b085eecc1 to your computer and use it in GitHub Desktop.
Save synio-wesley/10087748d38b09c195d95d9b085eecc1 to your computer and use it in GitHub Desktop.
AOC 2018 - Day 4 - Python
# Prepare and sort data
data = [line.strip() for line in open('day4.txt')]
data.sort(key=lambda x: x.split(']')[0])
# Part 1
sleepingGuards = {}
currentGuard = None
asleepFrom = None
for line in data:
date, time, keyword, guard = line.split(' ')[:4]
if keyword == 'Guard':
currentGuard = int(guard[1:])
elif keyword == 'falls':
asleepFrom = int(time[3:5])
elif keyword == 'wakes':
if currentGuard not in sleepingGuards:
sleepingGuards[currentGuard] = {}
for i in range(asleepFrom, int(time[3:5])):
if i not in sleepingGuards[currentGuard]:
sleepingGuards[currentGuard][i] = 0
sleepingGuards[currentGuard][i] += 1
asleepFrom = None
asleepTimes = {guard: sum(minutes.values()) for guard, minutes in sleepingGuards.items()}
asleepMost = {guard: max(minutes, key=minutes.get) for guard, minutes in sleepingGuards.items()}
mostAsleepGuard = max(asleepTimes, key=asleepTimes.get)
print(int(mostAsleepGuard * asleepMost[mostAsleepGuard]))
# Part 2
asleepMostOnSameMinute = {guard: max(minutes.values()) for guard, minutes in sleepingGuards.items()}
mostAsleepGuard = max(asleepMostOnSameMinute, key=asleepMostOnSameMinute.get)
mostAsleepMinute = {guard: max(minutes, key=minutes.get) for guard, minutes in sleepingGuards.items()}
print(int(mostAsleepGuard * mostAsleepMinute[mostAsleepGuard]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment