Java Array of unique randomly generated integers

后端 未结 9 715
再見小時候
再見小時候 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:46
     import java.util.Scanner;
     class Unique
    {
    public static void main(String[]args)
    {
        int i,j;
        Scanner in=new Scanner(System.in);
        int[] a=new int[10];
        System.out.println("Here's a unique no.!!!!!!");
        for(i=0;i<10;i++)
        {
            a[i]=(int)(Math.random()*10);
            for(j=0;j<i;j++)
            {
                if(a[i]==a[j])
                {
                    i--;
    
                }
            }   
        }
        for(i=0;i<10;i++)
        {
            System.out.print(a[i]);
        }
    }
    }
    
    0 讨论(0)
  • 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]);
        }
    
    0 讨论(0)
  • 2020-11-28 16:52
    int[] a = new int[20];
    
    for (int i = 0; i < size; i++) {
        a[i] = (int) (Math.random() * 20);
    
        for (int j = 0; j < i; j++) {
            if (a[i] == a[j]) {
                a[i] = (int) (Math.random() * 20); //What's this! Another random number!
                i--;
                break;
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题