Working out solutions for Advent of Code
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

03a.py 1.5KB

5 år sedan
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. for path in paths[i+1]:
  17. d, v = path[0], int(path[1:])
  18. if d == "U":
  19. dir = 1
  20. inc = 1
  21. elif d == "D":
  22. dir = 1
  23. inc = -1
  24. elif d == "R":
  25. dir = 0
  26. inc = 1
  27. else:
  28. dir = 0
  29. inc = -1
  30. for _ in range(v):
  31. a, b = pos
  32. if dir == 0:
  33. a += inc
  34. else:
  35. b += inc
  36. pos = (a,b)
  37. if pos not in grid:
  38. grid[pos] = [0,0]
  39. grid[pos][i] = 1
  40. dists = []
  41. for k,v in grid.items():
  42. if v == [1,1] and k != (0,0):
  43. dists.append(abs(k[0]) + abs(k[1]))
  44. print(dists)
  45. print(min(dists))
  46. if __name__ == "__main__":
  47. main(False)