How to generate unique random numbers in an array

本小妞迷上赌 提交于 2020-01-06 12:58:30

问题


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

回答1:


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.




回答2:


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

        }

    }
}


来源:https://stackoverflow.com/questions/23897814/how-to-generate-unique-random-numbers-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!