Hugo Riggs
Hugo Riggs

Reputation: 55

Dice Rolling, 2 die, c++, unexpected result

When rolling 2 six-sided die the most common result should be 7, with 2 and 12 as the least common results.

enter image description here

When I execute the code below, I get a high occurrence of the number 12 which is erroneous.

#include <iostream>
#include <iomanip>
#include <random>
#include <ctime>
#include <array>
using namespace std;

int main() {

    default_random_engine engine(static_cast<unsigned int>(time(0)));
    uniform_int_distribution<unsigned int> randomInt(1, 6);

    const size_t arraySize{11};
    array<unsigned int, arraySize> frequency{};

    for (unsigned int roll{1}; roll <= 36'000'000; ++roll){
        ++frequency[randomInt(engine) + randomInt(engine)];
    }

    cout << "Face" << setw(24) << "Frequency" << endl;

    for (size_t sum{2}; sum <= 12; ++sum) {
        cout << setw(4) << sum << setw(24) << frequency[sum] << endl;
    }
}

Below are a couple results:

Face               Frequency
   2                 1001328
   3                 1997709
   4                 2999938
   5                 4000842
   6                 4998363
   7                 5998813
   8                 5003114
   9                 4001434
  10                 3000068
  11                 1999298
  12                 5197605

Face               Frequency
   2                 1001328
   3                 1997709
   4                 2999938
   5                 4000842
   6                 4998363
   7                 5998813
   8                 5003114
   9                 4001434
  10                 3000068
  11                 1999298
  12                 5197605

Why are so many 12's being counted?

Upvotes: 1

Views: 255

Answers (1)

max66
max66

Reputation: 66200

Try setting arraySize to 13, not to 11.

With 11 you're lucky unlucky not to get a core-dump.

Setting arraySize to 11, frequency[11] and frequency[12] are initialized with undefined values.

Setting to 13 I get

Face               Frequency
   2                  999735
   3                 1999765
   4                 2997658
   5                 3998991
   6                 5003045
   7                 6002570
   8                 4999055
   9                 3999659
  10                 3000068
  11                 1999566
  12                  999888

Setting to 11 I get

Face               Frequency
   2                  998866
   3                 1999702
   4                 3001777
   5                 3999977
   6                 4999754
   7                 5999024
   8                 5000215
   9                 4000132
  10                 2999408
  11               793621638
  12                 1000941

Upvotes: 5

Related Questions