Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random boolean generator

Tags:

scala

is there a method which allows me to generate a boolean based on some percentages?

For example I need a generator which has a 25% chance of giving me false.

Right now I am doing :

val rand = new Random()
val a = List(true,true,true,false)
val isFailure = a(rand.nextInt(4))

I am doing this to get my "25%" chance of failure but I am not sure if this is the correct way and I am pretty sure there is a better way.

Can someone guide me on where to look or how to do it?

like image 891
K. L. Avatar asked Nov 16 '13 12:11

K. L.


People also ask

How do you generate a boolean randomly?

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 generate a random boolean in C ++?

The best way to generate random bool is to use the MSB bit. This is actually a standard Bernoulli distribution with probability 1/2 . Save this answer.

How do you generate a random boolean in Python?

Use random. getrandbits() to get a random boolean value Call random. getrandbits(k) with k set to 1 to get a single random bit. A bit is either 0 (representing False ) or 1 (representing True ). Use bool() to convert the random bit into a bool.

How do you randomize true or false in C#?

If you want to create a random boolean, use this code: var random = new Random(); var randomBool = random.


1 Answers

This:

math.random < 0.25

will yield true with a 0.25 probability.

like image 145
Jean-Philippe Pellet Avatar answered Oct 24 '22 06:10

Jean-Philippe Pellet