solution.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/usr/bin/python3
  2. import sys
  3. def expand_system(system, m, factor):
  4. empty_rows = set(range(m)) - {y for y, _ in system}
  5. empty_cols = set(range(m)) - {x for _, x in system}
  6. expanded = set()
  7. for y, x in system:
  8. expanded.add((y + sum(row < y for row in empty_rows) * factor, (x + sum(col < x for col in empty_cols) * factor)))
  9. return expanded
  10. def manhattan(a, b):
  11. return abs(a[0] - b[0]) + abs(a[1] - b[1])
  12. def part12(factor=1):
  13. print('part 1')
  14. system = set([])
  15. max_y = 0
  16. max_x = 0
  17. for y, line in enumerate(sys.stdin):
  18. for x, c in enumerate(line.strip()):
  19. if c != '.':
  20. system.add((y, x))
  21. max_y = y
  22. max_x = x
  23. print(f'system ({max_y}x{max_x}) {system}')
  24. assert max_y == max_x
  25. m = max_y
  26. distances = 0
  27. system = expand_system(system, m, factor)
  28. for galaxy1 in system:
  29. for galaxy2 in system:
  30. if galaxy1 == galaxy2:
  31. continue
  32. distances += manhattan(galaxy1, galaxy2)
  33. print(distances // 2)
  34. if sys.argv[1] in '1':
  35. part12(factor=1)
  36. else:
  37. part12(factor=(1000000 - 1))