簡體   English   中英

如何在數組中生成唯一的隨機數

[英]How to generate unique random numbers in an array

我在執行此分配時遇到麻煩,該分配要求我創建50個隨機唯一數字而不使用ArrayLists。 我需要使用一個布爾數組來檢查隨機數是否已經生成。 在布爾數組中,每50個數字都會設置為true。 防爆。 生成數字23將使check [23] = true。 我遇到的問題是while循環中的錯誤,即使沒有其他唯一數字,該循環仍會繼續生成新的隨機數。 如何在仍然使用布爾數組檢查唯一性的同時解決此問題。

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); 聲明。 它不會執行您要執行的操作。 而double Random rand=new Random(); 其余的代碼都可以。 我以更清楚/更簡單的方式重寫了它,但是如果您修復輸出語句,那么您已經可以使用。

很少進行調整:

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

        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM