From 62599897938c30a787bd1c33899734d5d119613f Mon Sep 17 00:00:00 2001 From: Samuel Shuert Date: Wed, 1 Oct 2025 15:07:49 +0000 Subject: [PATCH] feat: oct 1 level 4 --- python/oct1/level4/playThreeDiceYahtzee.py | 92 ++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 python/oct1/level4/playThreeDiceYahtzee.py diff --git a/python/oct1/level4/playThreeDiceYahtzee.py b/python/oct1/level4/playThreeDiceYahtzee.py new file mode 100644 index 0000000..fd300f4 --- /dev/null +++ b/python/oct1/level4/playThreeDiceYahtzee.py @@ -0,0 +1,92 @@ +def handToDice(hand: int) -> tuple[int, int, int]: + """Converts a hand to a tuple of dice.""" + return hand // 100, (hand // 10) % 10, hand % 10 + + +def diceToOrderedHand(a: int, b: int, c: int) -> int: + """Converts a tuple of dice to an ordered hand.""" + ordered = sorted([a, b, c]) + return ordered[2] * 100 + ordered[1] * 10 + ordered[0] + + +def playStep2(hand: int, dice: int) -> tuple[int, int]: + """ + If you don't have 3 matching dice: + If you have a pair: keep the pair and reroll the third + Else: Roll all dice again + """ + (a, b, c) = handToDice(hand) + if a == b and b == c: + return hand, dice + if a == b: + c = dice % 10 + dice //= 10 + elif b == c: + a = dice % 10 + dice //= 10 + elif a == c: + b = dice % 10 + dice //= 10 + else: + b = dice % 10 + dice //= 10 + c = dice % 10 + dice //= 10 + return diceToOrderedHand(a, b, c), dice + + +def score(hand: int) -> int: + """ + Calculate the score of a hand + 3 dice match: 20 + highest value * 3 + 2 dice match: 10 + highest value * 2 + 1 dice match: highest value + """ + (a, b, c) = handToDice(hand) + if a == b and b == c: + return 20 + a * 3 + elif a == b: + return 10 + a * 2 + elif b == c: + return 10 + b * 2 + elif a == c: + return 10 + c * 2 + else: + return a + + +def playThreeDiceYahtzee(dice: int) -> tuple[int, int]: + """Play a game of Three Dice Yahtzee""" + a = dice % 10 + dice //= 10 + b = dice % 10 + dice //= 10 + c = dice % 10 + dice //= 10 + hand = diceToOrderedHand(a, b, c) + hand, dice = playStep2(hand, dice) + hand, dice = playStep2(hand, dice) + return hand, score(hand) + + +print("Testing playThreeDiceYahtzee()...", end="") +assert handToDice(123) == (1, 2, 3) +assert handToDice(214) == (2, 1, 4) +assert handToDice(422) == (4, 2, 2) + +assert diceToOrderedHand(1, 2, 3) == 321 +assert diceToOrderedHand(1, 4, 2) == 421 + +assert playStep2(413, 2312) == (421, 23) +assert playStep2(544, 23) == (443, 2) +assert playStep2(544, 456) == (644, 45) + +assert score(432) == 4 +assert score(443) == 10 + 4 + 4 +assert score(633) == 10 + 3 + 3 +assert score(555) == 20 + 5 + 5 + 5 + +assert playThreeDiceYahtzee(2312413) == (432, 4) +assert playThreeDiceYahtzee(2633413) == (633, 16) +assert playThreeDiceYahtzee(2333555) == (555, 35) +print("Passed!") -- 2.51.2