0

I am trying to create a program that will roll 2 dice 10 million times, and output how many times each number is rolled. Along with this, I am tasked with creating a histogram (*=2000) for the outputs. Here is what I have so far.

/*
Creating a program that counts outcomes of two dice rolls, then show a
histogram of the outcomes.
Section 1 : Simulate ten million times rolls of two dice, while counting
outcomes. (Hint: Use an array of size 13.)
Section 2 : Show the outcome, the numbers of outcomes, and the histogram
(one * designates 20000). Your output must align properly.
*/

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

int main()
{
   int i, j, ary[13] = {};

   cout << "Please enter the random number seed.";
       cin >> j;
   srand(j);

   for (i = 0; i < 10000000; i++)
       ary[die() + die()]++;

   for (i = 2; i <= 12; i++)
   {
       cout << setw(3) << i << " : " << setw(6) << ary[i] << " : ";
       for (j = 0; j < ary[i]; j += 2000)
           cout << "*";
       cout << endl;
   }
   return 0;
}

EXAMPLE OUTPUT: https://i.stack.imgur.com/duxQz.jpg

I know I need to do something with rand() % 6 + 1; in the beginning of the program. I feel like I am close to being complete but missing key points! I also realize I have not defnied die() in my ary[]

austin
  • 3
  • 2
  • About [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)... – Aconcagua Oct 31 '19 at 04:39
  • 1
    Have you forgotten to add the definition of `die` function? – Aconcagua Oct 31 '19 at 04:39
  • `rand()` and modulo gives rather bad distributions, better (provided no overflow occurs) is `rand() * 6 / RAND_MAX`. Additionally, I'd consider *not* adding one for your die values, but instead operate on [0 .. 5]. Then when outputting, you'd iterate over [0 .. 10] and would add 2 to the loop variable to get [2 .. 12] again. You'll safe 999 988 additions that way... – Aconcagua Oct 31 '19 at 04:51
  • Can someone please help my define die() and also insert a rand function – austin Oct 31 '19 at 18:23

1 Answers1

0

I recommend creating random seeds from high precision timers such as std::chrono::high_resolution_clock. Then they are not dependent on the user and are actually random. Create the seed always before calling std::rand.

#include <chrono>

auto time = std::chrono::high_resolution_clock::now();
auto seed = std::chrono::duration_cast<std::chrono::milliseconds>(time);
std::srand(seed)

Millisecond precision makes the seed usually unique enough but if the seed is required close to 1000 times a second then i recommend using nanosecond or microsecond precision to be really random.

Best would be to create a function that creates the random seed using high precision timer and the random value and finally makes sure the return value is between 0 and 5 (for 6 sided dice).

parti82
  • 165
  • 5