Search code examples
javaandroidrandomsecure-random

Generating random numbers in a particular range


I am trying to generate n random numbers between 0-31 in my Android code. Below is the code that I am using:

int max_range = 31;
SecureRandom secureRandom = new SecureRandom();
int[] digestCodeIndicesArr = new int[indices_length];
int i = 0, random_temp = 0;

while (i != indices_length-1) {
    random_temp = secureRandom.nextInt(max_range);
    if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp)) {
        digestCodeIndicesArr[i] = random_temp;
        i++;
    }
}

indices_length is the number of random numbers that I need. It's generally 6,7 or 9. But when I print the generated array, I generally end up seeing duplicates. Can someone point out the mistake I am making. I have added the below line of code to filter out random duplicates:

if (!Arrays.asList(digestCodeIndicesArr).contains(random_temp))

Thanks in advance!


Solution

  • Arrays.asList(digestCodeIndicesArr) does not produce a List<Integer> with size() == digestCodeIndicesArr.length.
    It produces a List<int[]> with size() == 1, where first (and only) element is the array.
    As such, it will never contain random_temp, so ! contains() is always true.

    It is bad for performance to constantly create a list and perform a sequential search to check for duplicates. Use a Set instead, that you maintain in parallel with the array, or use a LinkedHashSet first, then convert to array.

    Anyway, this explains why your code wasn't working. The duplicate link that Tunaki had provided and the duplicate link I provided in comment, explains how to actually do what you were trying to do.