KatInterview

Four Weighted Dice: Lowest Three Add Up to Three

Math & Bit ManipulationAuto-graded · 18 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilitycombinatoricsfractions

Last updated

Compute the exact reduced probability that the three smallest of four independent weighted dice sum to 3, which reduces to counting weighted outcomes with at least three ones.

Four distinguishable dice are rolled independently. Every die is identical. Its faces are numbered 1, 2, ..., m, where m = len(weights). Face i + 1 comes up with probability weights[i] / denominator.

Task

A roll is an ordered 4-tuple (r1, r2, r3, r4) of face values. Its probability is the product of the four individual face probabilities.

For a roll, sort the four values in non-decreasing order and take the first three entries. Duplicates are kept as separate entries, so the roll (1, 1, 2, 2) gives the three values 1, 1, 2. Call the sum of these three values the low sum of the roll.

Return the total probability of all ordered rolls whose low sum is exactly 3, as a fraction in lowest terms.

Rules

  • Use weights and denominator exactly as given. Do not normalize or rescale them, and do not assume that the weights add up to denominator. The probability of face i + 1 is defined to be weights[i] / denominator, and the answer is the formula above applied to these numbers.
  • Rolls are ordered. (1, 1, 1, 2) and (2, 1, 1, 1) are different rolls, and each is counted separately with its own probability.
  • Each roll is counted at most once, so a roll such as (1, 1, 1, 1) contributes its probability a single time.
  • The result is a list [numerator, denominator] with gcd(numerator, denominator) = 1 and denominator > 0. A probability of zero is returned as [0, 1].
  • Return plain Python integers in a list of length 2.

Constraints

  • 1 <= len(weights), typically 6.
  • Each weights[i] is a non-negative integer.
  • denominator is a positive integer.
  • Values are small enough that exact integer arithmetic is fast.

Examples

Example 1

Input: three_lowest_sum_to_three([1, 1, 1, 1, 1, 1], 6)

Output: [7, 432]

Example 2

Input: three_lowest_sum_to_three([2, 1, 1, 1, 1, 1], 6)

Output: [11, 81]

Hints

Hint 1

Every face value is at least 1, so the three smallest values can total 3 only if all three of them equal 1.

Hint 2

That is the same as asking for at least three of the four dice to show a 1. Only 'is a 1' versus 'is not a 1' matters, so merge all other faces into one weight.

Hint 3

Split into disjoint cases to avoid double counting: exactly three ones (4 positions for the non-1 die) and exactly four ones. Divide by denominator^4 and reduce with Fraction or gcd.