Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Boolean Value [closed]

Tags:

c++

random

ctime

I'm trying to generate a random int that is either 0 or 1 in C++. Right now, I receive a 0 every time I run this code, and I'm not sure why. What's the problem here?

#include <ctime> #include <cstdlib>  srand(time(0)); int randomval = rand() % 2; cout << randomval << endl; 
like image 249
Rich Byden Avatar asked Dec 07 '11 21:12

Rich Byden


People also ask

How do you generate a random Boolean in C++?

Until now I used the following code to generate a random bool : bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);

How do you find the random Boolean value?

In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.

What is a random Boolean?

The nextBoolean() method of the Random class is an instance method that generates pseudorandom, uniformly distributed Boolean values. True and false values are generated with approximately equal probability.

How do you randomize a Boolean in JavaScript?

To get a boolean randomly, we can use the JavaScript Math. random() method. The random() method will generate a random float between 0 and 1. We can then put this in an if else condition statement.


2 Answers

I know this is an older question but I believe this answers the question properly.

Don't re-seed the the generator every time you run that code.

By seeding it to the same value every time, you're just gonna get the same "random" number. Remember this is a Pseudo-Random number generator, so based on the seed value, a "random" number will be generated. So if you seed it with the same number every time you're just gonna get the same number every time.

The solution is to call srand(time(NULL)) only once in your program execution. Then, each call to rand() will give you a different number every time.

like image 32
Christian Gossain Avatar answered Sep 23 '22 01:09

Christian Gossain


It is called bad luck. Try it again.

like image 126
Michael Krelin - hacker Avatar answered Sep 23 '22 01:09

Michael Krelin - hacker