From c2b5593a6ca2c4108ca40f84b10058f9bd7907a6 Mon Sep 17 00:00:00 2001 From: Sebastian Mark Date: Wed, 11 Dec 2024 16:35:44 +0100 Subject: [PATCH] add 2022/day04 --- 2022/04/main.py | 53 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 2022/04/main.py diff --git a/2022/04/main.py b/2022/04/main.py new file mode 100644 index 0000000..50a3a2f --- /dev/null +++ b/2022/04/main.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python +# -*- encoding: utf-8; py-indent-offset: 4 -*- + +# Author: Sebastian Mark +# CC-BY-SA (https://creativecommons.org/licenses/by-sa/4.0/deed.de) + +# pylint: disable=missing-module-docstring,missing-function-docstring,consider-using-f-string + + +def readinput(): + with open("input", "r", encoding="utf-8") as file: + lines = [line.strip().split(",") for line in file] + return lines + + +def overlaps(a: str, b: str) -> bool: + start_a, stop_a = a.split("-") + start_b, stop_b = b.split("-") + for x in range(int(start_a), int(stop_a) + 1): + if x in range(int(start_b), int(stop_b) + 1): + return True + return False + + +def contains(a: str, b: str) -> bool: + start_a, stop_a = a.split("-") + start_b, stop_b = b.split("-") + for x in range(int(start_a), int(stop_a) + 1): + if x not in range(int(start_b), int(stop_b) + 1): + return False + return True + + +def main(): + assignments = readinput() + + # part 1 + count = 0 + for list_a, list_b in assignments: + if contains(list_a, list_b) or contains(list_b, list_a): + count += 1 + print("Assignments in range: %d" % count) + + # part 2 + count = 0 + for list_a, list_b in assignments: + if overlaps(list_a, list_b) or overlaps(list_b, list_a): + count += 1 + print("Overlapping ranges: %d" % count) + + +if __name__ == "__main__": + main()