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!

36 Upvotes

340 comments sorted by

View all comments

2

u/cluk Dec 04 '18

I am learning Python this year. I really wanted to use built-in max, tuples for the win! I would appreciate any tips.

import re

with open('input_04.txt') as f:
	lines = f.read().splitlines()

guards = {}
id = 0
falls = 0
for line in sorted(lines):	
	if 'Guard' in line:
		id = int(re.findall('#(\d+)', line)[0])
		if id not in guards:
			guards[id] = [0] * 59
		continue
	minute = int(re.findall(':(\d+)\]', line)[0])
	if 'falls asleep' in line:
		falls = minute
	else:
		for m in range(falls, minute):
			guards[id][m] += 1

def star1(guards):
	_, guard_id = max((sum(minutes), guard) for (guard, minutes) in guards.items())
	_, chosen_minute = max((m, idx) for (idx, m) in enumerate(guards[guard_id]))
	return guard_id * chosen_minute

def star2(guards):	
	_, chosen_minute, guard_id = max((minute, idx, guard) for (guard, minutes) in guards.items() for (idx, minute) in enumerate(minutes))
	return guard_id * chosen_minute

print("Star 1:", star1(guards))
print("Star 2:", star2(guards))