input = "137826495" #input = "389125467" cups = [int(i) for i in list(input)] max_cup = max(cups) def ring_str(after): result = "" current = 1 printed = [] while current not in printed: result += str(current) printed.append(current) current = after[current] return result def run_on_cups(cups, iterations): cup_count = len(cups) max_cup = max(cups) after = {} for i in range(0, cup_count - 1): after[cups[i]] = cups[i + 1] after[cups[-1]] = cups[0] current_cup = cups[0] for i in range(0, iterations): #print("Current:", current_cup) #print_ring(after) one = after[current_cup] two = after[one] three = after[two] three_cups = [one, two, three] #print("Selecting:", three_cups) dest = current_cup while True: dest -= 1 if dest == 0: dest = max_cup if dest not in three_cups: break #print("Destination:", dest) after[current_cup] = after[three] after[three] = after[dest] after[dest] = one current_cup = after[current_cup] return after after = run_on_cups(cups, 100) print("Answer 1:", ring_str(after)[1:]) after = run_on_cups(cups + list(range(10, 1000001)), 10000000) a = after[1] b = after[a] print("Answer 2:", a * b)