From 5a5f94d5571e0789042b50b83913c4d1a3644204 Mon Sep 17 00:00:00 2001 From: aaron Date: Sun, 4 Dec 2022 14:25:37 +0100 Subject: [PATCH] solve day 4 --- 4/cleanup.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 4/cleanup.py diff --git a/4/cleanup.py b/4/cleanup.py new file mode 100644 index 0000000..d091b9e --- /dev/null +++ b/4/cleanup.py @@ -0,0 +1,51 @@ +from aocd.models import Puzzle +from aocd import submit + + +def find_overlaps(sets: list) -> int: + overlaps = [1 if set.intersection(*pair) else 0 for pair in sets] + return sum(overlaps) + + +def find_subsets(sets: list) -> int: + """ + count the number of sets that fully contain each other + """ + subsets = [ + 1 if pair[0].issubset(pair[1]) or pair[1].issubset(pair[0]) else 0 + for pair in sets + ] + return sum(subsets) + + +def parse_input(data: list) -> list: + """ + parses the input data and generates a list of set tuples + """ + # get a list of section pairs + sections = [sections.split(",") for sections in data.split("\n")] + + # generate a list of section set pairs + sets = list() + for pair in sections: + a, b = pair[0].split("-") + c, d = pair[1].split("-") + a, b, c, d = int(a), int(b), int(c), int(d) + sets.append([set(range(a, b + 1)), set(range(c, d + 1))]) + return sets + + +if __name__ == "__main__": + # get puzzle and parse data + puzzle = Puzzle(year=2022, day=4) + sections = parse_input(puzzle.input_data) + + # part a: find the number of sections that fully contain each other + answer_a = find_subsets(sections) + print(f"sum of priorities of all common items amongst compartments: {answer_a}") + submit(answer_a, part="a", day=4, year=2022) + + # part b: determine the priority of common items in groups of three and create a priority summary + answer_b = find_overlaps(sections) + print(f"sum of priorities of all common items amongst groups of three: {answer_b}") + submit(answer_b, part="b", day=4, year=2022)