diff --git a/2021/d01/p1.py b/2021/d01/p1.py new file mode 100644 index 0000000..baf308d --- /dev/null +++ b/2021/d01/p1.py @@ -0,0 +1,34 @@ +import itertools +from pathlib import Path +from typing import Sequence, Iterable + + +INPUT_FILE_PATH = Path('..', 'inputs', '1.txt') + + +def get_measurements_from_input(input_text: str) -> Iterable[int]: + """ + :param input_text: input test to process + :return: split measurements from the input + """ + return map(int, input_text.splitlines()) + + +def get_depth_measurements_increases(measurements: Sequence[int]) -> int: + """ + :param measurements: measurements to parse + :return: count of the number of times a depth measurement increases + """ + return sum(couple[1] > couple[0] for couple in itertools.pairwise(measurements)) + + +def main(): + input_text = INPUT_FILE_PATH.read_text() + measurements = get_measurements_from_input(input_text) + + depth_measurements_increases = get_depth_measurements_increases(measurements) + print(f'Amount of measurements which are larger than the previous measurement: {depth_measurements_increases}') + + +if __name__ == '__main__': + main() diff --git a/2021/d01/p2.py b/2021/d01/p2.py new file mode 100644 index 0000000..6729b44 --- /dev/null +++ b/2021/d01/p2.py @@ -0,0 +1,34 @@ +from typing import Iterable + +from p1 import INPUT_FILE_PATH, get_measurements_from_input, get_depth_measurements_increases + + +_DEFAULT_WINDOW_SIZE = 3 + + +def get_measurements_windows(measurements: Iterable[int], window_size: int = _DEFAULT_WINDOW_SIZE) -> Iterable[ + tuple[int]]: + """ + Create sliding windows of measurements and return them. + Stop when there are not enough measurements to produce a window with the given size. + :param measurements: measurements to create windows from + :param window_size: size of every window + :return: measurements windows + """ + measurements = list(measurements) + indented_measurements = (measurements[i:] for i in range(window_size)) + return zip(*indented_measurements) + + +def main(): + input_text = INPUT_FILE_PATH.read_text() + measurements = get_measurements_from_input(input_text) + windows = get_measurements_windows(measurements) + windows_sums = [sum(window) for window in windows] + + sums_increases = get_depth_measurements_increases(windows_sums) + print(f'Amount of measurements windows sums which are larger than the previous sum: {sums_increases}') + + +if __name__ == '__main__': + main()