Suppose we start at the number zero, and repeatedly roll a fair 6-sided die, adding the resulting number to the total. We win if we reach the total 100, and lose if we overshoot, for example by reaching a total of 99 and then rolling a number greater than 1. Describe an algorithm for computing the probability that we win.
2 Answers
Let $P_k(n)$ be the probability that you are in position $n$ after $k$ throws. Since you always move forward you simply want $\sum\limits_{k=1}^\infty P_k(100)$.
We can calculate $P_k(n)$ recursively. It is clearly equal to $\sum\limits_{j=n-6}^{n-1} p_{k-1}(j)/6$
We only need to calculate $p_k(n)$ for $n\,k leq 100$ and $k\leq 16$, so it can be calculated in time $\mathcal O (n^2)$
Here is a c++ code:
#include <bits/stdc++.h>
using namespace std;
double P[101][101];
int main(){
P[0][0]=1;
for(int k=1;k<101;k++){
for(int n=1;n<101;n++){
for(int j=max(0,n-6); j<n;j++){
P[n][k]+=P[j][k-1]/6;
}
}
}
double res=0;
for(int k=0;k<101;k++){
res+=P[100][k];
}
printf("%f\n",res);
}
The result given is approximately $0.285714$ which makes a lot of sense, the approximate length of each "jump" is $\frac{7}{2}$, so the approximate probability that we hit a number should be around $\frac{2}{7}=0.\overline{285714}$
- 105,651
-
apparently my recursion is more complicated than necessary. The other recursion is better. – Asinomás Jan 06 '17 at 20:05
Hint:
You can use recurrence here. $$a_n=\frac{a_{n-1}+a_{n-2}+a_{n-3}+a_{n-4}+a_{n-5}+a_{n-6}}{6}$$ where $a_n$ is the probability to get the sum $n$.
Therefore, $$a_{100}=\frac{a_{99}+a_{98}+a_{97}+a_{96}+a_{95}+a_{94}}{6}$$
- 1,843