Advertisement
Guest User

AOC_2020_Day22

a guest
Dec 21st, 2020
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 0 0
  1. from __future__ import division
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. from math import cos,sin
  5. import sys
  6. sys.path.append("../../")
  7. from aoc_utilities import *
  8.  
  9. def calc_score(d):
  10.     return np.sum([d[-i]*i for i in range(1,len(d)+1)])
  11.  
  12. sol1,sol2 = 0,0
  13.  
  14. inp,raw = parse(year = 2020, day = 22,delim=' ',force_int=True,test=False)
  15.  
  16. p1 = [i[0] for i in inp[1:26]]
  17. p2 = [i[0] for i in inp[28:]]
  18.  
  19. sol1 = 0
  20. while True:
  21.     a = p1[0]
  22.     b = p2[0]
  23.  
  24.     if a > b:
  25.         p1 = p1[1:] + [a,b]
  26.         p2 = p2[1:]
  27.     else:
  28.         p1 = p1[1:]
  29.         p2 = p2[1:] + [b,a]
  30.  
  31.     if len(p1) == 0:
  32.         sol1 = calc_score(p2)
  33.         print('p2',sol1)
  34.         break
  35.     if len(p2) == 0:
  36.         sol1 = calc_score(p1)
  37.         print('p1',sol1)
  38.         break
  39.  
  40. p1 = [i[0] for i in inp[1:26]]
  41. p2 = [i[0] for i in inp[28:]]
  42.  
  43. def play_recursive(d1,d2,ret_score=False):
  44.     history = {}
  45.     while True:
  46.         x = ','.join([str(i) for i in d1]) + ','.join([str(i) for i in d2])
  47.         if x in history:
  48.             score = -1
  49.             if ret_score: score = calc_score(d1)
  50.             return 'p1',score
  51.         else:
  52.             history[x] = 1
  53.  
  54.  
  55.         a,b = d1[0], d2[0]
  56.        
  57.         if len(d1)-1 >= a and len(d2)-1 >= b:
  58.             winner,score = play_recursive(d1[1:1+a],d2[1:1+b])
  59.         else:
  60.             winner = 'p1' if a > b else 'p2'
  61.  
  62.         if winner == 'p1':
  63.             d1 = d1[1:] + [a,b]
  64.             d2 = d2[1:]
  65.         else:
  66.             d1 = d1[1:]
  67.             d2 = d2[1:] + [b,a]
  68.  
  69.         if len(d1) == 0:
  70.             score = -1
  71.             if ret_score:
  72.                 print(d2)
  73.                 score = calc_score(d2)
  74.             return 'p2',score
  75.         if len(d2) == 0:
  76.             score = -1
  77.             if ret_score:
  78.                 print(d1)
  79.                 score = calc_score(d1)
  80.             return 'p1',score
  81.  
  82.  
  83. print(play_recursive(p1,p2,ret_score = True))
  84.  
  85.  
  86.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement