Advertisement
Guest User

Untitled

a guest
Dec 16th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.35 KB | None | 0 0
  1.  
  2.  
  3. from timeit import default_timer as timer
  4.  
  5. s = open("inputs/16.txt").read().strip()
  6. pattern = [0, 1, 0, -1]
  7.  
  8.  
  9. def solve(message, offset, repeat):
  10.     v = list(map(int, s)) * repeat
  11.     N = len(v)
  12.     v2 = [0] * N
  13.     cumsum = [0] * (N + 1)
  14.     for phase in range(100):
  15.         ts = timer()
  16.         # Precompute cumulative sums in O(N) so we can do fast range sums
  17.         cumsum[0] = 0
  18.         for i in range(N):
  19.             cumsum[i + 1] = cumsum[i] + v[i]
  20.         # Each entry sums intervals with increasing width. Inner loop takes O(N/w) so
  21.         # O(N / 1 + N / 2 + N / 3 + ... + N / N) which is O(N*H_N) or O(N*log(N))
  22.         for i in range(N):
  23.             total = 0
  24.             w = i + 1
  25.             # Sum intervals of width w (special casing the first and last interval)
  26.             p = 0
  27.             for j in range(-1, N, w):
  28.                 start = j
  29.                 if start < 0:
  30.                     start = 0
  31.                 end = j + w
  32.                 if end >= N + 1:
  33.                     end = N
  34.                 total += pattern[p] * (cumsum[end] - cumsum[start])
  35.                 p = (p + 1) % 4
  36.             v2[i] = abs(total) % 10
  37.  
  38.         v, v2 = v2, v
  39.         ts2 = timer()
  40.         print(phase, ts2 - ts)
  41.  
  42.     print(message, "".join(map(str, v[offset : offset + 8])))
  43.  
  44.  
  45. solve("Part1", 0, 1)
  46. solve("Part2", s[:7], 10000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement