简体   繁体   中英

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!

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() ! 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.

You need to change:

int[] digestCodeIndicesArr = new int[indices_length];

to:

Integer[] digestCodeIndicesArr = new Integer[indices_length];

because Arrays.asList(digestCodeIndicesArr) is List<int[]> , and not what you thought probably ( List<int> or List<Integer> I guess).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM