Day 2 (Puzzle 1) - Rock, Paper, Scissor

Successfully finished the first puzzle in which rock, paper scissor had to be evaluated into points and summed up. I wonder if there is a more elegant way of checking for wins vs losses.
main
Peery 2 years ago
parent 0a735eb84b
commit a77ad30e10

@ -1,5 +1,8 @@
from typing import Tuple
from entities.items.item import Item
from entities.items.food import Food
from rockpaperscissor.file.guide_list import RPS
class Elf:
@ -45,3 +48,30 @@ class Elf:
def get_inventory_calories(self) -> int:
return sum([x.calorie_value for x in list(filter(lambda x: isinstance(x, Food), self.get_inventory()))])
def evaluate_RPS_round(self, other: str, own: str) -> Tuple[bool, int]:
"""
Evaluates a rock paper scissor round according to day 2 puzzle 1.
:param other: What the opponent played
:param own: what you played
:return:
"""
round_score = None
was_win = None
if other == own:
round_score = RPS.DRAW_SCORE
else:
if (other == RPS.PAPER and own == RPS.ROCK) or \
(other == RPS.SCISSOR and own == RPS.PAPER) or \
(other == RPS.ROCK and own == RPS.SCISSOR):
round_score = RPS.LOSS_SCORE
was_win = False
elif (other == RPS.PAPER and own == RPS.SCISSOR) or \
(other == RPS.SCISSOR and own == RPS.ROCK) or \
(other == RPS.ROCK and own == RPS.PAPER):
round_score = RPS.WIN_SCORE
was_win = True
else:
raise Exception(f"Something went terribly wrong! Other: {other} Own: {own}")
return was_win, round_score + RPS.RPS_SHAPE_TO_SCORE[own]

File diff suppressed because it is too large Load Diff

@ -1,15 +1,21 @@
from calories.file.calorie_list import CalorieList
from entities.elf import Elf
from rockpaperscissor.file.guide_list import RockPaperScissorGuide
if __name__ == "__main__":
elves = CalorieList("./input/day1/input.lst").parse_file()
for elf in elves:
print(f"Elf {elf} has calories: {elf.get_inventory_calories()}")
elves.sort(key=lambda x: x.get_inventory_calories(), reverse=True)
print(f"Most calories has: {elves[0]} with {elves[0].get_inventory_calories()} calories in their inventory!")
my_elf = Elf()
other_elf = Elf()
rounds = RockPaperScissorGuide("./input/day2/input.lst").parse_file()
scores = []
for other, own in rounds:
result, score = my_elf.evaluate_RPS_round(other, own)
scores.append(score)
if result:
r = "won"
else:
r = "lost"
print(f"Elf {my_elf} played {own} against {other} and {r} with {score} points!")
print()
print(f"I've got a total of {sum(scores)} points!")
print(f"The top 3 calorie elves are: {elves[0]} ({elves[0].get_inventory_calories()}), "
f"{elves[1]} ({elves[1].get_inventory_calories()}) and "
f"{elves[2]} ({elves[2].get_inventory_calories()})")
print(f"Their total is: {sum([x.get_inventory_calories() for x in elves[:3]])}")

@ -0,0 +1,14 @@
from calories.file.calorie_list import CalorieList
if __name__ == "__main__":
elves = CalorieList("./input/day1/input.lst").parse_file()
for elf in elves:
print(f"Elf {elf} has calories: {elf.get_inventory_calories()}")
elves.sort(key=lambda x: x.get_inventory_calories(), reverse=True)
print(f"Most calories has: {elves[0]} with {elves[0].get_inventory_calories()} calories in their inventory!")
print(f"The top 3 calorie elves are: {elves[0]} ({elves[0].get_inventory_calories()}), "
f"{elves[1]} ({elves[1].get_inventory_calories()}) and "
f"{elves[2]} ({elves[2].get_inventory_calories()})")
print(f"Their total is: {sum([x.get_inventory_calories() for x in elves[:3]])}")

@ -0,0 +1,66 @@
import os
from typing import List, Tuple
class RPS:
ROCK = "R"
PAPER = "P"
SCISSOR = "S"
ROCK_SCORE = 1
PAPER_SCORE = 2
SCISSOR_SCORE = 3
WIN_SCORE = 6
DRAW_SCORE = 3
LOSS_SCORE = 0
RPS_SYM_TO_SHAPE = {
"A": ROCK,
"X": ROCK,
"B": PAPER,
"Y": PAPER,
"C": SCISSOR,
"Z": SCISSOR
}
RPS_SHAPE_TO_SCORE = {
ROCK: ROCK_SCORE,
PAPER: PAPER_SCORE,
SCISSOR: SCISSOR_SCORE
}
class RockPaperScissorGuide:
"""
Day 2 - Rock Paper Scissors
The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage,
a giant Rock Paper Scissors tournament is already in progress.
One Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win.
The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors.
The second column, you reason, must be what you should play in response: X for Rock, Y for Paper,
and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen.
The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors)
plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).
"""
def __init__(self, path: str):
if not os.path.isfile(path):
raise FileNotFoundError(f"File was not found or isn't a file: {path}")
self.file_path = path
def parse_file(self) -> List[Tuple[str, str]]:
strategy_guide = []
with open(self.file_path, "r") as file:
for line in file:
line = line.replace("\n", "")
a, b = line.split(" ")
strategy_guide.append((RPS.RPS_SYM_TO_SHAPE[a], RPS.RPS_SYM_TO_SHAPE[b]))
return strategy_guide
Loading…
Cancel
Save