0

How would I go about implementing a 3/4 or 75% probability using this format in java?

Random rand = new Random();
boolean val = rand.nextInt(25)==0;
Pentrophy
  • 79
  • 1
  • 3
  • 2
    I think that would be nextInt(4). – Hot Licks Nov 16 '14 at 03:36
  • 2
    it has to be nextInt(4), that returns 0 with 25% chance, 1 with 25% chance, 2 with 25% chance, 3 with 25% chance. Then check that the value is one of three of those or that it is not one of those. – marcelv3612 Nov 16 '14 at 03:42
  • 1
    Welcome to Stack Overflow! I'm not sure why you're getting so many downvotes; this seems to me like a pretty clear question, and you've already received a few answers. Perhaps the downvoters will explain themselves. – Christian Conkle Nov 16 '14 at 03:51
  • 1
    @ChristianConkle I guess they have downvoted due to the lack of research effort. Or maybe because he "borrowed" his code from [here](http://stackoverflow.com/questions/8183840/probability-in-java#8183867) without saying so or with trying to understand that code and changing it accordingly. But I'm just guessing. – Tom Nov 16 '14 at 04:16

4 Answers4

7

Something like this,

Random rand = new Random();
int val = rand.nextInt(4) + 1;
if (val == 1) { // <-- 1/4 of the time.
} else { // <-- 3/4 of the time.
}

Random.nextInt(int) returns Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive). So, to 0-4 (exclusive) is (0-3) and if you then add 1 the result is the range (1-4).

You might also use Random.nextDouble() like,

if (rand.nextDouble() < 0.75) { // <-- 75% of the time.
}
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
6

A simple-minded way to do it that is good for any integer percent is:

boolean val = rand.nextInt(100) < 75;
Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • 1
    I'd might be wrong, but shouldn't this be `(rand.nextInt(100) + 1) < 75;`? The range from `0-99` might change the 75% chance a bit. – Tom Nov 16 '14 at 03:42
  • @Tom - What if you want 1%? Or 100%? Think about it. – Hot Licks Nov 16 '14 at 03:44
1

Try this :

rand.nextInt(4) < 3
Eric
  • 19,525
  • 19
  • 84
  • 147
1

The following is also valid and somewhat intuitive since many people share the notion of probability as being a value between 0 and 1:

Math.random() < 0.75

Of course, this is the same as

Random rand = new Random();
rand.nextDouble() < 0.75

which has been mentioned in the accepted answer.

One important point to note though is that the latter is more efficient than the former. Pete provides an explanation of why this the case on Oracle's community forum.