user3681185
user3681185

Reputation: 3

How to generate unique random numbers in an array

I'm having trouble with this assignment that requires me to create 50 random unique numbers without using ArrayLists. I'm required to use a boolean array that checks whether the random number has already been generated. Each number that is generated out of 50 will be set to true in the boolean array. Ex. Generating a number 23 would make check[23]=true. The problem I am having is an error in the while loop that keeps on generating a new random number even if there is no other unique number left. How can I solve this problem while still using a boolean array to check uniqueness.

int rnd;
Random rand=new Random();Random rand=new Random();
int[] nums = new int[50];
boolean[] check = new boolean[51];

rnd = rand.nextInt(50) +1;
for (int k = 0; k<50; k++)
{
    //Loop for when there number is already chosen
    while (check[rnd]==true)
    {
        rnd = rand.nextInt(50) +1;
    }
    //Sets the random unique number to a slot in the array
    if(check[rnd]==false)
    {
        nums[k]=rnd;
        check[rnd]=true;
    }
    rnd = rand.nextInt(50) +1;
}
System.out.println(nums);

Upvotes: 0

Views: 5452

Answers (2)

Abs
Abs

Reputation: 3962

Few tweaks done:

public class Test {

    public static void main(String args[]){
        int rnd;

        Random rand=new Random();
        int[] nums = new int[50];
        boolean[] check = new boolean[50];
        for (int k = 0; k<50; k++)
        {
            rnd = rand.nextInt(50);

            //Loop for when there number is already chosen
            while (check[rnd])
            {
                rnd = rand.nextInt(50);

            }
//Sets the random unique number to a slot in the array
                nums[k]=rnd;
                check[rnd]=true;

        }

        for(int num : nums){
            System.out.println("\n" + num);

        }

    }
}

Upvotes: 0

Patrick vD
Patrick vD

Reputation: 789

Try this:

import java.util.Random;

public class random {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Random myRandom = new Random();
        int[] numbers = new int[50];
        boolean[] check = new boolean[50];
        int amountFilled = 0;
        int trial;
        while (amountFilled < 50) {
            trial = myRandom.nextInt(50);
            if (!check[trial]) {
                check[trial] = true;
                numbers[amountFilled] = trial;
                amountFilled++;
            }
        }
        for (int i = 0; i < 50; i++) {
            System.out.println(numbers[i]);
        }
    }
}

Your real problem was the System.out.println(nums); statement. It doesn't do what you what it to do. And the double Random rand=new Random();. The rest of the code is OK. I rewrote it in a clearer/simpler way, but what you had already works if you fix the output statement.

Upvotes: 1

Related Questions