From ba7381b531a4306ec3310e135d6e1c84eb7d6e66 Mon Sep 17 00:00:00 2001 From: Benjo Date: Tue, 21 Dec 2021 10:29:10 +0100 Subject: [PATCH] day 21 --- 21/21.py | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 21/input | 2 ++ 21/testInput | 2 ++ 3 files changed, 61 insertions(+) create mode 100644 21/21.py create mode 100644 21/input create mode 100644 21/testInput diff --git a/21/21.py b/21/21.py new file mode 100644 index 0000000..9a9a469 --- /dev/null +++ b/21/21.py @@ -0,0 +1,57 @@ +from itertools import product + + +def readStartPositions(fileName): + with open(fileName) as file: + return tuple(int(line[len(line) - 1]) for line in file.read().splitlines()) + + +def part1(p1: int, p2: int): + P = {True: p1, False: p2} + S = {True: 0, False: 0} + p = True + totalDiceCount = 0 + while True: + diceAmount = 0 + for _ in range(3): + diceAmount += (totalDiceCount % 100) + 1 + totalDiceCount += 1 + P[p] += diceAmount + P[p] = ((P[p] - 1) % 10) + 1 + S[p] += P[p] + if S[p] >= 1000: + break + p = not p + print(totalDiceCount * S[not p]) + + +cache = {} + + +def part2(p1, p2, s1=0, s2=0, p=True): + if (p1, p2, s1, s2, p) in cache: + return cache[(p1, p2, s1, s2, p)] + + winCount = {True: 0, False: 0} + + for r1, r2, r3 in product([1, 2, 3], repeat=3): + P = {True: p1, False: p2} + S = {True: s1, False: s2} + + P[p] += r1 + r2 + r3 + P[p] = ((P[p] - 1) % 10) + 1 + S[p] += P[p] + if S[p] >= 21: + winCount[p] += 1 + else: + subWinCount = part2(*P.values(), *S.values(), not p) + winCount[True] += subWinCount[True] + winCount[False] += subWinCount[False] + + cache[(p1, p2, s1, s2, p)] = winCount + return winCount + + +startPos = readStartPositions("input") +part1(*startPos) +print(max(part2(*startPos).values())) diff --git a/21/input b/21/input new file mode 100644 index 0000000..ccc302a --- /dev/null +++ b/21/input @@ -0,0 +1,2 @@ +Player 1 starting position: 1 +Player 2 starting position: 3 diff --git a/21/testInput b/21/testInput new file mode 100644 index 0000000..3f69194 --- /dev/null +++ b/21/testInput @@ -0,0 +1,2 @@ +Player 1 starting position: 4 +Player 2 starting position: 8