I am doing some c++ practice and trying to write a program to count the amount of times a dice combination is rolled after 10000 attempts. I have used a 2D array to store every possible dice combination, and I perform 10000 rand()%6+1 and increments the value in the memory allocation it randoms.
This is my attempt.
cout << "\nDice roll analyser" << endl;
const int first = 6;
const int second = 6;
int nRolls[first][second];
int count = 0;
while (count < 10000){
nRolls[rand()%6+1][rand()%6+1]+=1;
count++;
}
for (int i=0;i<first;i++){
for (int j=0;j<second;j++){
cout << nRolls[i][j] << " ";
}
}
This is the output that I get;
0 0 0 0 0 0 0 269 303 265 270 264 228 289 272 294 290 269 262 294 303 277 265 294 288 266 313 274 301 245 317 276 292 284 264 260
What I am trying to achieve is the amount of times each combination is rolled e.g. how many times 1, 6 is rolled etc.
You never update your
count.For something where you want to run a code segment n times, where right now n = 10000, this is the general way you wanna do it.
additionally,
myVariable+=1can always be simplified to either++myVariableormyVariable++(if you aren’t use the value of myVariable right when you are assigning it, it is better to use the first one. More info on pre/post increment can be found here: http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_015.htmso instead of
nRolls[rand()%6+1][rand()%6+1]+=1;you can instead do
Additionally, arrays are zero-indexed, meaning when you do
rand()%6+1you are restricting the values from1to6and leaving out the0position of an array, which is the first one, so consider instead just usingthen, to find out how often you roll a (i,j), where i and j are between 1 and 6,