main.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import os, sys
  2. import numpy as np
  3. task_dir = os.path.dirname(__file__)
  4. sys.path.append(f"{task_dir}/..")
  5. from get_tasks import get_input, check_example, generate_readme
  6. def bits2num(bits: np.ndarray) -> int:
  7. return (bits * 2 ** np.arange(bits.shape[0] - 1, -1, -1)).sum()
  8. def part1(input):
  9. diagnostics = np.array(
  10. [list(bits.replace("\n", "")) for bits in input], dtype=np.uint8
  11. )
  12. a = diagnostics.sum(axis=0)
  13. b = diagnostics.shape[0] - a
  14. gamma = (a > b).astype(np.uint)
  15. epsilon = 1 - gamma
  16. gamma_decimal = bits2num(gamma)
  17. epsilon_decimal = bits2num(epsilon)
  18. print(
  19. f"The gamma rate is {gamma_decimal}, and the epsilon rate is {epsilon_decimal}."
  20. )
  21. print(
  22. f"The power comnsuimpsion of the submarine and the answer of part1 is: {gamma_decimal * epsilon_decimal}"
  23. )
  24. def filter_array(array: np.ndarray, CO2: bool) -> np.ndarray:
  25. for ind in range(array.shape[1]):
  26. a = array.sum(axis=0)
  27. b = array.shape[0] - a
  28. c = (a >= b).astype(np.uint)
  29. if CO2:
  30. c = 1 - c
  31. if (temp := array[array[:, ind] == c[ind]]).size != 0:
  32. array = temp
  33. else:
  34. break
  35. return array
  36. def part2(input):
  37. diagnostics = np.array(
  38. [list(bits.replace("\n", "")) for bits in input], dtype=np.uint8
  39. )
  40. O2 = filter_array(diagnostics, False)
  41. CO2 = filter_array(diagnostics, True)
  42. O2_decimal = bits2num(O2[0])
  43. CO2_decimal = bits2num(CO2[0])
  44. print(f"The oxygen generator rating is {O2_decimal}")
  45. print(f"The CO2 scrubber rating is {CO2_decimal}")
  46. print(
  47. f"The life support raiting and the answer of part2 is: {O2_decimal*CO2_decimal}"
  48. )
  49. if __name__ == "__main__":
  50. import timeit
  51. input, example = get_input(task_dir, 3)
  52. setup = """
  53. from __main__ import part1, part2
  54. import os, sys
  55. import numpy as np
  56. task_dir = os.path.dirname(__file__)
  57. sys.path.append(f"{task_dir}/..")
  58. from get_tasks import get_input
  59. input, example = get_input(task_dir, 3)
  60. """
  61. check_example(example, part1)
  62. check_example(example, part2)
  63. part1(input)
  64. print("\n")
  65. part2(input)
  66. # meas = timeit.timeit("part2(input)", setup=setup, number=100)
  67. # print((meas))
  68. generate_readme(task_dir, 3)