Skip to content
Advertisement

How to generate array of unique values

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);
}

Advertisement

Answer

In your approach, you have three 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.


Bonus. For easier debugging, you can use a trick. Replace 99 with 10. Why? When you generate a list all values in it should be unique.

Random r = new Random();
int[] list = new int[10];

int bound = 10;
for (int number = 0; number < list.length; ++number) {
    list[number] = r.nextInt(bound);

    for (int uniqueNumber = 0; uniqueNumber < number; ++uniqueNumber) {
        if (list[uniqueNumber] == list[number]) {
            list[number] = r.nextInt(bound);
            uniqueNumber = -1;
        }
    }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement