Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to generate some random booleans. However I need to be able to specify the probability of returning true. As a results doing:

private Random random = new Random();
random.nextBoolean();

will not work.

One possible solution would be:

private Random random = new Random()

public boolean getRandomBoolean(float p){
    return random.nextFloat() < p;
}

I was wondering if there is a better or more natural way of doing this.

EDIT: I guess I am asking whether there is a library class that provides a nextBoolean(float probability) method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
492 views
Welcome To Ask or Share your Answers For Others

1 Answer

I was wondering if there is a better or more natural way of doing this.

The approach you're using already is fine.

* As far as I know, there's not a standard Java method that will make this code any shorter.


* For non-cryptographic purposes.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...