Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return True or False Randomly

I need to create a Java method to return true or false randomly. How can I do this?

like image 401
Bishan Avatar asked Jan 16 '12 09:01

Bishan


People also ask

How do you randomly pick true or false in Java?

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.

How do you randomize true or false in Python?

The random. random() function generated a random floating number between 0 and 1. The generated number is compared with 0 by using the if() function. If the generated number is greater than 0, the used method will return True as output, else it will return False.

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 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);


2 Answers

The class java.util.Random already has this functionality:

public boolean getRandomBoolean() {     Random random = new Random();     return random.nextBoolean(); } 

However, it's not efficient to always create a new Random instance each time you need a random boolean. Instead, create a attribute of type Random in your class that needs the random boolean, then use that instance for each new random booleans:

public class YourClass {      /* Oher stuff here */      private Random random;      public YourClass() {         // ...         random = new Random();     }      public boolean getRandomBoolean() {         return random.nextBoolean();     }      /* More stuff here */  } 
like image 85
buc Avatar answered Sep 20 '22 23:09

buc


(Math.random() < 0.5) returns true or false randomly

like image 44
Hachi Avatar answered Sep 21 '22 23:09

Hachi