main.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import os, sys
  2. task_dir = os.path.dirname(__file__)
  3. sys.path.append(f"{task_dir}/..")
  4. import numpy as np
  5. from get_tasks import get_input, generate_readme, check_example, bench
  6. from itertools import takewhile
  7. from scipy import ndimage
  8. def parse(input, test=False):
  9. if test:
  10. code = (
  11. "".join([line for line in takewhile(lambda l: len(l) > 0, input)])
  12. .replace("#", "1")
  13. .replace(".", "0")
  14. )
  15. image = np.array([list(line) for line in input[8:]])
  16. else:
  17. code = input[0].replace("#", "1").replace(".", "0")
  18. image = np.array([list(line) for line in input[2:]])
  19. image[image == "."] = 0
  20. image[image == "#"] = 1
  21. return image.astype(int), code
  22. def naive_enhance_image(image, code, step):
  23. if code[0] == "0":
  24. pad = 0
  25. val = pad
  26. else:
  27. pad = step % 2
  28. val = 1 - pad
  29. sp = 3 if step == 0 else 1
  30. enhance_image = np.pad(image, sp, "constant", constant_values=pad)
  31. enhanced_image = np.full_like(enhance_image, val, dtype=int)
  32. for i in range(enhance_image.shape[0] - 2):
  33. for j in range(enhance_image.shape[1] - 2):
  34. win = enhance_image[i : i + 3, j : j + 3]
  35. enhanced_image[i + 1, j + 1] = code[
  36. int("".join(win.flatten().astype(str)), 2)
  37. ]
  38. return enhanced_image
  39. # works ony in test
  40. def scipy_enhance_image(image, code, outside=0):
  41. def convert(values):
  42. string = "".join(str(int(value)) for value in values)
  43. return code[int(string, 2)]
  44. enhance_image = np.pad(image, 1)
  45. ndimage.generic_filter(
  46. enhance_image, convert, size=3, mode="constant", cval=outside
  47. )
  48. def part1(input, test=False):
  49. image, code = parse(input, test)
  50. for step in range(2):
  51. image = naive_enhance_image(image, code, step)
  52. print("The answer of part1 is:", image.sum())
  53. @bench
  54. def part2(input, test=False):
  55. image, code = parse(input, test)
  56. for step in range(50):
  57. image = naive_enhance_image(image, code, step)
  58. print("The answer of part2 is:", image.sum())
  59. if __name__ == "__main__":
  60. input, example = get_input(task_dir, 20)
  61. part1(example, True)
  62. part2(example, True)
  63. part1(input)
  64. part2(input)
  65. generate_readme(task_dir, 20)