Reacen
Reacen

Reputation: 2370

Method that returns true or false at x percentage

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

Upvotes: 5

Views: 6453

Answers (4)

Nidis
Nidis

Reputation: 145

It should be easy enough if you pick up a random number between 1-100. For example 55 for the case percent(50) this will be false if you assume that the number between 1-50 are true and the rest are false. Given the fact that you accept that rand() is totally random this shoud solve your problem.

So
if (random_num >= percent) changed
return true;
else
return false;

Upvotes: 0

BlackVegetable
BlackVegetable

Reputation: 13064

I would break it into smaller pieces to understand:

public boolean rollDie(int percentGiven)
{
  Random rand = new Random();
  int roll = rand.nextInt(100);
  if(roll < percentGiven)
    return true;
  else
    return false;
}

Frequently, naming conventions and breaking code across more lines (instead of many method calls stacked in a single line) can make it easier to solve problems. Here I am using explicit names that make it easy to read. This is good for beginners like me that do not do well interpreting very compact code.

Upvotes: 6

NominSim
NominSim

Reputation: 8511

I believe you are just overthinking it:

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

Should work fine.

Upvotes: 17

Pshemo
Pshemo

Reputation: 124275

public boolean percent(int p){
    Random r=new Random();
    return r.nextInt(100)<p;
}

Upvotes: 4

Related Questions