Random Boolean Generator

Is there a method that allows me to generate a boolean based on some percentages?

For example, I need a generator that has a 25% chance of giving me false information.

Now I am doing:

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

I do this to get my “25%” chance of failure, but I'm not sure if this is the right way, and I’m sure there is a better way.

Can someone direct me where to look or how to do it?

+4
source share
2 answers

It:

math.random < 0.25

will give true with a probability of 0.25.

+17
source

A good elegant way to do this would be to wrap it in a stream as follows:

scala> def booleanStream(p : Double) : Stream[Boolean] = (math.random < p) #::    booleanStream(p)
booleanStream: (p: Double)Stream[Boolean]

scala> booleanStream(0.25) take 25 foreach println
false
false
false
true
false
false
true
false
false
false
true
false
false
false
false
false
false
false
false
false
false
false
false
false
false

, , ... , - .

+3

All Articles