Skip to content
Advertisement

Generating 10 random numbers without duplicate with fundamental techniques

my intend is to use simplest java (array and loops) to generate random numbers without duplicate…but the output turns out to be 10 repeating numbers, and I cannot figure out why.

Here is my code:

int[] number = new int[10];
int count = 0;
int num;

while (count < number.length) {
    num = r.nextInt(21);
    boolean repeat = false;
    do {
        for (int i=0; i<number.length; i++) {
            if (num == number[i]) {
                repeat = true;
            } else if (num != number[i] && i == count) {
                number[count] = num;
                count++;
                repeat = true;
            }
        }
    } while (!repeat);
}

for (int j = 0; j < number.length; j++) {
    System.out.print(number[j] + " ");
}

Advertisement

Answer

You need to break out of the for loop if either of the conditions are met.

    int[] number = new int[10];
    int count=0;
    int num;
    Random r = new Random();
    while(count<number.length){
        num = r.nextInt(21);
        boolean repeat=false;
        do{
            for(int i=0; i<number.length; i++){
                if(num==number[i]){
                    repeat=true;
                    break;
                }
                else if(i==count){
                    number[count]=num;
                    count++;
                    repeat=true;
                    break;
                }
            }
        }while(!repeat);

    }

    for(int j=0;j<number.length;j++){
        System.out.print(number[j]+" ");
    }

This will make YOUR code work but @gonzo proposed a better solution.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement