iamfazn
iamfazn

Reputation: 21

Generating unique random number is increasing complexity and might cause performance overhead?

Implementation:

private static List<Integer> getRandomDistribution(List<String> unsortedList, int max) {
    Random random = new Random();
    List<Integer> indexContainer = new ArrayList<>();
    for (int i = 0; i < max; i++) {
        int index = random.nextInt(max);
        // Below is what I don't like, 
        if (indexContainer.contains(index)) {
            i--;
        } else {
            indexContainer.add(index);
        }
    }
    return indexContainer;
}

So basically its saying that, until I don't find the required unique random number. I will continue the loop, what could happen is it might keep looping for a long time thus increasing the overhead.

Problems:

NOTE: I will also have to maintain the order within the indexContainer.

Upvotes: 1

Views: 293

Answers (1)

Eran
Eran

Reputation: 393811

Since you are generating a permutation of all the numbers from 0 to max-1, it would make more sense to populate the List with all the numbers from 0 to max-1 and then call Collections.shuffle(list).

Random random = new Random();
List<Integer> indexContainer = new ArrayList<>();
for (int i = 0; i < max; i++) {
    indexContainer.add(i);
}
Collections.shuffle(indexContainer, random);

Upvotes: 4

Related Questions