mardi 13 octobre 2020

Create an array with random integers but with no duplicates

I need a solution to create an array with random values and with no duplicates. My issue is when I create an array with no duplicates it removes the duplicates and keeps my array with some 0 values.

How can I create an array with a specific index but instead of just removing duplicates, changes it to another value,

note: it has to be done only with regular arrays and not collections since its a task in flow control.

// *Initializing first array with random numbers*
for (int i = 0; i < guesses.length; i++) {
    guesses[i] = rand.nextInt(10) + 1;
}

// *Creating a second array while removing duplicates*
int[] array2 = new int[5];
int index = 0;

lbl: for (int i = 0; i < guesses.length; i++) {
    int x = guesses[i];

    for (int j = 0; j < index; j++) {
        if (array2[j] == x) {
            continue lbl;
        }

    }
    array2[index++] = x;
}

Array with duplicates:

[6, 9, 8, 5, 5, 6]

What I get after removing duplicates (as you can see i have two 0's)

[6, 9, 8, 5, 0, 0]

example of What i need:

[6, 9, 8, 5, 3, 1]



Aucun commentaire:

Enregistrer un commentaire