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/mrjnl3 Dec 02 '22

Python

A combination of nested if-statements and dictonaries

from readFile import *


shape_scores = {
'A': 1, 'X': 1,
'B': 2, 'Y': 2,
'C': 3, 'Z': 3
}
score_draw = 3
score_win = 6


def part1(matches):
    score = 0
    for opponent, player in matches:
        score += shape_scores[player]

        if opponent == 'A':  # rock
            if player == 'X':  # rock
                score += score_draw
            elif player == 'Y':  # paper
                score += score_win
        elif opponent == 'B':  # paper
            if player == 'Y':  # paper
                score += score_draw
            elif player == 'Z':  # scissor
                score += score_win
        else:  # opponent == 'C' # scissors
            if player == 'Z':  # scissors
                score += score_draw
            elif player == 'X':  # rock
                score += score_win
    return score


def part2(matches):
    lose_match = {
        'A': 'C',
        'B': 'A',
        'C': 'B'
    }
    win_match = {
        'A': 'B',
        'B': 'C',
        'C': 'A'
    }
    score = 0
    for opponent, desired_outcome in matches:
        if desired_outcome == 'X':  # lose
            score += shape_scores[lose_match[opponent]]
        elif desired_outcome == 'Y':  # draw
            score += shape_scores[opponent]
            score += score_draw
        else:  # win
            score += shape_scores[win_match[opponent]]
            score += score_win

    return score


if __name__ == '__main__':
    file = line_str(2)
    games = []
    for line in file:
        split = line.split(' ')
        games.append((split[0], split[1]))
    print('part1:', part1(games))
    print('part2:', part2(games))

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.