Files
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

1.9 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
6a2037a68a0bc2aef0006004 Challenge 342: Dice Odds 29 challenge-342

--description--

Given a number of six-sided dice to roll and a target sum, return the odds of rolling that sum as a string in the format "1 in X".

  • The number of dice will be between 1 and 6.
  • The target sum is always achievable with the given number of dice.
  • Round "X" to the nearest whole number.

--hints--

get_odds(1, 5) should return "1 in 6".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_odds(1, 5), "1 in 6")`)
}})

get_odds(2, 4) should return "1 in 12".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_odds(2, 4), "1 in 12")`)
}})

get_odds(3, 10) should return "1 in 8".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_odds(3, 10), "1 in 8")`)
}})

get_odds(4, 7) should return "1 in 65".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_odds(4, 7), "1 in 65")`)
}})

get_odds(5, 26) should return "1 in 111".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_odds(5, 26), "1 in 111")`)
}})

get_odds(6, 35) should return "1 in 7776".

({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(get_odds(6, 35), "1 in 7776")`)
}})

--seed--

--seed-contents--

def get_odds(dice, target):

    return dice

--solutions--

def get_odds(dice, target):
    valid_combos = 0
    total_combos = 6 ** dice

    def roll(dice_left, total):
        nonlocal valid_combos
        if dice_left == 0:
            if total == target:
                valid_combos += 1
            return
        for face in range(1, 7):
            roll(dice_left - 1, total + face)

    roll(dice, 0)
    return f"1 in {round(total_combos / valid_combos)}"