mercredi 24 février 2016

Should I create my object "Random r" before or in my loop

What I want to know is:
I have a Random object r which is currently being created in the while loop.
And I have 3 places where I could create it.

  1. Right when the main() starts
  2. In the while() loop
  3. In the for() loop

Question is: What are the differences? has any of those any advantage or disadvantage.
Is there a difference in performance? Is the randomness affected?

What I know is that I cannot use r outside of the loop as it stops existing once the loop terminates. So if I want to use r for any other thing it may be required. (right?)

    import java.util.*;

    class test{
    public static void main(String[] args) {

        int numberOfTrue = 0;
        long loopCounter = 0;
        int howManyInts = 20;

        while(numberOfTrue != howManyInts){
            loopCounter += 1;
            numberOfTrue = 0;

            Random r = new Random();

            for(int a = 0; a < howManyInts; a++){       
                if(r.nextBoolean()){
                    numberOfTrue += 1;
                }else{
                   break; 
                }
            }
        }
        System.out.println("It took " + loopCounter + " loops to get " + howManyInts + " random values which are all even.");
    }
}

The program creates "endless" random numbers and if it created howManyInts of 0 in a row it terminates.

EDIT1: Changed the code a little as @Peter Lawrey suggested and changing if(r.nextInt(2) % 2 == 0) to if(r.nextBoolean()) and also renamed some variables to fit the new code

I love to help you help me and I can cope with strong criticism. Don't hold back.




Aucun commentaire:

Enregistrer un commentaire