Files
aoc2020/day22/module.py
2020-12-22 07:14:57 +01:00

135 lines
3.1 KiB
Python

from aoc.input import get_input
import time
import copy
import itertools
import time
import collections
import re
from aoc.partselector import part_one, part_two
import functools
def pw(line):
return line.strip()
def p1():
inp = get_input(pw)
players = []
temp = []
for sample in inp:
if sample == '':
players.append(temp)
temp = []
continue
if not 'Player' in sample:
temp.append(int(sample))
while True:
i = (players[0].pop(0), players[1].pop(0))
print(i)
if i[0] > i[1]:
players[0].append(i[0])
players[0].append(i[1])
else:
players[1].append(i[1])
players[1].append(i[0])
if(len(players[0]) == 0):
break
if(len(players[1]) == 0):
break
if len(players[0]) == 0:
w = players[1]
else:
w = players[0]
su = 0
for i, x in enumerate(reversed(w), start=1):
print(i,x)
su += i*x
print(su)
return inp
globalgame = 0
mdepth = 0
def p2():
inp = get_input(pw)
players = []
temp = []
for sample in inp:
if sample == '':
players.append(temp)
temp = []
continue
if not 'Player' in sample:
temp.append(int(sample))
print(players)
final = False
wins = [0, 0]
def play(players, depth=0):
global globalgame
global mdepth
mdepth = max(mdepth, depth)
globalgame += 1
history = set()
while all(filter(lambda x: len(x) > 0, players)):
hv = frozenset([frozenset(players[0]), frozenset(players[1])])
# ','.join(map(str, players[0])) + ':' + ','.join(map(str, players[1]))
if hv in history:
return 0
else:
history.add(hv)
i = (players[0].pop(0), players[1].pop(0))
if i[0] <= len(players[0]) and i[1] <= len(players[1]):
players2 = [players[0][:i[0]], players[1][:i[1]]]
won = play(players2, depth + 1)
if won == 1:
won = 0
else:
won = 1
#print(f'cont game {game} {won}')
else:
won = i[0] > i[1]
if won:
players[0].append(i[0])
players[0].append(i[1])
else:
players[1].append(i[1])
players[1].append(i[0])
if(len(players[0]) == 0):
return 1
if(len(players[1]) == 0):
return 0
won = play(players, 1)
if len(players[0]) == 0:
w = players[1]
else:
w = players[0]
su = 0
for i, x in enumerate(reversed(w), start=1):
#print(i,x)
su += i*x
print(su, f'(played games {globalgame}/{mdepth})')
return 0
result1 = None
if part_one():
start = time.time()
result1 = p1()
print(round(1000*(time.time() - start), 2), 'ms')
if part_two():
start = time.time()
p2()
print(round(1000*(time.time() - start), 2), 'ms')