如何在数组中生成唯一的随机数 [英] How to generate unique random numbers in an array

查看:69
本文介绍了如何在数组中生成唯一的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在执行此分配时遇到麻烦,需要我在不使用ArrayLists的情况下创建50个随机唯一数字。我需要使用一个布尔数组来检查随机数是否已经生成。在布尔数组中,每50个生成的数字将设置为true。例如生成数字23将使check [23] = true。我遇到的问题是while循环中的错误,即使没有其他唯一的数字,该循环仍会继续生成新的随机数。

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


推荐答案

尝试一下:

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

您真正的问题是 System.out.println(nums); 语句。它不会做您要做什么。以及双 Random rand = new Random(); 。其余的代码都可以。我以更清楚/更简单的方式重写了它,但是如果您修复输出语句,您已经可以使用。

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.

这篇关于如何在数组中生成唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆