Java Array of unique randomly generated integers

后端 未结 9 843
再見小時候
再見小時候 2020-11-28 16:06
public static int[] uniqueRandomElements (int size) {

    int[] a = new int[size];

    for (int i = 0; i < size; i++) {
        a[i] = (int)(Math.random()*10);
         


        
9条回答
  •  醉酒成梦
    2020-11-28 16:39

    If you have a duplicate you only regenerate the corresponding number once. But it might create another duplicate. You duplicate checking code should be enclosed in a loop:

    while (true) {
        boolean need_to_break = true;
        for (int j = 0; j < i; j++) {
            if (a[i] == a[j]) {
                need_to_break = false; // we might get another conflict
                a[j] = (int)(Math.random()*10);
            }
        }
        if (need_to_break) break;
    }   
    

    But make sure that size is less than 10, otherwise you will get an infinite loop.

    Edit: while the above method solves the problem, it is not efficient and should not be used for large sized arrays. Also, this doesn't have a guaranteed upper bound on the number of iterations needed to finish.

    A better solution (which unfortunately only solves second point) might be to generate a sequence of the distinct numbers you want to generate (the 10 numbers), randomly permute this sequence and then select only the first size elements of that sequence and copy them to your array. You'll trade some space for a guarantee on the time bounds.

    int max_number = 10;
    int[] all_numbers = new int[max_number];
    for (int i = 0; i < max_number; i++)
        all_numbers[i] = i;
    
    /* randomly permute the sequence */
    for (int i = max_number - 1; i >= 0; i--) {
        int j = (int)(Math.random() * i); /* pick a random number up to i */
    
        /* interchange the last element with the picked-up index */
        int tmp = all_numbers[j];
        all_numbers[j] = a[i];
        all_numbers[i] = tmp;
    }
    
    /* get the a array */
    for (int i = 0; i < size; i++)
        a[i] = all_numbers[i];
    

    Or, you can create an ArrayList with the same numbers and instead of the middle loop you can call Collections.shuffle() on it. Then you'd still need the third loop to get elements into a.

提交回复
热议问题