#!/usr/bin/env python from itertools import chain my_raw_input = [] my_input = {} with open("/home/login/bin/advent/input12.txt") as f: for line in f: my_raw_input.append(line.split()) my_input[int(my_raw_input[-1][0])] = [int(item[:-1]) for item in my_raw_input[-1][2:]] def group(id, adjacency_dict): list_of_programs = [id] offsets = [1] list_of_programs.extend([item for item in adjacency_dict[list_of_programs[0]] if item not in list_of_programs]) if len(list_of_programs) > offsets[0]: offsets.append(len(list_of_programs)) else: # group is a singleton return list_of_programs i = 1 offset_i = 0 # offset index, for indexing into `offsets` is_i_reset = False while offset_i != len(offsets): beginning_offset_i = offset_i while i <= 1999: if i == 1: is_i_reset = False if any(map(lambda x: x in list_of_programs[offsets[offset_i]:], adjacency_dict[i])): if i not in list_of_programs: list_of_programs.append(i) for j in adjacency_dict[i]: if j not in list_of_programs: list_of_programs.append(j) is_i_reset = True if i == 1999 and is_i_reset == True: i = 0 # i will become 1 because of i+=1 offsets.append(len(list_of_programs)) offset_i+=1 i += 1 if beginning_offset_i == offset_i: break return list_of_programs groups = [] groups.append(group(0, my_input)) answer1 = 0 for group_item in groups: if 0 in group_item: answer1 = len(groups[0]) break print("Part 1: " + str(answer1)) for key in my_input: for group_item in groups: if key not in chain.from_iterable(groups): groups.append(group(key, my_input)) if len(list(chain.from_iterable(groups))) == len(my_input): break answer2 = len(groups) print("Part 2: " + str(answer2))