Skip to content
advent of code 2018

day 07

the sum of its parts

approach

the instructions become chars, a map from each step to the steps that wait on it, and depends_on(c) scans the list for c's prerequisites. part 1 is a topological sort with alphabetical tie-breaking: a sorted list of available steps, take the first one whose prerequisites are all done, add its successors and re-sort. the final step(s), which have no successors, get appended at the end.

part 2 simulates five workers, one second per loop. free workers pick up available steps, with a countdown of ord(c) - 4 (60 seconds plus the letter's position). when a countdown hits 1 the step is done and its successors become available. it prints the state on every tick, and the last t is the answer.

the header comment reads "fix this god dammned mess!", and part 1's result is reset to [] before part 2 without being printed, so the part 1 order is only visible if you stop the script halfway.

the trick

hand out steps only when all their prerequisites are done, and give each worker a countdown equal to the step's duration.

python
	for c in stack:
		#check if character is available
		if len(depends_on(c)-set(result))==0:
			#find, if there is, available worker
			for i in range(num):
				if count[i]==0:
					#ord(c)-64+60
					count[i]=ord(c)-4
					worker[i]=c
					to_pop.append(c)
					#break loop
					break
	stack=[c for c in stack if c not in to_pop]