9.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. lines = [(line[0], int(line[2:])) for line in open("9.input")]
  2. DIR = {'R': (0, 1), 'L': (0, -1), 'U': (-1, 0), 'D': (1, 0)}
  3. #SNEK_LEN = 2 # Part 1
  4. SNEK_LEN = 10 # Part 2
  5. snek = [(0, 0) for _ in range(0, SNEK_LEN)]
  6. def add(a, b):
  7. return (a[0] + b[0], a[1] + b[1])
  8. def show_snek(snek):
  9. for x in range(-20, 20):
  10. for y in range(-20, 20):
  11. if (x, y) in snek:
  12. print("#", end='')
  13. elif (x, y) == (0, 0):
  14. print("s", end='')
  15. else:
  16. print(".", end='')
  17. print("")
  18. visited = set()
  19. visited.add(snek[-1])
  20. for direction, steps in lines:
  21. for _ in range(0, steps):
  22. # Move head
  23. snek[0] = add(snek[0], DIR[direction])
  24. # Follow with tail
  25. for head_idx in range(0, len(snek) - 1):
  26. head = snek[head_idx]
  27. tail = snek[head_idx+1]
  28. follow = [0, 0]
  29. follow[0] = head[0] - tail[0]
  30. follow[1] = head[1] - tail[1]
  31. dist = sum(map(abs, follow))
  32. if dist >= 3:
  33. follow[0] = follow[0] // abs(follow[0])
  34. follow[1] = follow[1] // abs(follow[1])
  35. elif abs(follow[0]) == 2:
  36. follow[0] = follow[0] // 2
  37. elif abs(follow[1]) == 2:
  38. follow[1] = follow[1] // 2
  39. else:
  40. follow = [0, 0]
  41. snek[head_idx+1] = add(snek[head_idx+1], follow)
  42. visited.add(snek[-1])
  43. print(len(visited))