Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method that returns true or false at x percentage

Tags:

java

i'm looking for a method that answers randomly true or false by a given percentage Integer. for example:

percent(100); //Will always 100% return true
percent(50); //Will return 50% true, or 50% false
percent(0); //Will always 100% return false, etc..

Here is what I came up with, but for some reason it's not working as it should be:

public static boolean percent(int percentage)
{
    Random rand = new Random();
    return ((rand.nextInt((100-percentage)+1))+percentage)>=percentage;
}

I need a very accurate and real method, please help it's too complicated it's giving me a headache

like image 362
Reacen Avatar asked Nov 29 '22 02:11

Reacen


1 Answers

I believe you are just overthinking it:

return (rand.nextInt(100) < percentage);

Should work fine.

like image 75
NominSim Avatar answered Dec 05 '22 19:12

NominSim