简体   繁体   English

在Java中的数组中分配随机数(不重复)

[英]Assigning random numbers in an array in java (non repeating)

I am trying to set up a game of Deal or No Deal. 我正在尝试建立一个有交易或没有交易的游戏。 I need to assign one of the money values to each case. 我需要为每种情况分配一个货币值。 I was wondering if this would be possible and if so, how. 我想知道这是否可能,如果可以,怎么做。 I would set up 2 arrays, case for the case number (1-26) and money for the different values (specific numbers between 1 and 1,000,000 that I would set at the beginning). 我将设置2个数组,大小写为(1-26)的大小写,并为不同的值设置金钱(我将在开始时设置的1到1,000,000之间的特定数字)。 I then would like to take a random value out of array money and assign it a value in array case but also check to make sure it isn't already stored in another case variable. 然后,我想从数组中取出一个随机值,并在数组大小写中为其分配一个值,但还要检查以确保它尚未存储在另一个case变量中。

int cases[]=new int[26];
int money = {1,2,,5,10,25,50,75,100,200,300,400,...};

Every value stored in money will be used once and only once. 存储在货币中的每个值都将使用一次,并且只能使用一次。 Every case will get assigned one and only one value. 每个案例将被分配一个且只有一个值。

Use an ArrayList instead. 请改用ArrayList。

ArrayList<Integer> money = ....;

for (int i = 0; i < 26; i++){
    int pick = (int)(Math.random() * money.size());
    cases[i] = money.remove(pick);
}

However, if you're going to use an ArrayList, you may as well take advantage of the wealth of methods found in Collections , such as Collections#shuffle . 但是,如果要使用ArrayList,则还可以利用Collections丰富的方法,例如Collections#shuffle Per the docs, 根据文档,

Randomly permutes the specified list using a default source of randomness. 使用默认的随机性源随机排列指定的列表。 All permutations occur with approximately equal likelihood. 所有排列发生的可能性几乎相等。

You could then use the method like so: 然后,您可以使用如下方法:

ArrayList<Integer> money = ....;
Collections.shuffle(money);
//money is now functionally what `cases` used to be

You should have at least 26 values in money[] array money []数组中至少应包含26个值

    int cases[]=new int[26];
    int[] money = {1,2,5,10,25,50,75,100,200,300,400....};
    Random random = new Random();
    int index = 0;
    firstLoop:
    while(cases[25]==0){
        int randomChosenIndex = random.nextInt(money.length);
        int randomChosenValueFromMoney = money[randomChosenIndex];
        for (int i = 0; i < index; i++) {
            if (cases[i]==randomChosenValueFromMoney) {
                continue firstLoop;
            }
        }
        cases[index++] = randomChosenValueFromMoney;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM