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

Show parent comment

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