Working out solutions for Advent of Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

03b.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Python 3.7
  2. def main(debug):
  3. paths = {}
  4. if debug:
  5. #paths = {1: ["R75","D30","R83","U83","L12","D49","R71","U7","L72"],
  6. # 2: ["U62","R66","U55","R34","D71","R55","D58","R83"]}
  7. paths = {1: ["R98","U47","R26","D63","R33","U87","L62","D20","R33","U53","R51"],
  8. 2: ["U98","R91","D20","R16","D67","R40","U7","R15","U6","R7"]}
  9. else:
  10. with open("03in.txt","r") as file:
  11. for i in range(2): # there are only two lines
  12. paths[i+1] = file.readline().strip("\n").split(",")
  13. grid = {}
  14. for i in range(2):
  15. pos = (0,0)
  16. steps = 0
  17. for path in paths[i+1]:
  18. d, v = path[0], int(path[1:])
  19. if d == "U":
  20. dir = 1
  21. inc = 1
  22. elif d == "D":
  23. dir = 1
  24. inc = -1
  25. elif d == "R":
  26. dir = 0
  27. inc = 1
  28. else:
  29. dir = 0
  30. inc = -1
  31. for _ in range(v):
  32. steps += 1
  33. a, b = pos
  34. if dir == 0:
  35. a += inc
  36. else:
  37. b += inc
  38. pos = (a,b)
  39. if pos not in grid:
  40. grid[pos] = [0,0]
  41. if grid[pos][i] == 0:
  42. grid[pos][i] = steps
  43. dists = []
  44. for k,v in grid.items():
  45. if v[0] != 0 and v[1] != 0 and k != (0,0):
  46. dists.append(abs(v[0]) + abs(v[1]))
  47. print(sorted(dists))
  48. print(min(dists))
  49. if __name__ == "__main__":
  50. main(False)