main.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import re
  2. import os, sys
  3. import numpy as np
  4. task_dir = os.path.dirname(__file__)
  5. sys.path.append(f"{task_dir}/..")
  6. from get_tasks import generate_readme, check_example, get_input
  7. def draw_lines(input: str, diag: bool = False) -> int:
  8. with open(f"{input}.txt", "r") as f:
  9. inp = f.readlines()
  10. coords = np.array(
  11. [
  12. np.array([(nums[0:2], nums[2:])], dtype=int)
  13. for nums in [re.findall("\d+", num) for num in inp]
  14. ]
  15. )
  16. size = coords.max()
  17. field = np.zeros([size + 1, size + 1])
  18. coords = coords.reshape(coords.shape[0], 2, 2)
  19. for (x, y), (X, Y) in coords:
  20. if x == X:
  21. field[min(y, Y) : max(y, Y) + 1, x] += 1
  22. elif y == Y:
  23. field[y, min(x, X) : max(x, X) + 1] += 1
  24. elif diag:
  25. mat = field[min(y, Y) : max(y, Y) + 1, min(x, X) : max(x, X) + 1]
  26. if x + y == X + Y:
  27. np.fliplr(mat).flat[:: mat.shape[0] + 1] += 1
  28. else:
  29. mat.flat[:: mat.shape[0] + 1] += 1
  30. return np.count_nonzero(field > 1)
  31. def part1(input: str):
  32. print("The answer of part1 is:", draw_lines(input, diag=False))
  33. def part2(input: str):
  34. print("The answer of part2 is:", draw_lines(input, diag=True))
  35. if __name__ == "__main__":
  36. get_input(task_dir, 5)
  37. check_example("example", part1)
  38. check_example("example", part2)
  39. part1("input")
  40. part2("input")
  41. generate_readme(task_dir, 5)