#/usr/bin/env python # Remove all instances of #"1"# from the code # to view Part 1 interactively # Remove all instances of #"2"# from the code # and comment out the one originally uncommented # line under each instance of #"2"# (three such instances # are present in this program) to run Part 1 rather # than Part 2 # In the above instructions, #"x"# for some digit "x" # (without quotes) represents #x# in the actual code # below pipes = [] with open("/home/login/bin/advent17/input24.txt") as f: for line in f: pipes.append([int(n) for n in line[:-1].split("/")]) def pipes_containing_connector(n, pipe_list): pipes_sublist = [] for pipe in pipe_list: if n in pipe: pipes_sublist.append(pipe) return pipes_sublist bridges = [] strengths = [] pipes_left = [] pipes_with_0_connector = pipes_containing_connector(0, pipes) # set so that checking if element belongs in set # has constant time complexity for pipe in pipes_with_0_connector: bridges.append([[0],pipe]) strengths.append(sum(pipe)) pipes_left.append([p for p in pipes if p!=pipe]) connected_connector = open_connector = 0 # Legend: (Max Strength, min Strength, number of bridges) #1#print("Ms, ms, nb") #1#print("") max_strength = max(strengths) min_strength = min(strengths) #2#while max_strength!=min_strength: while bridges: bridge_indices = range(len(bridges)) #1#print(max_strength, min_strength, len(bridges)) #1#input() for i in bridge_indices: pipes_left = (p for p in pipes if p not in bridges[i]) if not pipes_left: # empty generator is False continue # Current connected_connector is open_connector # from previous iteration connected_connector = open_connector # Setting current open_connector if bridges[i][-1][0] in bridges[i][-2]: open_connector = bridges[i][-1][1] elif bridges[i][-1][1] in bridges[i][-2]: open_connector = bridges[i][-1][0] connectable_pipes = pipes_containing_connector(open_connector, pipes_left) for pipe in connectable_pipes: my_bridge = [p for p in bridges[i]] my_bridge.append(pipe) my_strength = strengths[i] bridges.append(my_bridge) strengths.append(my_strength+sum(pipe)) offset=0 max_strength = max(strengths) min_strength = min(strengths) for i in bridge_indices: #2#if strengths[i-offset] < max_strength: #2# del bridges[i-offset], strengths[i-offset] #2# offset+=1 del bridges[0], strengths[0] #2#print("Part 1: " + str(max_strength)) print("Part 2: " + str(max_strength))