Sunday, March 1, 2020

Generate random numbers without repetition

Instead of controlling the repetition by inserting the already-generated-number in a set, create the set first, pick from there, and remove it for the next iteration,

e.g.:


import java.util.Random;

public class ControlRepetitionWithoutKeepingScore {

     public static void main(String []args) {

         int choices[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
         int sz = choices.length;
         Random random = new Random();
         
         for(int i = 0; i < choices.length; i++ ) {
             int pos = random.nextInt(sz);
             print(choices[pos]);
             
             choices[pos] = choices[sz-1];
             sz--;
         }
     }
}


Other entries:

No comments:

Post a Comment