14.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. lines = [line.strip() for line in open("14.input")]
  2. rocks = set()
  3. for line in lines:
  4. coords = line.split(" -> ")
  5. for i in range(0, len(coords) - 1):
  6. start = list(map(int, coords[i].split(",")))
  7. end = list(map(int, coords[i+1].split(",")))
  8. if start[0] == end[0]:
  9. for y in range(min(start[1], end[1]), max(start[1], end[1]) + 1):
  10. rocks.add((start[0], y))
  11. else:
  12. for x in range(min(start[0], end[0]), max(start[0], end[0]) + 1):
  13. rocks.add((x, start[1]))
  14. def draw_grid(rocks, sands):
  15. obst = rocks.union(sands)
  16. min_x = min(o[0] for o in sands)
  17. max_x = max(o[0] for o in sands)
  18. max_y = max(o[1] for o in obst)
  19. for y in range(0, max_y+1):
  20. for x in range(min_x, max_x):
  21. if (x, y) in rocks:
  22. print("#", end="")
  23. elif (x, y) in sands:
  24. print("o", end="")
  25. else:
  26. print(".", end="")
  27. print("")
  28. def step(rocks, sands, bottom):
  29. obst = rocks.union(sands)
  30. sand = (500, 0)
  31. if sand in sands:
  32. return sands
  33. while True:
  34. if sand[1] > bottom:
  35. return sands
  36. targets = [
  37. (sand[0], sand[1] + 1),
  38. (sand[0] - 1, sand[1] + 1),
  39. (sand[0] + 1, sand[1] + 1),
  40. ]
  41. for t in targets:
  42. if t not in obst:
  43. sand = t
  44. break
  45. else:
  46. break
  47. sands.add(sand)
  48. return sands
  49. def part1():
  50. sands = set()
  51. bottom = max(r[1] for r in rocks)
  52. while True:
  53. l = len(sands)
  54. sands = step(rocks, sands, bottom)
  55. if l == len(sands):
  56. break
  57. print(len(sands))
  58. part1()
  59. def part2():
  60. sands = set()
  61. bottom = max(r[1] for r in rocks) + 2
  62. for x in range(-1000, 1000):
  63. rocks.add((x, bottom))
  64. while True:
  65. l = len(sands)
  66. sands = step(rocks, sands, bottom)
  67. if l == len(sands):
  68. break
  69. print(len(sands))
  70. part2()