DEV Community

Viper
Viper

Posted on

Advent of Code 2020: Python Solution Day 22

This time we have to fight with crab and fighting with crab is easier. I quickly found the solution to part one and for the part two, I took help from here. So for the second part, credit goes to the author of that code. What was your solution? Please share it on comment.

Part 1

with open("day22.txt") as fp:
    lines = fp.read().split("\n\n")
lines = {line.split(":")[0]: line.split(":")[1].strip() for line in lines}
lines = {key: list(map(lambda x: int(x), value.split("\n"))) for key, value in lines.items()}
card_dict = lines.copy()

p1 = card_dict["Player 1"]
p2 = card_dict["Player 2"]

i = 0
while len(p1) != 0 or len(p2) != 0:
    print(f"Iteration {i}, P1: {p1}, P2: {p2}")
    c1 = p1[0]
    c2 = p2[0]
    del p1[0]
    del p2[0]

    if c1 > c2:
        p1.append(c1)
        p1.append(c2)
    else:
        p2.append(c2)
        p2.append(c1)
    i+=1
    if len(p1) == 0 or len(p2) == 0:
        break
if len(p1) == 0:
    part1_sum = sum([((i+1)*j) for i, j in enumerate(p2[::-1])])
else:
    part1_sum = sum([((i+1)*j) for i, j in enumerate(p1[::-1])])
part1_sum
Enter fullscreen mode Exit fullscreen mode

Part 2

def recursive_war(p1cards, p2cards, visited):
    while(len(p1cards) > 0 and len(p2cards) > 0):
        if (tuple(p1cards), tuple(p2cards)) in visited:
            return 1, p1cards

        visited.add((tuple(p1cards), tuple(p2cards)))

        a, b = p1cards.pop(0), p2cards.pop(0)
        if len(p1cards) >= a and len(p2cards) >= b:
            winner, _ = recursive_war(p1cards[:a], p2cards[:b], set())
        else:
            winner = 1 if a > b else 0

        if winner == 1:
            p1cards.extend([a, b])
        else:
            p2cards.extend([b, a])
    return (1, p1cards) if len(p1cards) > 0 else (0, p2cards)
print(sum((i + 1) * x for i, x in enumerate(recursive_war(card_dict["Player 1"], card_dict["Player 2"]
                                                          , set())[1][::-1])))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)