Two-Die Wager Expected Value

Easy · Statistics & Math · Data Scientist · Onsite

Problem Statement

A tabletop wager pits a challenger against a dealer, each throwing a single unbiased cube numbered 1 through 6 independently:

  • Whenever the challenger's face value exceeds the dealer's (challenger > dealer), the challenger collects n dollars (+n).
  • Whenever the dealer's face value exceeds or equals the challenger's (challenger <= dealer, so identical faces favor the dealer), the challenger forfeits m dollars (-m).

Given non-negative integer stakes n and m, implement dice_game_analysis(n, m) returning a dictionary with two entries:

  • "expected_value": a float equal to the exact single-round mean net dollar payoff.
  • "should_play": a bool indicating whether a risk-neutral challenger accepts the wager (True whenever the mean net payoff is non-negative, including exact break-even 0.0, and False when negative).

Examples

Example 1

Input: n = 12, m = 6
Output: {'expected_value': 1.5, 'should_play': True}

Out of 36 equally probable die pairs, 15 give challenger > dealer (+12 each, totaling +180) and 21 give challenger <= dealer (-6 each, totaling -126). Dividing 180 - 126 = 54 by 36 yields 1.5, which is positive, so "should_play" is True.

Example 2

Input: n = 6, m = 6
Output: {'expected_value': -1.0, 'should_play': False}

Equal payouts favor the dealer because all 6 matching rolls count as challenger losses: (15 * 6 - 21 * 6) / 36 = -36 / 36 = -1.0, so "should_play" is False.

Example 3

Input: n = 21, m = 15
Output: {'expected_value': 0.0, 'should_play': True}

Here 15 * 21 = 315 balances 21 * 15 = 315 exactly, producing mean payoff 0.0. Because non-negative expectation (>= 0) meets the risk-neutral acceptance rule, "should_play" is True.

Constraints

  • 0 <= n, m <= 10^9
  • Avoid intermediate floating-point rounding drift when testing exact break-even stakes (5 * n == 7 * m).

Step-by-step walkthrough

  1. Restate the rules and what risk-neutral means

    In each round, the challenger and the dealer each throw one unbiased, independent six-sided die:

    • If player_roll > house_roll (strictly higher), you gain +n dollars.
    • If player_roll <= house_roll (the dealer rolls higher or both dice tie), you lose -m dollars.

    We need to return {"expected_value": EV, "should_play": bool} and also show how to cross-check the formula via simulation.

    The expected value (EV) of one round is the long-run average dollar gain (or loss) per round across infinitely many independent rounds. A risk-neutral participant cares only about this long-run average, not about round-to-round swings:

    • If EV > 0, you gain money on average, so accept (True).
    • If EV < 0, you lose money on average, so decline (False).
    • If EV == 0, playing and walking away have the exact same average return (0.0). As shown in Example 3 (n = 21, m = 15), exact break-even counts as acceptable (should_play = True), so the decision rule is EV >= 0.
  2. Map out all 36 dice pairs in a 6x6 grid

    Because both dice are unbiased and independent, every ordered pair (player_roll, house_roll) from (1, 1) to (6, 6) has the exact same probability: 1 / 36. Laying out all 6 * 6 = 36 pairs in a grid makes the counts unmistakable (W = strict win, T = tie, L = lower roll):

                     Dealer roll
                     1   2   3   4   5   6
    Player     1  [  T   L   L   L   L   L  ]   -> 0 W, 1 T, 5 L
    roll       2  [  W   T   L   L   L   L  ]   -> 1 W, 1 T, 4 L
               3  [  W   W   T   L   L   L  ]   -> 2 W, 1 T, 3 L
               4  [  W   W   W   T   L   L  ]   -> 3 W, 1 T, 2 L
               5  [  W   W   W   W   T   L  ]   -> 4 W, 1 T, 1 L
               6  [  W   W   W   W   W   T  ]   -> 5 W, 1 T, 0 L
    
    Strict wins (below diagonal):   0 + 1 + 2 + 3 + 4 + 5 = 15 pairs
    Ties (on main diagonal):        6 pairs
    Strict losses (above diagonal): 15 pairs
    

    Because ties belong to the dealer, your losing outcomes combine the 15 lower rolls and the 6 ties into 15 + 6 = 21 pairs:

    P(win)  = 15 / 36 = 5 / 12  (about 41.7%)
    P(lose) = 21 / 36 = 7 / 12  (about 58.3%)
    

    With only 36 pairs, we can also let a short loop count win_pairs and loss_pairs directly so there is zero chance of an arithmetic slip:

    from typing import Tuple
    
    
    def count_outcomes() -> Tuple[int, int]:
        """Count (win_pairs, loss_pairs) across all 36 equally likely (player, house) rolls."""
        win_pairs = 0
        loss_pairs = 0
        # Two fair 6-sided dice produce 6 * 6 = 36 equally likely ordered pairs (1..6, 1..6).
        for player_roll in range(1, 7):
            for house_roll in range(1, 7):
                # You win only on a strictly higher roll; ties go to the house as losses.
                if player_roll > house_roll:
                    win_pairs += 1
                else:
                    loss_pairs += 1
        return win_pairs, loss_pairs
    
  3. Build the expected value formula step by step

    Expected value multiplies each possible dollar outcome by its probability and adds them together. Here there are two outcomes: +n with probability 15 / 36, and -m with probability 21 / 36:

    EV = (+n) * (15 / 36) + (-m) * (21 / 36)
       = (15 * n - 21 * m) / 36
       = (5 * n - 7 * m) / 12       (dividing numerator and denominator by 3)
    

    Let's check Example 2 (n = 6, m = 6):

    EV = (5 * 6 - 7 * 6) / 12 = (30 - 42) / 12 = -12 / 12 = -1.0 dollars
    

    Even though the dice look symmetric at first glance, staking 6 against 6 loses $1.00 per round on average because all 6 ties go to the dealer.

  4. Derive the condition on n and m to play

    A risk-neutral player accepts whenever EV >= 0. Starting from our formula and multiplying both sides by positive 12 (which preserves the >= direction):

    (5 * n - 7 * m) / 12 >= 0
    5 * n - 7 * m >= 0
    5 * n >= 7 * m
    

    When m > 0, we can also write this as n / m >= 7 / 5 = 1.4: a win must pay at least 1.4 times (40% more than) what a loss costs just to overcome the tie disadvantage.

    Example |  n  |  m  | 5*n vs 7*m   | EV = (15*n - 21*m)/36 | should_play
    --------+-----+-----+--------------+-----------------------+------------
       1    | 12  |  6  |  60 >  42    |         1.5           |    True
       2    |  6  |  6  |  30 <  42    |        -1.0           |    False
       3    | 21  | 15  | 105 == 105   |         0.0           |    True
    

    In code, always test 15 * n - 21 * m >= 0 (or 5 * n >= 7 * m) rather than n / m >= 1.4, because m = 0 is a valid input where dividing by m would crash with ZeroDivisionError.

  5. Write the exact analysis function without float drift

    A subtle floating-point trap happens if you write (5 / 12) * n - (7 / 12) * m. Because 5 / 12 and 7 / 12 are repeating binary fractions, Python rounds each fraction slightly before multiplying; at the exact break-even stakes n = 147, m = 105, (5 / 12) * 147 - (7 / 12) * 105 evaluates to -7.105e-15 instead of 0.0, causing >= 0 to wrongly return False!

    Computing the integer numerator net_payoff_sum = win_pairs * n - loss_pairs * m first uses exact Python integer arithmetic, so every break-even game gives net_payoff_sum == 0 and 0 / 36 == 0.0 with zero rounding drift.

    from typing import Dict
    
    
    def dice_game_analysis(n: int, m: int) -> Dict[str, object]:
        # win_pairs = 15 (strictly higher), loss_pairs = 21 (15 lower + 6 ties)
        win_pairs, loss_pairs = count_outcomes()
        total_pairs = win_pairs + loss_pairs
    
        # Compute the exact integer numerator first so break-even stakes (5n == 7m) never suffer float drift.
        net_payoff_sum = win_pairs * n - loss_pairs * m
        expected_value = net_payoff_sum / total_pairs
    
        # Risk-neutral rule: accept whenever EV >= 0 (including exact break-even EV == 0 as True).
        should_play = net_payoff_sum >= 0
        return {"expected_value": expected_value, "should_play": should_play}
    
  6. Cross-check with a Monte Carlo simulation

    A Monte Carlo simulation estimates the theoretical EV empirically by rolling two virtual dice for R independent rounds (say R = 100,000) using a seeded random number generator, adding +n on strict wins and -m otherwise, and dividing total net winnings by R. By the law of large numbers (as the number of independent trials grows, the sample average converges toward the true expected value), this sample average approaches (5n - 7m) / 12.

    import random
    
    
    def simulate_ev(n: int, m: int, rounds: int = 100_000, seed: int = 0) -> float:
        """Monte Carlo check: average the net payoff across many seeded random rounds."""
        rng = random.Random(seed)
        total_payoff = 0
        for _ in range(rounds):
            player_roll = rng.randint(1, 6)
            house_roll = rng.randint(1, 6)
            if player_roll > house_roll:
                total_payoff += n
            else:
                total_payoff -= m
        return total_payoff / rounds
    

    How close should the simulated average be before we call it verified? One round wins +n with probability p = 5/12 and loses -m with probability 1 - p = 7/12, so its spread per round has standard deviation (n + m) * sqrt(p * (1 - p)). Across R independent rounds, the standard error (the typical random wiggle in the sample mean) shrinks by sqrt(R):

    standard_error = (n + m) * sqrt((5/12) * (7/12)) / sqrt(R)
    For n = 12, m = 6, R = 100,000:  18 * sqrt(35 / 144) / sqrt(100,000) ≈ 0.028
    

    Checking that abs(simulated_ev - formula_ev) < 3 * standard_error (about ±0.084 here) confirms our formula without mistaking normal random noise for a bug.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import random
    
    
    def count_outcomes() -> Tuple[int, int]:
        """Count (win_pairs, loss_pairs) across all 36 equally likely (player, house) rolls."""
        win_pairs = 0
        loss_pairs = 0
        # Two fair 6-sided dice produce 6 * 6 = 36 equally likely ordered pairs (1..6, 1..6).
        for player_roll in range(1, 7):
            for house_roll in range(1, 7):
                # You win only on a strictly higher roll; ties go to the house as losses.
                if player_roll > house_roll:
                    win_pairs += 1
                else:
                    loss_pairs += 1
        return win_pairs, loss_pairs
    
    
    def dice_game_analysis(n: int, m: int) -> Dict[str, object]:
        # win_pairs = 15 (strictly higher), loss_pairs = 21 (15 lower + 6 ties)
        win_pairs, loss_pairs = count_outcomes()
        total_pairs = win_pairs + loss_pairs
    
        # Compute the exact integer numerator first so break-even stakes (5n == 7m) never suffer float drift.
        net_payoff_sum = win_pairs * n - loss_pairs * m
        expected_value = net_payoff_sum / total_pairs
    
        # Risk-neutral rule: accept whenever EV >= 0 (including exact break-even EV == 0 as True).
        should_play = net_payoff_sum >= 0
        return {"expected_value": expected_value, "should_play": should_play}
    
    
    def simulate_ev(n: int, m: int, rounds: int = 100_000, seed: int = 0) -> float:
        """Monte Carlo check: average the net payoff across many seeded random rounds."""
        rng = random.Random(seed)
        total_payoff = 0
        for _ in range(rounds):
            player_roll = rng.randint(1, 6)
            house_roll = rng.randint(1, 6)
            if player_roll > house_roll:
                total_payoff += n
            else:
                total_payoff -= m
        return total_payoff / rounds
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a carnival dice booth with one quiet rule: "ties go to the dealer." When challenger and dealer each roll an unbiased six-sided die, there are 6 * 6 = 36 equally likely outcome pairs. Six of those pairs are ties (1,1) through (6,6), leaving 30 non-ties that split evenly by symmetry—15 where the challenger's roll is higher and 15 where the dealer's roll is higher. Because the dealer claims all 6 ties on top of the 15 higher rolls, the challenger wins only 15 / 36 (5 / 12) of the time and loses 21 / 36 (7 / 12) of the time. We evaluate the wager using expected value (EV) (the long-run average dollar gain or loss per round) for a risk-neutral player (someone who judges a bet solely by its average payoff, regardless of ups and downs).

The most common mistake is treating "higher die wins" like a 50–50 coin flip and accepting equal payouts (n = m), which actually loses m / 6 dollars per round. On the coding side, writing the formula as (5 / 12) * n - (7 / 12) * m introduces tiny binary floating-point rounding errors (for instance, -7.1e-15 at the exact break-even stakes n = 147, m = 105), which flips EV >= 0 from True to False. Similarly, checking the ratio n / m >= 1.4 crashes with ZeroDivisionError whenever m = 0. Computing the exact integer numerator 15 * n - 21 * m before a single division by 36 avoids both traps completely.

Walk through the three statement examples: 1. n = 12, m = 6 (Example 1): Across 36 equally likely outcomes, 15 wins bring in 15 * 12 = +180 dollars and 21 losses cost 21 * 6 = -126 dollars. Net sum is +54, so EV = 54 / 36 = 1.5 and should_play is True. 2. n = 6, m = 6 (Example 2): 15 wins bring in +90 dollars while 21 losses cost -126 dollars. Net sum is -36, so EV = -36 / 36 = -1.0 and should_play is False. 3. n = 21, m = 15 (Example 3): 15 wins bring in +315 dollars and 21 losses cost -315 dollars. Net sum is 0, so EV = 0.0 and should_play is True.

Complexity

  • Time: O(1) for dice_game_analysis. count_outcomes always loops over the exact same 6 * 6 = 36 pairs regardless of how large n and m are, followed by a handful of arithmetic operations. For the Monte Carlo simulation (estimating an expected value by averaging many randomized computer trials), simulate_ev runs in O(R) time because it simulates R rounds in a single loop doing O(1) work per round.
  • Space: O(1) for both dice_game_analysis and simulate_ev. Only a few integer counters and the two-key output dictionary are stored in memory at any point, even when R is in the hundreds of thousands.

Edge cases

  • Exact break-even stakes (5 * n == 7 * m, such as (21, 15) or (147, 105)): net_payoff_sum is 0, expected_value is 0.0, and should_play is True (matching Example 3).
  • Equal stakes (n == m > 0, such as (6, 6) in Example 2): EV = (15n - 21n) / 36 = -n / 6 < 0, so equal payouts always favor the dealer.
  • Zero loss stake (m == 0, n >= 0): losing or tying costs nothing, so net_payoff_sum = 15 * n >= 0 and should_play is True without ever dividing by m.
  • Zero win stake (n == 0, m > 0): you can never gain money (EV = -21 * m / 36 < 0), so should_play is False.
  • Very large integer stakes (n = 700_000_007, m = 500_000_005): Python integers have arbitrary precision, so 15 * n - 21 * m evaluates to 0 with zero overflow or catastrophic cancellation.

Common mistakes

  • Treating ties as a "push" (0 dollars exchanged): if ties paid 0, P(lose) would be 15 / 36 instead of 21 / 36 and EV would be 15 * (n - m) / 36. Under this game's rules, ties forfeit m dollars.
  • Assuming P(win) = 1/2: forgetting the 6 diagonal ties overestimates the win probability (18 / 36 vs 15 / 36).
  • Pre-dividing probabilities before multiplying: (15 / 36) * n - (21 / 36) * m rounds repeating binary floats before subtraction and can produce tiny negative numbers like -7.1e-15 when the true EV is 0. Keep one division at the end: (15 * n - 21 * m) / 36.
  • Using strict EV > 0 instead of EV >= 0: Exact break-even inputs like (21, 15) in Example 3 satisfy risk-neutral acceptance and expect should_play = True.
  • Expecting a Monte Carlo simulation to hit the formula to 6 decimal places: by the law of large numbers (sample averages converge toward the true mean as trial count R grows), the standard error (typical random error of the sample mean) shrinks at rate 1 / sqrt(R). At R = 100,000 for (12, 6), random noise is around ±0.028, so verify within 2 to 3 standard errors rather than testing exact float equality.

Follow-up questions

  • How would the expected payoff and decision threshold change if tied rolls returned zero dollars instead of counting as losses? Six of the 36 outcomes would yield 0 dollars, leaving 15 wins (+n) and 15 losses (-m). The expected value would become EV = (15 * n - 15 * m) / 36 = 5 * (n - m) / 12, and a risk-neutral challenger would accept whenever n >= m. That shows the dealer's entire statistical edge in the original wager comes from claiming ties.
  • Why might a risk-averse bettor reject a break-even wager, and how could they size bets when the edge is positive? A risk-averse player (someone who dislikes uncertainty and requires a positive profit cushion to compensate for potential losses) also cares about variance (the average squared distance of outcomes from the mean, here (5/12) * (7/12) * (n + m)^2, which equals 315 at (21, 15)). At EV = 0, taking on variance for zero expected reward makes a risk-averse player strictly worse off, so they require EV > 0 by a margin depending on their bankroll. When EV > 0 and bets can be sized as a fraction of bankroll, the Kelly criterion (a formula that maximizes long-run logarithmic bankroll growth while avoiding ruin) risks fraction p - (1 - p) * (m / n) per round—for example, 5/12 - (7/12) * (6/12) = 1/8 at (12, 6), and 0 at break-even.
  • When winning pays 10 dollars and losing costs 5 dollars, about how many rounds are needed for a 95% probability of net profit? One round has mean EV = (150 - 105) / 36 = 1.25 dollars and standard deviation sqrt((5/12) * (7/12) * 15^2) = sqrt(54.6875) ≈ 7.40 dollars. Using the normal approximation (approximating the sum of many independent rounds with a bell curve), total profit after R rounds has mean 1.25 * R and standard deviation 7.40 * sqrt(R), which stays above 0 with 95% probability when (1.25 * R) / (7.40 * sqrt(R)) >= 1.645, giving R >= (1.645 * 7.40 / 1.25)^2 ≈ 95 rounds (and by exact binomial probabilities, P(profit > 0) stays permanently above 95% for every R >= 100).

Follow-up questions

Similar questions

More PayPal interview questions

All 53 PayPal questions →