diff --git a/day02.py b/day02.py new file mode 100644 index 0000000..61bb15d --- /dev/null +++ b/day02.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python + +import re +from functools import reduce + +f = open("day02input.txt", "r") +a = f.readline().strip().split(",") + + +def get_re(pat_len: int, pat_num: int = 2) -> re.Pattern: + return re.compile((r"(" + r"\d" * pat_len + r")") * pat_num) + +def part1(data: list[str]) -> int: + bad_ids = 0 + r = {} + + for id_set in data: + _from, _to = id_set.split("-") + # loop over IDs in range + for _id in range(int(_from), int(_to) + 1): + id_len = len(str(_id)) + + # weed out IDs with odd number of digits + if id_len % 2 == 1: + continue + + hl = str(id_len // 2) + + # check if compiled re is already in dict; add if not + if not hl in r.keys(): + r[hl] = get_re(int(hl)) + + # match ID and check if first and second halves are equal + m = r[hl].match(str(_id)) + if m.group(1) == m.group(2): + bad_ids += _id + return bad_ids + +def part2(data: list[str]) -> int: + bad_ids = set() # collect invalid IDs in a set to avoid adding counting the same ID multiple times + r = {} + + for id_set in data: + _from, _to = id_set.split("-") + + # loop over IDs in range + for _id in range(int(_from), int(_to) + 1): + id_len = len(str(_id)) + + # loop over pattern lengths + for pat_len in range(1, (id_len // 2) + 1): + # weed out IDs where ID length is not a multiple of pattern length + if id_len % pat_len != 0: + continue + + pat_num = id_len // pat_len + + # check if compiled re is already in dict; add if not + if not str(pat_len) in r.keys(): + r[str(pat_len)] = {} + if not str(pat_num) in r[str(pat_len)].keys(): + r[str(pat_len)][str(pat_num)] = get_re(pat_len, pat_num) + print(f"RE:\t{_id}\t\t{pat_len}\t{pat_num}\t{r[str(pat_len)][str(pat_num)]}") + + # match ID and check if all groups are equal + m = r[str(pat_len)][str(pat_num)].match(str(_id)) + if len(set(m.groups())) == 1: + print(f"Match:\t{_id}\t\t{pat_len}\t{pat_num}\t{r[str(pat_len)][str(pat_num)]}") + bad_ids.add(_id) + return sum(bad_ids) + + +print(part1(a)) +print(part2(a)) diff --git a/day02input.txt b/day02input.txt new file mode 100644 index 0000000..60591bc --- /dev/null +++ b/day02input.txt @@ -0,0 +1 @@ +82853534-82916516,2551046-2603239,805115-902166,3643-7668,4444323719-4444553231,704059-804093,32055-104187,7767164-7799624,25-61,636-1297,419403897-419438690,66-143,152-241,965984-1044801,1-19,376884-573880,9440956-9477161,607805-671086,255-572,3526071225-3526194326,39361322-39455443,63281363-63350881,187662-239652,240754-342269,9371-26138,1720-2729,922545-957329,3477773-3688087,104549-119841