Home > database >  How to generate array of unique values
How to generate array of unique values

Time:11-13

I'm trying to generate an array of unique values but my first number is always 0, how can I fix this?

Random r = new Random();
Scanner in = new Scanner(System.in);
int generatedNumbers = 0;
int winningSum = 0;
int[] list = new int[10];

for (int number = 1; number < list.length;   number) {
    list[number] = r.nextInt(99);

    for (int uniqueNumber = 0; uniqueNumber < number;   uniqueNumber) {
        if (list[uniqueNumber] == list[number]) {
            list[number] = r.nextInt(99);
            uniqueNumber = 0;
        }
    }
}
int random_first = r.nextInt(99);)
for (int element : list) {
    System.out.println(element);
}

CodePudding user response:

you need to start from zero, not one, in your for loop

Random r = new Random();
int[] list = new int[50];
for(int index = 0; index < list.length; index  ) {
    int newNum = r.nextInt(99);
    outer:while(true){
        for(int i = 0;i<index;i  ){
            if(list[i]==newNum){
                newNum = r.nextInt(99);
                continue outer;
            }
        }
        break;
    }
    list[index] = newNum;
    
}
for (int element: list) {
    System.out.println(element);
}

CodePudding user response:

In your approach, you have thre mistakes (that I noticed).

The first, this loop for (int number = 1; number < list.length; number) should start with zero. So, for (int number = 0; number < list.length; number).

The second, inner check for (int uniqueNumber = 0; uniqueNumber < number; uniqueNumber) { fails here uniqueNumber = 0; It should be uniqueNumber = -1.

And finally, you don't need this line int random_first = r.nextInt(99);) after outer for loop.


  • Related