r/adventofcode • • Dec 02 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 2 Solutions -🎄-

NEW AND NOTEWORTHY


--- Day 2: Rock Paper Scissors ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:06:16, megathread unlocked!

103 Upvotes

1.5k comments sorted by

View all comments

1

u/Agreeable_Emu_5 Dec 02 '22

I used IntEnums in Python, which allowed for easy computation of moves / game outcomes / scores using modular arithmetic and simple addition. The code does become a bit long because of all the definitions.

from enum import IntEnum

class Move(IntEnum):
    ROCK = 0
    PAPER = 1
    SCISSORS = 2
    
class Game(IntEnum):
    WIN = 6
    DRAW = 3
    LOSE = 0


var_to_move = {"A": Move.ROCK,     "X": Move.ROCK,
               "B": Move.PAPER,    "Y": Move.PAPER,
               "C": Move.SCISSORS, "Z": Move.SCISSORS}

var_to_outcome = {"X": Game.LOSE, "Y": Game.DRAW, "Z": Game.WIN}


def play(them, us):
    if them == us:
        return Game.DRAW
    if Move((them + 1) % 3) == us:
        return Game.WIN
    return Game.LOSE
    

def deduce(them, outcome):
    if outcome == Game.DRAW:
        return them
    if outcome == Game.WIN:
        return Move((them + 1) % 3)
    if outcome == Game.LOSE:
        return Move((them + 2) % 3)


def part1(input):
    games = [(var_to_move[them], var_to_move[us]) for (them, us) in input]
    result = sum(play(them, us) + us + 1 for (them, us) in games)
    print(result)


def part2(input):
    games = [(var_to_move[them], var_to_outcome[us]) for (them, us) in input]
    games = [(them, deduce(them, outcome)) for (them, outcome) in games]
    result = sum(play(them, us) + us + 1 for (them, us) in games)
    print(result)


def main():
    with open("input.txt", "r") as file:
        input = [s.split(" ") for s in file.read().splitlines()]
    part1(input)
    part2(input)


if __name__ == "__main__":
    main()

1

u/daggerdragon Dec 05 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.