Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. """Advent of Code 2016 day 1 solutions"""
  2.  
  3.  
  4. import re
  5.  
  6.  
  7. NORTH = (0, 1)
  8. EXAMPLE_STEPS = [('R', 8), ('R', 4), ('R', 4), ('R', 8)]
  9.  
  10.  
  11. def turn(direction, side):
  12. """
  13. Turns direction vector left or right by 90 degrees
  14.  
  15. >>> turn(NORTH, 'L')
  16. (-1, 0)
  17. >>> turn(NORTH, 'R')
  18. (1, 0)
  19. """
  20.  
  21. d_x, d_y = direction
  22. if side == 'L':
  23. return -d_y, d_x
  24. elif side == 'R':
  25. return d_y, -d_x
  26. else:
  27. raise ValueError('Invalid side: %s' % side)
  28.  
  29.  
  30. def teleport(steps):
  31. """
  32. The last coordinates of Santa
  33.  
  34. >>> teleport(EXAMPLE_STEPS)
  35. (4, 4)
  36. """
  37.  
  38. coords = (0, 0)
  39. direction = NORTH
  40. for (side, distance) in steps:
  41. direction = turn(direction, side)
  42. c_x, c_y = coords
  43. d_x, d_y = direction
  44. coords = (c_x + d_x * distance, c_y + d_y * distance)
  45. return coords
  46.  
  47.  
  48. def walk(steps):
  49. """
  50. The path of Santa
  51.  
  52. >>> steps = [('R', 2), ('L', 2)]
  53. >>> list(walk(steps))
  54. [(1, 0), (2, 0), (2, 1), (2, 2)]
  55. """
  56.  
  57. coords = (0, 0)
  58. direction = NORTH
  59. for (side, distance) in steps:
  60. direction = turn(direction, side)
  61. for _ in range(distance):
  62. c_x, c_y = coords
  63. d_x, d_y = direction
  64. coords = (c_x + d_x, c_y + d_y)
  65. yield coords
  66.  
  67.  
  68. def find_first_duplicate(iteratable):
  69. """
  70. Finds the first duplicate in iteratable
  71.  
  72. >>> find_first_duplicate([0, 1, 2, 1, 2])
  73. 1
  74. """
  75.  
  76. visited = set()
  77. for elem in iteratable:
  78. if elem in visited:
  79. return elem
  80. visited.add(elem)
  81.  
  82.  
  83. def manhattan_distance_from_origin(coords):
  84. """
  85. Manhattan's distance to (0, 0)
  86.  
  87. >>> manhattan_distance_from_origin((4, -4))
  88. 8
  89. """
  90.  
  91. c_x, c_y = coords
  92. return abs(c_x) + abs(c_y)
  93.  
  94.  
  95. def main():
  96. """Main function"""
  97. with open('input.txt', 'r') as handle:
  98. pattern = r'([RL])(\d+)'
  99. matches = re.findall(pattern, handle.read())
  100. steps = [(side, int(distance)) for (side, distance) in matches]
  101.  
  102. part1 = teleport(steps)
  103. print('Part 1:', manhattan_distance_from_origin(part1))
  104.  
  105. path = walk(steps)
  106. part2 = find_first_duplicate(path)
  107. print('Part 2:', manhattan_distance_from_origin(part2))
  108.  
  109.  
  110. if __name__ == '__main__':
  111. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement