samedi 9 avril 2022

Duplicate entries while generating Random number [duplicate]

With the below code if we try to generate random numbers from 1 to 10, I some times get duplicate values.

Below code should generate 5 unique values for random numbers between 1 to 10.

When I print the array it happens uniqueness is not guaranteed. Output was 2,1,9,10,2.

2 was repeated in this case.

        Random random = new Random(System.currentTimeMillis());
        random.setSeed(System.currentTimeMillis());
        int[] myUniqueValues = new int[5];
        for (int i = 0; i < 5; i++) {
            myUniqueValues[i] = random.nextInt(10) + 1;
        }
        return myUniqueValues;



Aucun commentaire:

Enregistrer un commentaire