#!/usr/bin/env python3 lines = (x.strip() for x in open("input.txt")) init_stats = [[], []] player2 = False for line in lines: if line.startswith("Player"): continue elif line == "": player2 = True else: init_stats[1 if player2 else 0].append(int(line)) def play_game(stats): done = set() while all(len(x) > 0 for x in stats): state = (*stats[0], "+", *stats[1]) if state in done: return True, state done.add(state) a, b = stats[0].pop(0), stats[1].pop(0) if len(stats[0]) >= a and len(stats[1]) >= b: winner = play_game([stats[0][:a], stats[1][:b]])[0] else: winner = a > b if winner: stats[0].extend((a, b)) else: stats[1].extend((b, a)) return len(stats[0]) > 0, stats winner, out_stats = play_game(init_stats) print(list(map(lambda x: sum(i*v for i, v in zip(x, range(len(x), 0, -1))), out_stats))[0 if winner else 1])