Browse Source

Much faster solution to day 23

Frans Bergman 4 years ago
parent
commit
12f83baa4b
1 changed files with 34 additions and 32 deletions
  1. 34 32
      23.py

+ 34 - 32
23.py

@@ -1,30 +1,36 @@
-from collections import deque
-from time import time
-
 input = "137826495"
 #input = "389125467"
 cups = [int(i) for i in list(input)]
 max_cup = max(cups)
 
-def my_popleft(cups, following):
-    current = cups.popleft()
-    if current in following:
-        cups.extendleft(following[current])
-        del following[current]
-    return current
+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)
-    following = {}
-    start = time()
-    print("Start")
+    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):
-        current_cup = my_popleft(cups, following)
-        one = my_popleft(cups, following)
-        two = my_popleft(cups, following)
-        three = my_popleft(cups, following)
-        three_cups = [three, two, one]
+        #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
@@ -32,20 +38,16 @@ def run_on_cups(cups, iterations):
                 dest = max_cup
             if dest not in three_cups:
                 break
-        following[dest] = three_cups
-        cups.append(current_cup)
-    print("Time:", time() - start)
-
-    while len(following) > 0:
-        current = my_popleft(cups, following)
-        cups.append(current)
-    return cups
+        #print("Destination:", dest)
+        after[current_cup] = after[three]
+        after[three] = after[dest]
+        after[dest] = one
+        current_cup = after[current_cup]
+    return after
 
-res1 = run_on_cups(deque(cups), 100)
-print("Answer 1:", ''.join([str(i) for i in res1]))
-res2 = run_on_cups(deque(cups + list(range(10, 1000001))), 10000000)
-res2.rotate(- res2.index(1))
-assert res2.popleft() == 1
-a = res2.popleft()
-b = res2.popleft()
+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)