solution.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/python3
  2. import sys
  3. from dataclasses import dataclass
  4. @dataclass
  5. class Pos:
  6. x: int
  7. y: int
  8. def move(self, pos):
  9. self.x += pos.x
  10. self.y += pos.y
  11. def behind(self, pos):
  12. if abs(self.x - pos.x) <= 1 and abs(self.y - pos.y) <= 1:
  13. return
  14. elif abs(self.x - pos.x) > 1 and abs(self.y - pos.y) > 1:
  15. x_sign = 1 if self.x - pos.x > 1 else -1
  16. y_sign = 1 if self.y - pos.y > 1 else -1
  17. self.x = pos.x + x_sign
  18. self.y = pos.y + y_sign
  19. elif abs(self.x - pos.x) > 1:
  20. sign = 1 if self.x - pos.x > 1 else -1
  21. self.y = pos.y
  22. self.x = pos.x + sign
  23. elif abs(self.y - pos.y) > 1:
  24. sign = 1 if self.y - pos.y > 1 else -1
  25. self.x = pos.x
  26. self.y = pos.y + sign
  27. def as_struct(self):
  28. return (self.x, self.y)
  29. # part 1
  30. directions = { 'U': Pos(0, 1), 'D': Pos(0, -1), 'L': Pos(-1, 0), 'R': Pos(1, 0) }
  31. def visualize(visited, max_width=180):
  32. y_s = [y for x, y in visited]
  33. y_start, y_end = min(y_s), max(y_s)
  34. x_s = [x for x, y in visited]
  35. x_start, x_end = min(x_s), max(x_s)
  36. for y in range(y_start, y_end + 1)[::-1]:
  37. for x in range(x_start, min(x_start + max_width, x_end) + 1):
  38. print('#' if (x, y) in visited else '.', end='')
  39. print()
  40. def count_positions(visited):
  41. return len(visited)
  42. def solution(n):
  43. head = Pos(0, 0)
  44. tails = [Pos(0, 0) for i in range(n)]
  45. visited = set()
  46. for line in sys.stdin:
  47. s = line.strip().split(' ')
  48. direction, count = s[0], int(s[1])
  49. for i in range(count):
  50. head.move(directions[direction])
  51. tails[0].behind(head)
  52. for i in range(1, n):
  53. tails[i].behind(tails[i - 1])
  54. if tails[-1].as_struct() not in visited:
  55. visited.add(tails[-1].as_struct())
  56. #print(head, tails)
  57. #print(sorted(visited))
  58. visualize(visited)
  59. print(f'{count_positions(visited)} visited')
  60. if sys.argv[1] in '1':
  61. solution(1)
  62. else:
  63. solution(9)