Skip to content
advent of code 2018

day 13

mine cart madness

approach

the long comment at the top works out the encoding: directions are numbers (< 0, ^ 1, > 2, v 3), so turning right is +1 mod 4 and left is -1 mod 4. carts are dicts with a direction, a location and an intersection counter. the counter mod 3 decides left, straight or right at each +. the carts are stripped from the map, leaving plain track.

tick sorts the carts into reading order, moves each one in turn and prints a location whenever two carts share one.

only part 1 exists, and there's no driver loop: tick is meant to be called by hand until the first crash prints. carts get an ok flag on collision but are never removed, which part 2 would need.

the trick

encode directions as 0–3 so the curves and the left/straight/right cycle are all arithmetic mod 4.

python
def tick():
	carts.sort(key=lambda x:x['location'])
	for cart in carts:
		step(cart)
		for other in carts:
			if crash(cart,other):
				cart['ok']=other['ok']=False
				print('crash reported in '+str(cart['location'][1])+','+str(cart['location'][0]) )