Java Array of unique randomly generated integers

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

    It might work out faster to start with a sequential array and shuffle it. Then they will all be unique by definition.

    Take a look at Random shuffling of an array, and at the Collections.shuffle function.

    int [] arr = [1,2,3,.....(size)]; //this is pseudo code
    
    Collections.shuffle(arr);// you probably need to convert it to list first
    

提交回复
热议问题