mardi 24 novembre 2015

Generating Unique random numbers effectively in Java

I want to generate unique random numbers from range 0 to 999,999.

In order to achieve that, I tried:

ArrayList<Integer> list = new ArrayList<Integer>();

        for (int i = 0; i < 999999; i++) { 
            list.add(new Integer(i)); // Add numbers from 0 - 999,999 into ArrayList
        }

        Collections.shuffle(list); // shuffle them

        for (int i = 0; i < 10; i++) {
            System.out.println(list.get(i)); // printed unique numbers
        }

The problem is the larger the number I want to generate, the longer the time it takes, for the above method, it took about 700ms.

But if I use Random() to generate them without filter duplicate numbers, it only takes 2ms

for(int i = 0; i<10; i++) {
  int digit = 0 + new Random().nextInt((999999 - 0) + 1); 
  System.out.println(digit);
}

Is there other way to generate unique random numbers in a more efficient manner?




Aucun commentaire:

Enregistrer un commentaire