main.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 cp in coords:
  20. if (p1 := cp[0][0]) == (cp[1][0]):
  21. field[min(cp[0][1], cp[1][1]) : max(cp[0][1], cp[1][1]) + 1, p1] += 1
  22. elif (p1 := cp[0][1]) == (cp[1][1]):
  23. field[p1, min(cp[0][0], cp[1][0]) : max(cp[0][0], cp[1][0]) + 1] += 1
  24. elif diag:
  25. mat = field[
  26. cp[:, 1].min() : cp[:, 1].max() + 1, cp[:, 0].min() : cp[:, 0].max() + 1
  27. ]
  28. if cp[1].sum() == cp[0].sum():
  29. np.fliplr(mat).flat[:: mat.shape[0] + 1] += 1
  30. else:
  31. mat.flat[:: mat.shape[0] + 1] += 1
  32. return np.count_nonzero(field > 1)
  33. def part1(input: str):
  34. print("The answer of part1 is:", draw_lines(input, diag=False))
  35. def part2(input: str):
  36. print("The answer of part2 is:", draw_lines(input, diag=True))
  37. if __name__ == "__main__":
  38. get_input(task_dir, 5)
  39. check_example("example", part1)
  40. check_example("example", part2)
  41. part1("input")
  42. part2("input")
  43. generate_readme(task_dir, 5)