Adding random generated numbers to arrays + averaging those arrays - c++

HW Question: We will simulate the throwing of dice. Again we will use Top-Down_Design to improve the readability, etc.
Generate 20 dice throws of two dies. Each die can generate a number of dots from 1 to 6. Add the two numbers together to get the value of the throw.
In one pass generate the 20 throws and store the numbers in an array.
In a second pass calculate the average of the numbers and display that on the console.
Seed the Random Number Generator with 8193 one time before getting any random numbers.
NOTE : We have not talked about passing a Array to functions. So for this assignment you can make the array of Dice throws global.
//I'm just confused to the concepts of adding the random generated numbers to arrays and then averaging them through the Top Down method.
#include <iostream>
#include <cstdlib>
using namespace std;
void Gen_20_Throws_Of_2_Die_And_Add_Values();
void Output_Avg(); //Calculates the average of the sum of the 20 rolls
int ArraySum[13]; // array for the numbers of 0-12 (13 total). Will ignore index array 0 and 1 later. array[13] = 12
int main()
{
Gen_20_Throws_Of_2_Die_And_Add_Values();
Output_Avg;
cin.get();
return 0;
}
void Gen_20_Throws_Of_2_Die_And_Add_Values()
{
srand(8193); //seed random number generator with 8193
int Dice_Throw_Number, Die1, Die2, Sum_Of_Two_Die;
for (int Dice_Throw_Number = 1; Dice_Throw_Number <= 20; Dice_Throw_Number++)
{
Die1 = (rand() % 6 + 1);
Die2 = (rand() % 6 + 1);
Sum_Of_Two_Die = Die1 + Die2;
ArraySum[Sum_Of_Two_Die] += 1;
}
}
void Output_Avg()
{
int Total_Of_20_Rolls, Average_Of_Rolls;
for (int i = 2; i <= 12; i++) //ignores index of 0 and 1
{
Total_Of_20_Rolls += ArraySum[i];
}
Average_Of_Rolls = Total_Of_20_Rolls / 20;
cout << "The average of 2 die rolled 20 times is " << Average_Of_Rolls;
}

Your code is a little confusing to follow, but I think I understand what's happening. Lets start with your Gen_20_Throws_Of_2_Die_And_Add_Values method.
int Dice_Throw_Number, Die1, Die2, Sum_Of_Two_Die;
for (int Dice_Throw_Number = 1; Dice_Throw_Number <= 20; Dice_Throw_Number++)
{
Die1 = (rand() % 6 + 1);
Die2 = (rand() % 6 + 1);
Sum_Of_Two_Die = Die1 + Die2;
ArraySum[Sum_Of_Two_Die] += 1;
}
You don't need to necessarily initialize int Dice_Throw_Number outside of the for loop. Feel free to make it inside the for loop. Also, I personally always find it easier to understand to start from zero and go up to only a < condition rather than a <=. So you'll have:
int Die1, Die2;
for (int Dice_Throw_Number = 0; Dice_Throw_Number < 20; Dice_Throw_Number++)
{
Die1 = (rand() % 6 + 1);
Die2 = (rand() % 6 + 1);
//increment position of sum by 1
ArraySum[Die1 + Die2] += 1;
}
Now in your Output_Average function, your logic is a lot off. You want to calculate what the average result was of throwing 2 die? Right now you're only adding how many times a certain total came up, not the total itself. So for example if you rolled 12 5 times, you'll adding 5 to the Total_Of_20_Rolls, not 60. That's easy to change, you just need to multiply.
int Total_Of_20_Rolls, Average_Of_Rolls;
for (int i = 2; i < 13; i++) //ignores index of 0 and 1
{
Total_Of_20_Rolls += ArraySum[i] * i;
}
Average_Of_Rolls = Total_Of_20_Rolls / 20;
cout << "The average of 2 die rolled 20 times is " << Average_Of_Rolls;
That should help you out!

Related

How to generate a 4-digit numbers with digits from 1 to 6 only?

I'm looking for a way to generate a 4 digit number with digits from 1 to 6 like 1234, 1251, 3243 ... and so on.
I want it for my makeDigitsToGuess() method in my MastermindDigits class. Every time a user starts the game, this function should be called and generate a 4 digit number containing only digits from 1 to 6.
This is what I've tried so far:
srand(time(0));
cout << "RANDOM NUMBER: " << (rand() % 6 + 1)
<< (rand() % 6 + 1)
<< (rand() % 6 + 1)
<< (rand() % 6 + 1) << endl;
this is how far I got on my own. The next step I was thinking about, was to create a vector in my method where I could push_back those 4x generated random numbers.
Does this make sense? Is there an easier way to code it?
I suggest this solution using the C++11's std::uniform_int_distribution.
#include <iostream>
#include <random>
#include <iomanip>
int generateFour()
{
int result=0;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 6);
for (int n=0; n<4; ++n)
{
result=result*10+dis(gen);
}
return result;
}
int main()
{
std::cout << std::setfill('0') << std::setw(4)
<< generateFour() << std::endl;
return 0;
}
You're basically generating a number in base 6, except you replace digit "0" by "6". (Or alternatively add 1 to all). Since it's a 4 digit number, there are 6*6*6*6 possibilities = 1296. So generate a number in the range [0, 1296) and print that in base 6.
const unsigned sup(6 * 6 * 6 * 6);
unsigned base6[sup];
for (unsigned i(0); i < sup; ++i)
{
base6[i] = (i / 216 % 6) * 1000 +
(i / 36 % 6) * 100 +
(i / 6 % 6) * 10 +
i % 6;
}
then your random number is base6[rand() % sup].
Why not make this easy, practically as you did in question.
std::string number;
for(int i = 0; i < 4; i++) {
number += rand() % 6 + 1;
}
std::cout << std::stoi(number);
I didn't test this code, but its the basic idea. You put everything into a string and convert it to a number. Perhaps not the best idea, but at least better than doing 4 times rand() :)
unsigned result = 0;
while(!(result / 1000)) /// while "result" doesn't consist of 4 digits
{
result = result * 10 + rand() % 6 + 1; // multiply previous result by 10, then add new digit.
}
I assume you have the same task as me (PAD2) so i can help you.
This is my function makeDigitsToGuess:
int randomNumber = 0;
int x = 3; //Numbers to guess
for (int i = 0; i <= x; i++) {
randomNumber = rand() % 6 + 1;
digits[i] = randomNumber;
}
This gives me a four digit number for the play mode.

I tried coding my own simple moving average in C++

I want a function that works.
I believe my logic is correct, thus my (vector out of range error) must be coming from the lack of familiarity and using the code correctly.
I do know that there is long code out there for this fairly simple algorithm.
Please help if you can.
Basically, I take the length as the "moving" window as it loops through j to the end of the size of the vector. This vector is filled with stock prices.
If the length equaled 2 for a 2 day moving average for numbers 1 2 3 4. I should be able to output 1.5, 2.5, and 3.5. However, I get an out of range error.
The logic is shown in the code. If an expert could help me with this simple moving average function that I am trying to create that would be great! Thanks.
void Analysis::SMA()
{
double length;
cout << "Enter number days for your Simple Moving Average:" << endl;
cin >> length;
double sum = 0;
double a;
while (length >= 2){
vector<double>::iterator it;
for (int j = 0; j < close.size(); j++){
sum = vector1[length + j - 1] + vector1[length + j - 2];
a = sum / length;
vector2.push_back(a);
vector<double>::iterator g;
for (g = vector2.begin(); g != vector2.end(); ++g){
cout << "Your SMA: " << *g;
}
}
}
}
You don't need 3 loops to calculate a moving average over an array of data, you only need 1. You iterate over the array and keep track of the sum of the last n items, and then just adjust it for each new value, adding one value and removing one each time.
For example suppose you have a data set:
4 8 1 6 9
and you want to calculate a moving average with a window size of 3, then you keep a running total like this:
iteration add subtract running-total output average
0 4 - 4 - (not enough values yet)
1 8 - 12 -
2 1 - 13 13 / 3
3 6 4 15 15 / 3
4 9 8 16 16 / 3
Notice that we add each time, we start subtracting at iteration 3 (for a window size of 3) and start outputting the average at iteration 2 (window size minus 1).
So the code will be something like this:
double runningTotal = 0.0;
int windowSize = 3;
for(int i = 0; i < length; i++)
{
runningTotal += array[i]; // add
if(i >= windowSize)
runningTotal -= array[i - windowSize]; // subtract
if(i >= (windowSize - 1)) // output moving average
cout << "Your SMA: " << runningTotal / (double)windowSize;
}
You can adapt this to use your vector data structure.
Within your outermost while loop you never change length so your function will run forever.
Then, notice that if length is two and closes.size() is four, length + j - 1 will be 5, so my psychic debugging skills tell me your vector1 is too short and you index off the end.
This question has been answered but I thought I'd post complete code for people in the future seeking information.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<double> vector1 { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
double length;
cout << "Enter number days for your Simple Moving Average:" << endl;
cin >> length;
double sum = 0;
int cnt = 0;
for (int i = 0; i < vector1.size(); i++) {
sum += vector1[i];
cnt++;
if (cnt >= length) {
cout << "Your SMA: " << (sum / (double) length) << endl;
sum -= vector1[cnt - length];
}
}
return 0;
}
This is slightly different than the answer. A 'cnt' variable in introduced to avoid an additional if statement.

How to make Random Numbers unique

I am making a random number generator. It asks how many digits the user wants to be in the number. for example it they enter 2 it will generate random numbers between 10 and 99. I have made the generator but my issue is that the numbers are not unique.
Here is my code. I am not sure why it is not generating unique number. I thought srand(time(null)) would do it.
void TargetGen::randomNumberGen()
{
srand (time(NULL));
if (intLength == 1)
{
for (int i = 0; i< intQuantity; i++)
{
int min = 1;
int max = 9;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
else if (intLength == 2)
{
for (int i = 0; i<intQuantity; i++)
{
int min = 10;
int max = 90;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
if (intLength == 3)
{
for (int i = 0; i<intQuantity; i++)
{
int min = 100;
int max = 900;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
else if (intLength == 4)
{
for (int i = 0; i<intQuantity; i++)
{
int min = 1000;
int max = 9000;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
if (intLength == 5)
{
for (int i = 0; i<intQuantity; i++)
{
int min = 10000;
int max = 90000;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
else if (intLength == 6)
{
for (int i = 0; i<intQuantity; i++)
{
int min = 100000;
int max = 900000;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
if (intLength == 7)
{
for (int i = 0; i<intQuantity; i++)
{
int min = 1000000;
int max = 9000000;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
else if (intLength == 8)
{
for (int i = 0; i <intQuantity; i++)
{
int min = 10000000;
int max = 89999999;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
if (intLength == 9)
{
for (int i = 0; i < intQuantity; i++)
{
int min = 100000000;
int max = 900000000;
int number1 = rand();
if (intQuantity > max)
{
intQuantity = max;
}
cout << number1 % max + min << "\t";
}
}
}
Okay so I thought I figured out a way to do this without arrays but It isn't working before I switch to the fisher yates method. Can someone tell me why this isn't working? It is supposed to essentially take the random number put that into variable numGen. Then in variable b = to numgen. Just to hold what numGen used to be so when the loop goes through and generates another random number it will compare it to what the old number is and if it is not equal to it, then it will output it. If it is equal to the old number than rather than outputting it, it will deincrement i so that it will run through the loop without skipping over the number entirely. However, when I do this is infinitely loops. And I am not sure why.
if (intLength == 1)
{
for (int i = 0; i< intQuantity; ++i)
{
int min = 1;
int max = 9;
int number1 = rand();
int numGen = number1 % max + min;
if (intQuantity > max)
{
intQuantity = max;
}
for (int k = 0; k < 1; k++)
{
cout << numGen << "\t";
int b = numGen;
}
int b = numGen;
if (b != numGen )
{
cout << numGen << "\t";
}
else
{
i--;
}
}
}
Everyone has interesting expectations for random numbers -- apparently, you expect random numbers to be unique! If you use any good random number generator, your random numbers will never be guaranteed to be unique.
To make this most obvious, if you wanted to generate random numbers in the range [1, 2], and you were to generate two numbers, you would (normally expect to) get one of the following four possibilities with equal probability:
1, 2
2, 1
1, 1
2, 2
It does not make sense to ask a good random number generator to generate the first two, but not the last two.
Now, take a second to think what to expect if you asked to generate three numbers in the same range... 1, 2, then what??
Uniqueness, therefore, is not, and will not be a property of a random number generator.
Your specific problem may require uniqueness, though. In this case, you need to do some additional work to ensure uniqueness.
One way is to keep a tab on which numbers are already picked. You can keep them in a set, and re-pick if you get one you got earlier. However, this is effective only if you pick a small set of numbers compared to your range; if you pick most of the range, the end of the process gets ineffective.
If the number count you are going to pick corresponds to most of the range, then using an array of the range, and the using a good shuffling algorithm to shuffle the numbers around is a better solution. (The Fisher-Yates shuffle should do the trick.)
Hint 0:
Use Quadratic residue from number theory; an integer q is called a quadratic residue modulo p if it is congruent to a perfect square modulo p; i.e., if there exists an integer x such that:
x2 ≡ q (mod p)
Hint 1:
Theorem: Assuming p is a prime number, the quadratic residue of x is unique as long as 2x < p. For example:
02 ≡ 0 (mod 13)
12 ≡ 1 (mod 13)
22 ≡ 4 (mod 13)
32 ≡ 9 (mod 13)
42 ≡ 3 (mod 13)
52 ≡ 12 (mod 13)
62 ≡ 10 (mod 13)
Hint 2:
Theorem: Assuming p is a prime number such that p ≡ 3 (mod 4), not only x2%p (i.e the quadratic residue) is unique for 2x < p but p - x2%p is also unique for 2x>p. For example:
02%11 = 0
12%11 = 1
22%11 = 4
32%11 = 9
42%11 = 5
52%11 = 3
11 - 62%11 = 8
11 - 72%11 = 6
11 - 82%11 = 2
11 - 92%11 = 7
11 - 102%11 = 10
Thus, this method provides us with a perfect 1-to-1 permutation on the integers less than p, where p can be any prime such that p ≡ 3 (mod 4).
Hint 3:
unsigned int UniqueRandomMapping(unsigned int x)
{
const unsigned int p = 11; //any prime number satisfying p ≡ 3 (mod 4)
unsigned int r = ((unsigned long long) x * x) % p;
if (x <= p / 2) return r;
else return p - r;
}
I didn't worry about the bad input numbers (e.g. out of the range).
Remarks
For 32-bit integers, you may choose the largest prime number such that p ≡ 3 (mod 4) which is less than 232 which is 4294967291.
Even though, this method gives you a 1-to-1 mapping for generating random number, it suffers from the clustering issue.
To improve the randomness of the aforementioned method, combine it with
other unique random mapping methods such as XOR operator.
I'll assume you can come up with a way to figure out how many numbers you want to use. It's pretty simple, since a user input of 2 goes to 10-99, 3 is 100-999, etc.
If you want to come up with your own implementation of unique, randomly generated numbers, check out these links.
http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
Here is a very similar implementation: https://stackoverflow.com/a/196065/2142219
In essence, you're creating an array of X integers, all set to the value of their index. You randomly select an index between 0 and MAX, taking the value at this index and swapping it with the max value. MAX is then decremented by 1 and you can repeat it by randomly selecting an index between 0 and MAX - 1.
This gives you a random array of 0-999 integers with no duplicates.
Here are two possible approaches to generating unique random numbers in a range.
Keep track of which numbers you have already generated using std::set, and throw away and regenerate numbers as long as they are already in the set. This approach is not recommended if you want to generate a large number of random numbers, due to the birthday paradox.
Generate all numbers in your given range, take a random permutation of them, and output however many the user wants.
Standard random generators would never generate unique numbers, in this case they would Not be independent.
To generate unique numbers you have to:
Save all number generated and compare new one with old ones, if there is coincidence - regenerate.
or
Use random_shuffle function: http://en.cppreference.com/w/cpp/algorithm/random_shuffle to get all sequence in advance.
Firstly, srand()/rand() commonly have a period of 2^32, which means that after calling srand(), rand() will internally iterate over distinct integers during the first 2^32 calls to rand(). Still, rand() may well return a result with less than 32 bits: such as an int between 0 and RAND_MAX where RAND_MAX is 2^31-1 or 2^15-1, so you may see repeated results as the caller of rand(). You probably read about the period though, or somebody's comment made with awareness of that, and somehow it's been mistaken as uniqueness....
Secondly, given any call to rand() generates a number far larger than you want, and you're doing this...
number1 % max
The result of "number1 % max" is in the range 0 <= N <= max, but the random number itself may have been any multiple of max greater than that. In other words, two distinct random numbers that differ by a multiple of max still produce the same result for number1 % max in your program.
To get distinct random numbers within a range, you could prepopulate a std::vector with all the numbers, then std::shuffle them.

Birthday paradox for statement/calcutions

Apparently I was actually suppose to create an array that randomly assigns birthdays over many trials (5000). It's then suppose to count up each time there is at least 2 birthdays for 2 - 50 people and divide the outcome by 5,000 to get the approximate probability. I believe I have my loops messed up and would like some feedback. Not code, I would like to understand exactly what is going wrong and how I messed it up.
int main()
{
const int trials(5000);
double total;
int count(0), birthdays[49];
srand(time(NULL));
for (int i = 2; i <= 50; i++)
{
for (int k = 0; k < trials; k++)
{
fillUp(birthdays, 49);
for (int j = i + 1; j <= 50; j++)
{
if (birthdays[i] == birthdays[j])
{
count += 1;
}
}
}
total = count / 5000.0;
cout << "For " << i << " the probability is " << total << endl;
}
return 0;
}
void fillUp(int birthdays [], int size)
{
for (int i = 0; i < size; i++)
{
birthdays[i] = rand() % 365 + 1;
}
}
Output:
For 2 the probability is 0.1286
For 3 the probability is 0.2604
...
...
For 49 the probability is 3.9424
For 50 the probability is 3.9424
Any help would be really appreciated.
The problem isn't the C++ code; you just have a typo in your math. It should be:
power = (num * (num - 1.0) / 2.0);
chance = 1.0 - pow(constant, power);
You are calculating 364/365 &approx; 0.0027 to the power of some large number, which results in a number only very slightly above zero. When rounded to the requested output precision, this results in zero.
You may know the formula, but your code is not implementing it correctly. Here is some C code that implements the formula correctly:
#include <stdio.h>
int main(void) {
double p;
int ii;
int people;
for (people = 3; people < 50; people++) {
p = 1;
for (ii = 1; ii < people; ii++) {
p *= (365.0 - ii) / 365.0;
}
printf("for %d people, probability is %.4f\n", people, 1 - p);
}
return 0;
}
This results in the following output:
for 1 people, probability is 0.0000
for 2 people, probability is 0.0027
for 3 people, probability is 0.0082
for 4 people, probability is 0.0164
for 5 people, probability is 0.0271
for 6 people, probability is 0.0405
for 7 people, probability is 0.0562
for 8 people, probability is 0.0743
for 9 people, probability is 0.0946
for 10 people, probability is 0.1169
for 11 people, probability is 0.1411
for 12 people, probability is 0.1670
for 13 people, probability is 0.1944
for 14 people, probability is 0.2231
for 15 people, probability is 0.2529
for 16 people, probability is 0.2836
for 17 people, probability is 0.3150
for 18 people, probability is 0.3469
for 19 people, probability is 0.3791
for 20 people, probability is 0.4114
for 21 people, probability is 0.4437
for 22 people, probability is 0.4757
for 23 people, probability is 0.5073
for 24 people, probability is 0.5383
for 25 people, probability is 0.5687
for 26 people, probability is 0.5982
for 27 people, probability is 0.6269
for 28 people, probability is 0.6545
for 29 people, probability is 0.6810
Leading to the familiar result that "the chance is > 50% with just 23 people".
In essence you have created a new question, so I will create a new answer. Right now you keep changing the birthdays while you are looping over them; this is why things don't work. You need two nested loops to test for equal birthdays (or if you are smart you sort them, then only check adjacent ones. It is probably faster with n = 50.)
You also need to start testing at the first birthday (your array is base 0 - but you start with i = 2). And for each trial, you can see how many people you need to compare before you have a match. The correct code will look something like this (note that I run 5000 trials for each number of people in the room; you could be more efficient by checking for a match when you have 3,4,5... people based on the same sample, but then there would be some correlation in the sampling).
EDITED - tested this code, seems to compile and run OK. Results look close to expected values.
#include <iostream>
void fillUp(int birthdays [], int size)
{
for (int i = 0; i < size; i++)
{
birthdays[i] = rand() % 365 + 1;
}
}
int main(void) {
int birthdays[50];
int trials = 5000;
int flag;
double total;
int collisions[50];
// number of people "in the room"
for (int i = 2; i < 50; i++)
{
collisions[i] = 0;
// do 5000 trials:
for (int t = 0; t < trials; t++)
{
fillUp(birthdays, i);
flag = 0;
// compare all pairs (j,k):
for (int j = 0; j < i - 1 && flag == 0; j++)
{
for (int k = j + 1; k < i && flag == 0; k++ )
{
if (birthdays[k] == birthdays[j])
{
collisions[i]++;
flag = 1;
}
}
}
}
total = collisions[i] / 5000.0;
std::cout << "For " << i << " people in the room the probability is " << total << std::endl;
}
return 0;
}
Note - I did not have a chance to compile / test this; it should be right "in essence". Let me know if it gives a problem.

Code to generate random numbers in C++

Basically I have to write a program to generate random numbers to simulate the rolling of a pair of dice. This program should be constructed in multiple files. The main function should be in one file, the other functions should be in a second source file, and their prototypes should be in a header file. First I write a short function that returns a random value between 1 and 6 to simulate the rolling of a single 6-sided die.Second, i write a function that pretends to roll a pair of dice by calling this function twice.
My program starts by asking the user how many rolls should be made. Then I write a function to simulate rolling the dice this many times, keeping a count of exactly how many times the values 2,3,4,5,6,7,8,9,10,11,12(each number is the sum of a pair of dice) occur in an array. Later I write a function to display a small bar chart using these counts that ideally would look something like below for a sample of 144 rolls, where the number of asterisks printed corresponds to the count:
2 3 4 5 6 7 8 9 10 11 12
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * *
Next, to see how well the random number generator is doing, I write a function to compute the average value rolled. Compare this to the ideal average of 7. Also, print out a small table showing the counts of each roll made by the program, the ideal count based on the frequencies above given the total number of rolls, and the difference between these values in separate columns. This is my incomplete code so far:
"Compiler visual studio 2010"
int rolling(){ //Function that returns a random value between 1 and 6
rand(unsigned(time(NULL)));
int dice = 1 + (rand() %6);
return dice;
}
int roll_dice(int num1,int num2){ //it calls 'rolling function' twice
int result1,result2;
num1 = rolling();
num2 = rolling();
result1 = num1;
result2 = num2;
return result1,result2;
}
int main(void){
int times,i,sum,n1,n2;
int c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11;//counters for each sum
printf("Please enter how many times you want to roll the dice.\n")
scanf_s("%i",&times);
I pretend to use counters to count each sum and store the number(the count) in an array. I know i need a loop (for) and some conditional statements (if) but m main problem is to get the values from roll_dice and store them in n1 and n2 so then i can sum them up and store the sum in 'sum'.
You could use the library if you can use C++11.
From the page:
uniform_int_distribution<int> one_to_six {1,6}; // distribution that maps to the ints 1..6
default_random_engine re {}; // the default engine
int x = one_to_six(re); // x becomes a value in [1:6]
You cold seed with a quickly moving time value.
std::chrono::time_point<std::chrono::system_clock>
now {std::chrono::system_clock::now()};
std::chrono::system_clock::duration
epoch {now.time_since_epoch()};
typedef std::chrono::duration<unsigned long long int, std::milli> ms;
std::default_random_engine re {std::chrono::duration_cast<ms>(epoch).count()};
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int RollDice()
{
return rand() % 6 + 1;
}
int main()
{
int times, i, cont;
int count[11];
srand(time(NULL));
printf("Please enter how many times you want to roll the dice: ");
scanf("%i", &times);
if (times <= 0)
{
fprintf(stderr, "Invalid value.\n");
return -1;
}
for (i = 0; i < 11; i++)
{
count[i] = 0;
}
for (i = 0; i < times; i++)
{
int result = RollDice() + RollDice();
if (result < 2 || result > 12)
{
fprintf(stderr, "something goes wrong\n");
return -1;
}
++count[result - 2];
}
for (i = 2; i <= 12; i++)
{
printf("%3d", i);
}
printf("\n");
while (1)
{
cont = 0;
for (i = 0; i < 11; i++)
{
printf(" %c", (count[i] > 0) ? '*' : ' ');
if (count[i] > 0)
{
if (--count[i] > 0)
{
cont = 1;
}
}
}
printf("\n");
if (!cont)
{
break;
}
}
return 0;
}
Make a function for rolling the dices and returns the sum.
int Roll(int numberOfTimes)
{
int temp = numberOfTimes;
int sum = 0;
int dice1 = 0;
int dice2 = 0;
for (int i = 0; < temp; i++)
{
dice1 = 1 + (rand() % 6);
dice2 = 1 + (rand() % 6);
sum = dice1 + dice2;
}
return sum;
}
I have not tested this but it might help.