Ways to Roll a Total
Write dice_ways(n, target) that returns the number of different ways that n six-sided dice can show a total of exactly target. The dice are different from each other, so (1, 2) and (2, 1) are two different rolls.
dice_ways(2, 7) is 6. The tests include 10 and 25 dice, so trying every roll is too slow.
Understand the problem
Count by hand.
How many different rolls are there for 3 dice, whatever the total?
Each die has 6 faces, and the dice are independent: 6 x 6 x 6 = 216. For 10 dice it is 6 to the power 10, about 60 million.
In how many ways can 2 dice show a total of 7?
The rolls are (1,6), (2,5), (3,4), (4,3), (5,2), (6,1): six ways. (1,6) and (6,1) count as different rolls.
Write the brute force
Write the simplest version that is correct, even if it is slow. Then you have something to test against and something to improve.
def dice_ways(n, target):
# Write the simple version here. It only has to be correct, not fast.
pass
Hint 1: a question to ask yourself
How can you generate every possible roll of n dice?
Hint 2: the shape of the answer
itertools.product(range(1, 7), repeat=n) generates all rolls as tuples. Count those whose sum(roll) == target.
Find the bottleneck
How big is the search?
For 25 dice there are 6 to the power 25 rolls. Is it possible to try them all?
- Yes, in a minute
- No: it is about 2.8 x 10 to the power 19 rolls, far more than a computer can count
- Yes with a faster computer
A computer does about 10 million simple steps per second in Python. 2.8 x 10^19 steps would take tens of thousands of years. The search has to be avoided, not made faster.
ways(n, t): the first die shows f (1 to 6). How many ways do the remaining dice have?
ways(n, t)ways(n - 1, t - f)ways(n - 1, t)
If the first die shows f, the other n - 1 dice must add up to t - f. So ways(n, t) is the sum over the six faces of ways(n - 1, t - f). The same sub-questions repeat a lot, so remember their answers.
Make it faster
Use the recursion above with remembered results.
def dice_ways(n, target):
# Write the faster version here.
pass
Hint 1: a question to ask yourself
What are the base cases? How many ways can zero dice make a total of 0, and a total other than 0?
Hint 2: the pattern
Dynamic programming: ways(n, t) = sum of ways(n - 1, t - f) for f in 1..6, with ways(0, 0) = 1. Use functools.lru_cache or a table built from 0 dice upwards.
Hint 3: pseudocode
ways = {0: 1} # with 0 dice, total 0 in one way
repeat n times:
new = empty
for total, count in ways: for face 1..6: new[total + face] += count
ways = new
return ways.get(target, 0)
Reflect
Brute force: 6 to the power n rolls
from itertools import product
def dice_ways(n, target):
return sum(1 for roll in product(range(1, 7), repeat=n) if sum(roll) == target)
Improved: dynamic programming
from collections import defaultdict
def dice_ways(n, target):
ways = {0: 1}
for _ in range(n):
new = defaultdict(int)
for total, count in ways.items():
for face in range(1, 7):
new[total + face] += count
ways = new
return ways.get(target, 0)
Another way: memoized recursion
from functools import lru_cache
@lru_cache(maxsize=None)
def dice_ways(n, target):
if n == 0:
return 1 if target == 0 else 0
return sum(dice_ways(n - 1, target - face) for face in range(1, 7))
What this tests: itertools.product, recognising a counting problem that explodes, and dynamic programming with a dictionary or lru_cache.
The idea: instead of listing every roll, keep a table "how many ways to reach each total with k dice" and extend it one die at a time. The table has at most 6 x n entries, so the work is about 6 x 6n steps, not 6^n.
Dynamic programming in one sentence: split the problem into smaller ones with the same shape, notice that the small ones repeat, and store each answer once.
Cost:
| Version | Time |
|---|---|
product of all rolls |
O(6 to the power n) |
| Table over totals | O(n x n x 6) |
What an interviewer might ask next: Make the number of faces a parameter, and count the ways for at least a target. (Sum the table entries from target up.)
VISIBLE = 3
CASES = [
((2, 7), 6, 'two dice, total 7'),
((1, 3), 1, 'one die'),
((1, 7), 0, 'impossible with one die'),
((0, 0), 1, 'no dice make a total of 0 in one way'),
((0, 5), 0, 'no dice cannot make 5'),
((3, 10), 27, 'three dice, total 10'),
((2, 12), 1, 'two sixes'),
((3, 3), 1, 'three ones'),
((4, 14), 146, 'four dice'),
((2, 1), 0, 'too small'),
]
def REFERENCE(n, target):
ways = {0: 1}
for _ in range(n):
new = {}
for total, count in ways.items():
for face in range(1, 7):
new[total + face] = new.get(total + face, 0) + count
ways = new
return ways.get(target, 0)
LIMIT = 2.0
def PERF():
return [('10 dice, total 35', (10, 35)), ('25 dice, total 87', (25, 87)), ('60 dice, total 210', (60, 210))]