r/adventofcode • • Dec 13 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 13 Solutions -๐ŸŽ„-

--- Day 13: Packet Scanners ---


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.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


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!

16 Upvotes

199 comments sorted by

View all comments

2

u/vash3r Dec 13 '17

Python 2 (58/227):

d = eval("{"+data.strip().replace('\n',',')+"}")
delay = 0
while 1:
	tot_sev = 0
	was_caught = 0

	for depth in d.keys():
		if (depth+delay)%(d[depth]*2-2)==0:
			sev = depth*d[depth]
			tot_sev += sev
			was_caught = 1
	if delay==0:
		print tot_sev    #part 1
	if not was_caught:
		break
	delay+=1
print delay      #part 2

I also had to think about a more efficient solution to get part 2, especially since I wasn't expecting such a large delay.

3

u/vash3r Dec 13 '17

A much faster solution for part 2, by calculating the possible residues modulo the LCM of all periods of the security scanners:

from collections import defaultdict

# d is {depth:range}, eg:
d = eval("{"+data.strip().replace('\n',',')+"}")

neq = defaultdict(list) # of the form {b:[a1,a2...]} where delay != a_i (mod b)
for depth in d.keys():
	neq[d[depth]*2-2] +=  [(-depth)%(d[depth]*2-2)]
moduli = sorted(neq.keys())

prev_lcm=1
lcm = 1
residues = [0] #mod 1
for m in moduli:
	g = gcd(m,lcm) # simple Euclidean algorithm
	prev_lcm = lcm
	lcm = lcm*m/g  #new modulus
	residues = [x for x in
		sum([range(i,lcm,prev_lcm) for i in residues],[])
		if x%m not in neq[m]]

print sorted(residues)[0], "(mod",lcm,")" # the smallest residue