# encoding: utf-8 # Given a list of comma-separated pairs of numbers separated by a dash # e.g. 111-999,22-33 # find all the numbers that are some sequence of digits repeated # any number of times import logging import random import re logger = logging.Logger(__name__) logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.INFO) TESTING = False INPUT_FILE = "day2_test_input.txt" if TESTING else "day2_input.txt" def main(): with open(INPUT_FILE, "r") as f: input_line = f.readline().strip() inranges = [x.strip() for x in input_line.split(",")] num_ranges = len(inranges) tenths = num_ranges//10 logger.debug(f"Received {num_ranges} ranges.") all_invalids = [] for i, r in enumerate(inranges): if tenths and i % tenths == 0: logger.debug(f"Processing range {i}.") x, y = [int(q) for q in r.strip().split("-")] logger.debug(f"x: {x}, y: {y}") invalids = [] k = x while k <= y: found = False s_k = str(k) l = len(s_k) m = l//2 t = 1 while not found and t <= m: pattern = fr'^({s_k[:t]}){{2,}}$' found = re.match(pattern, s_k) is not None # if random.randint(1,10) == 1: logger.debug(f"Pattern: {pattern}, value: {s_k}, found: {found}") if found: logger.debug(f"Found a multiple: {k}") invalids.append(k) t += 1 k += 1 all_invalids.extend(invalids) logger.info(f"Found {len(all_invalids)} invalid IDs.") logger.info(f"Sum of invalid IDs is {sum(all_invalids)}.") if __name__ == "__main__": main()