-4

I'm trying to generate a random double for this section of my assignment.
The question is "Each week, each female Guppy who is 10 weeks old or older has a 25 percent chance of spawning".

I would like to generate a random double to determine if each female Guppy should spawn or not.

My code so far:

Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
    //?
}
MasterBlaster
  • 948
  • 2
  • 12
  • 26
  • When you look at the methods on `Random`, which method do you think would be best for you to get at 25% probability? And why do you think so? *Hint: Most of the `nextXxx()` methods would be suitable.* – Andreas Jul 11 '16 at 01:49
  • ya thats what i thought, but im really confused on how to input that into coding i reading up on random and next did come up but im confused – Kam Khangura Jul 11 '16 at 01:57

2 Answers2

1

I don't see any reason to generate a random double according to your question. What you need is an integer ranging from 0 to 3 inclusive where each number account for 25% for the spawning.

Random r = new Random();
if (isFemale == true && getAgeInWeeks() >= 10) {
    // Generate a random integer in [0,3]
    // Since there is a 25% or 1/4 chance 
    if(Math.abs(r.nextInt()) % 4 == 1){
       //Note that the 1 in the condition can be replaced by any 
       // integer in [0,3]
       //Put spawning code here 
    }
}

Check out this link for more information on random: Random (Java Platform SE 7

Falla Coulibaly
  • 759
  • 2
  • 11
  • 23
  • 2
    Use `nextInt(4)` instead of `nextInt()` with the modulo operator. The former is correctly random, but the latter is not if Integer.MAX_VALUE is not a multiple of your maximum value. – Erwin Bolwidt Jul 11 '16 at 02:28
1

To generate a random double, you can look at this question, however, this problem can more easily be solved by generating random ints.

In your situation, generating an int between 0 to 3 is what you want because checking if it is 0 will be true 25% of the time (1 Value / 4 Possible values = 25%).

EDIT: If you would like to also generate a random number to see how many spawn a Guppy will have use threadLocalRandomInstance.nextInt(int bound); like before.

These constraints can be translated to code like this:

import java.util.concurrent.ThreadLocalRandom;

public class Test {
    public static void main(String[] args) {        
        ThreadLocalRandom tlr = ThreadLocalRandom.current();

        int num = tlr.nextInt(3 + 1); //Bound is exclusive so add 1.
        int spawn;

        if(num == 0) {
            spawn = tlr.nextInt(100 + 1); //Again, bound is exclusive so add 1.
        } else spawn = 0;

        System.out.println("This guppy had " + spawn + " spawn.");
    }
}

I use ThreadLocalRandom as it is more straightforward as supported by this answer.
If you are not using Java 1.7+, use Random#nextInt(int) instead as also shown by that answer.

Community
  • 1
  • 1
MasterBlaster
  • 948
  • 2
  • 12
  • 26