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/NabrenX Dec 04 '18

Still kind of new at Python, so any feedback is appreciated:

import re

with open("advent4_input.txt") as input_file:
  input = input_file.read()

compiled_re = re.compile(r'\[([0-9]+)-([0-9]+)-([0-9]+) ([0-9]+):([0-9]+)\] (.*)')
guard_re = re.compile(r'Guard #([0-9]+) begins shift')
parsed_lines = sorted([(int(year), int(month), int(day), int(hour), int(minute), action) for (year, month, day, hour, minute, action) in compiled_re.findall(input)])

guard_data = {}

for (year, month, day, hour, minute, action) in parsed_lines:
  if action == 'falls asleep':
    asleep_time = minute
  elif action == 'wakes up':
    awake_time = minute
    for i in xrange(asleep_time, awake_time):
      current_guard[i] += 1
  else:
    guard_id = int(guard_re.match(action).group(1))
    current_guard = guard_data.get(guard_id)

    if current_guard == None:
      current_guard = [0] * 60
      guard_data[guard_id] = current_guard

best_guard = max(guard_data.iteritems(), key=lambda guard: sum(guard[1]))
best_hour = max(xrange(60), key=best_guard[1].__getitem__)
print 'Part one result: Guard {0} for hour {1} = {2} '.format(best_guard[0], best_hour, best_guard[0] * best_hour)

best_guard = max(guard_data.iteritems(), key=lambda guard: max(guard[1]))
best_hour = max(xrange(60), key=best_guard[1].__getitem__)
print 'Part two result: Guard {0} for hour {1} = {2} '.format(best_guard[0], best_hour, best_guard[0] * best_hour)