13_minecarts.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python3
  2. import sys
  3. dirs = {'<': (0, -1), '>': (0, 1), '^': (-1, 0), 'v': (1, 0)}
  4. LEFT, STRAIGHT, RIGHT = 0, 1, 2
  5. tracks = ''
  6. carts = []
  7. for y, line in enumerate(sys.stdin):
  8. for x, c in enumerate(line):
  9. if c in '<^>v':
  10. carts.append((y, x, *dirs[c], LEFT))
  11. tracks += '-' if c in '<>' else '|'
  12. else:
  13. tracks += c
  14. h = y + 1
  15. w = len(tracks) // h
  16. firstcrash = None
  17. while len(carts) > 1:
  18. crashed = set()
  19. for i, (y, x, dy, dx, nextturn) in enumerate(carts):
  20. y += dy
  21. x += dx
  22. track = tracks[y * w + x]
  23. for j, c in enumerate(carts):
  24. if c[:2] == (y, x):
  25. if firstcrash is None:
  26. firstcrash = x, y
  27. crashed.add(i)
  28. crashed.add(j)
  29. if track == '\\':
  30. turn = LEFT if dy else RIGHT
  31. elif track == '/':
  32. turn = RIGHT if dy else LEFT
  33. elif track == '+':
  34. turn = nextturn
  35. nextturn = (nextturn + 1) % 3
  36. else:
  37. turn = STRAIGHT
  38. if turn == LEFT:
  39. dy, dx = -dx, dy
  40. elif turn == RIGHT:
  41. dy, dx = dx, -dy
  42. carts[i] = y, x, dy, dx, nextturn
  43. carts = sorted(c for i, c in enumerate(carts) if i not in crashed)
  44. print(*firstcrash, sep=',')
  45. y, x = carts[0][:2]
  46. print(x, y, sep=',')