0

Having an array of numbers I want to randomly pick every index of it with a random generator. What is the best practise for the random generator to avoid useless loops on indexes that have already selected? So far I use an ArrayList tho store the already selected ones but I feel that in the end this algorithm will have many wasted loops in the end. Here is the code:

Random r = new Random();
ArrayList<Integer> found = new ArrayList<Integer>();
while(notAllPassed){
   int prediction = r.nextInt(sizeOfArray);
   if(!found.contains(prediction){
      found.Add(prediction);
      //Do stuff
   }
}
i_ll_be_back
  • 317
  • 1
  • 14

3 Answers3

4

The idea is, instead of choosing a random index each time, to prepare a shuffled list of all indices and just iterate over it in order.

List<Integer> indices = IntStream.range(0, sizeOfArray).boxed().collect(toList());
Collections.shuffle(indices);
for (int randomIndex : indices) {
   // do your thing
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

Instead of checking if you have things already generated, approach it differently. Create an array of all possible values and then shuffle the array randomly.

You can utilize built-in method java.util.Collection.shuffle(List)

For the initial list, order doesn't matter, but it is easiest to just fill it with 0..n-1 or 1..n values one after another. Doing it in more complex way is not helping in any way, as shuffle is anyway fully random.

Artur Biesiadowski
  • 3,595
  • 2
  • 13
  • 18
0

Marko Topolnik is absolutly right with his answer. Thats the best way to do it.

So my answer is just for the sake of completion, following your initial idea with Random

    Random r = new Random();                      // as you had it
    ArrayList<Integer> found = new ArrayList<>(); // as you had it

    for(int i = 0; i < sizeOfArray; i++){         // if you want ALL possible indexes 
        int prediction = r.nextInt(sizeOfArray);  // exactly as you did it
        while(found.contains(prediction)){        // here we check if the "found" list already contains the random index
            prediction = r.nextInt(sizeOfArray);  // if so, regenerate the "prediction" until one is generated that is not in the list
        }
        found.add(prediction);                    // this statement will only be reached after the while loop found an index that is not in the list
    }

    System.out.println(found.toString());         // convenience: print the list to see for yourself 

As I said, this is just following your initial idea to use random. I would have done it this way, if there was no Collection.shuffle() :)

Community
  • 1
  • 1
GameDroids
  • 5,584
  • 6
  • 40
  • 59