Reputation: 674
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?
Upvotes: 8
Views: 5973
Reputation: 575
A nice elegant way to do this, would be to wrap it in a stream like so:
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
Then you can just read off values which fall below your threshold probability as and when you need them...nice if you're wanting to do any kind of comprehension stuff with the output.
Upvotes: 3
Reputation: 60006
This:
math.random < 0.25
will yield true with a 0.25 probability.
Upvotes: 24