Advertisement
nein_yards

day 3 advent of code 2019

Dec 5th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. def path_to_coordinates(wire_path):
  2. wire_coordinates = []
  3. direction_to_sign = {'U': 1, 'D': -1, 'L': -1, 'R': 1}
  4. x, y = 0, 0
  5. steps = 0
  6.  
  7. for move in wire_path:
  8. direction = move[0]
  9. magnitude = int(move[1:])
  10. sign = direction_to_sign[direction]
  11.  
  12. if direction == 'L' or direction == 'R':
  13. x_change, y_change = sign, 0
  14. elif direction == 'U' or direction == 'D':
  15. x_change, y_change = 0, sign
  16. steps += magnitude
  17. for i in range(magnitude):
  18. x += x_change
  19. y += y_change
  20. wire_coordinates.append((x, y))
  21. return wire_coordinates, list(range(1, steps + 1))
  22.  
  23. def manhattan_distance(coord):
  24. return abs(coord[0]) + abs(coord[1])
  25.  
  26. def combined_steps(coord):
  27. step_count_1 = min([packed[1] for packed in zipped_1 if coord == packed[0]])
  28. step_count_2 = min([packed[1] for packed in zipped_2 if coord == packed[0]])
  29. return step_count_1 + step_count_2
  30.  
  31.  
  32. with open('day3.txt', 'r') as f:
  33. wire_path_1, wire_path_2 = map(lambda line: line.split(','), f.read().split())
  34.  
  35. wire_coordinates_1, steps_1 = path_to_coordinates(wire_path_1)
  36. wire_coordinates_2, steps_2 = path_to_coordinates(wire_path_2)
  37.  
  38. zipped_1 = list(list(zip(wire_coordinates_1, steps_1)))
  39. zipped_2 = list(list(zip(wire_coordinates_2, steps_2)))
  40.  
  41. intersections = set(wire_coordinates_1) & set(wire_coordinates_2)
  42.  
  43. print('Part 1: ' + str(min(map(manhattan_distance, intersections))))
  44. print('Part 2: ' + str(min(map(combined_steps, intersections))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement