We are given a fair 6-sided die. Each time we throw the die, our score gets increased as the number on the top of the die. Find the expected number of throws needed to reach a score at least equal to goal.
Examples :
Input : 2 Output : 1.1666666666666667 After the first throw, there is a probability of 1/6 that we will need an additional throw (if the outcome was 1 in the first throw). Input : 47 Output : 13.90476189046144
Approach :
Let’s denote dp[n] as the expected number of throws needed for us to get a score of at least n. dp[0] = 0.
Now we can compute rest of dp states as dp[n] = 1 + dp[n-1]/6 + dp[n-2]/6 + dp[n-3]/6 + dp[n-4]/6 + dp[n-5]/6 + dp[n-6]/6.
After one throw we can get any of 1, 2, 3, 4, 5, and 6 added to our score with an equal probability of 1/6.
Thus we can transition from a previous state and calculate all our answers with a linear dynamic programming technique.
Time Complexity : O(N)
Space Complexity : O(N)
Implementation :
#include<bits/stdc++.h>
using namespace std;
double expectedThrows(int goal){
//dp[x]=expected number of throws to reach a score of atleast x
vector<double> dp(goal+1);
for(int i=1;i<=goal;i++){
dp[i]=1; // throw die once
//iterate over all possible outcome
for(int j=1;j<=6;j++){
if(i-j<0)break;
// expected number of throws times probability (1/6)
dp[i]+=dp[i-j]/6.0;
}
}
//expected number of throws to reach goal
return dp[goal];
}
int32_t main()
{
cout << fixed << setprecision(12);
cout<<expectedThrows(2);
//prints 1.166666666667
return 0;
}