Java Array of unique randomly generated integers

后端 未结 9 841
再見小時候
再見小時候 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:41

    for (int i = 0; i < size; i++) {
        a[i] = (int)(Math.random()*10);
    
        for (int j = 0; j < i; j++) {
            if (a[i] == a[j]) {
                a[j] = (int)(Math.random()*10); //What's this! Another random number!
            }
        }   
    }
    

    You do find the duplicate values. However, you replace it with another random number that may be a duplicate. Instead, try this:

    for (int i = 0; i < size; i++) {
        a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]
    
        for (int j = 0; j < i; j++) {
            if (a[i] == a[j]) {
                i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again
                break;
            }
        }  
    }
    

    However, this method is inefficient. I recommend making a list of numbers, then randomizing it:

    ArrayList a = new ArrayList<>(11);
    for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive. 
                                   //For 0-9 inclusive, remove the = on the <=
        a.add(i);
    }
    Collections.shuffle(a);
    a = a.sublist(0,4);
    //turn into array
    

    Or you could do this:

    ArrayList list = new ArrayList<>(11);
    for (int i = 0; i <= 10; i++){
        list.add(i);
    }
    int[] a = new int[size];
    for (int count = 0; count < size; count++){
        a[count] = list.remove((int)(Math.random() * list.size()));
    }
    

提交回复
热议问题