Java Array of unique randomly generated integers

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

        int[] a = new int [size];
    
        for (int i = 0; i < size; i++) 
        {
            a[i] = (int)(Math.random()*16); //numbers from 0-15
            for (int j = 0; j < i; j++) 
            {
                //Instead of the if, while verifies that all the elements are different with the help of j=0
                while (a[i] == a[j])
                {
                    a[i] = (int)(Math.random()*16); //numbers from 0-15
                    j=0;
                }
            }
        }
    
        for (int i = 0; i < a.length; i++)
        {
            System.out.println(i + ".   " + a[i]);
        }
    

提交回复
热议问题