Hi all,
I am writing a program that uses a function that generates a random boolean value using a simple rand() function, seeded with the system time:
bool Game::numGetter ()
{
srand((unsigned)time(0));
int i = rand() % 2;
if (i == 1)
{
return true;
}
else if (i == 0)
{
return false;
}
}
I implemented the function in a for loop, filling a boolean array with the values returned by the function. Each time I run the compiled program, the array is either filled with all trues or all falses. I started debugging to see why this was occurring and realized that, with a breakpoint on this function, the program appeared to fill the array with truly random values. I suppose this is because while I am debugging I wait for a short period of time before I allow the program to continue, thus allowing the system clock to change, while running the program without debugging allows it to run in less then a second (with the same time value throughout). In lieu of forcing the user to tap a key at random intervals to advance the program, how can I make it output values at least as random in the current execution time of the program? Is there something other than time I can use?
Also, Is there another method for flipping a proverbial coin that is more truly random?
#include <iostream>
#include <cstdlib>
#include <time>
usingnamespace std;
int main ()
{
time_t seconds;
time(&seconds);
srand((unsignedint) seconds);
int a=0;
int b=0;
for (int z = 0;z<60000000;z++) {
int r=rand()%2;
if (r==0) {a=a+1;}
if (r==1) {b=b+1;}
}
cout<<"zeros: "<<a<<"\nones: "<<b;
getchar();
}
i was just testing the same thing because the last random tutorial i followed gave me the same problem, trying to do 1-6 at button push and if you hit the button fast enough you get the resulting "random" numbers 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4... but this one works. seems to split just about evenly with a slight lean one way or the other, breaking it down into couting individual flips looks fairly random, even if they all occur within the same milisecond. Hope that helps.
note: with 60 million flips this takes about 5 seconds or so to run.
This runs pretty well. However, my random function is called to return a single boolean within a loop within another function, ergo I can't implement the loop within this function. What can I do to yield similar results considering this?
the loop has nothing to do with it, its just the way the rand() is initialized in this one that makes it actually work compared to the other one i tried that looked more like yours.
i suppose you could if you wanted to, but if they are set up in the main function, then rand is ready for use in any function called afterwards. so if you needed to use it for multiple things you should leave it in main.