# Dice Roll Simulation in C++

Suppose a die simulator generates a random number from 1 to 6 for each roll. We want to introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Consider we have an array of integers rollMax and an integer n, we have to return the number of distinct sequences that can be obtained with exact n rolls. The two sequences are considered different if at least one element differs from each other. So if n is 2, then rollMax = [1,1,2,2,2,3], then the output will be 34. So there will be 2 rolls on die, if there is no constraints, on the die there are 6*6 = 36 possible combinations, in this case the numbers 1 and 2 appears at most once consecutively, so sequences (1,1) and (2,2) cannot occur. so the final answer will be 36 – 2 = 34.

To solve this, we will follow these steps −

• create one method called dfs(), this will take dieLeft, last, currLen, array r and matrix dp
• if dieLeft = 0, then return 1
• if dp[dieLeft][last][currLen] is not -1, then return dp[dieLeft, last, currLen]
• counter := 0
• for i in range 0 to 6
• if i = last and r[i] = currLen, then skip the next part and go for next iteration
• counter := dfs(dieLeft – 1, i, currLen + 1 when i = last, otherwise 1, r, dp)
• dp[dieLeft, last, currLen] := counter
• return dp[dieLeft, last, currLeft]
• the main method will be like −
• create one 3D array called dp of order (n + 1) x 6 x 16, and fill this with -1
• return dfs(n, 0, 0, rollMax, dp)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9+7;
class Solution {
public:
int dfs(int dieLeft, int last, int currLen, vector <int> &r,vector < vector < vector <int> > > &dp){
if(dieLeft == 0){
return 1;
}
if(dp[dieLeft][last][currLen]!=-1)return dp[dieLeft][last][currLen];
int counter = 0;
for(int i =0;i<6;i++){
if(i==last && r[i] == currLen)continue;
counter = (counter%mod + (dfs(dieLeft-1,i,i==last?currLen+1:1,r,dp))%mod)%mod;
}
dp[dieLeft][last][currLen] = counter%mod;
return dp[dieLeft][last][currLen]%mod;
}
int dieSimulator(int n, vector<int>& rollMax) {
vector < vector < vector <int> > > dp(n+1, vector < vector <int> > (6, vector <int>(16, -1)));
return dfs(n,0,0,rollMax, dp)%mod;
}
};
main(){
vector<int> v = {1,1,2,2,2,3};
Solution ob;
cout << (ob.dieSimulator(2,v));
}

## Input

2
[1,1,2,2,2,3]

## Output

34