从随机选择器列表中排除数字

exclude number from the Random picker list

我有一个随机选择器代码,可以从 1 到 6 中为 ex 选择随机数 .. 你能给我一个方法如何从随机选择列表中排除选择的号码吗..

import java.util.Random;

Random rand = new Random();

int  n = rand.nextInt(6) + 1;

比如 ex : 1.2.3.4.5.6 随机选择=5 1.2.3.4.6 随机选择=2 1.3.4.6 .. ETC 伙计们提前联系

将所有有效数字放入 ArrayList 中,而不是 select 列表中的随机索引。然后从列表中删除该号码并重复。

我的 Java 有点生疏,所以希望我写的代码有意义:

ArrayList<int> validOptions = /**/; // make your list with all initial options

int firstIndex = random.Next(validOptions.count());
int firstPick = validOptions.get(firstIndex);
validOptions.removeAt(firstIndex);

int secondIndex = random.Next(validOptions.count());
int secondPick = validOptions.get(secondIndex);
validOptions.removeAt(firstIndex);

您可以将已经选出的号码添加到一个ArrayList中,并选出一个号码,直到该号码不在列表中。

// list of numbers that I already picked
ArrayList<Integer> randomNumbersPicked = new ArrayList<>();
// int to save the current random number
int myCurrentRandomNumber;

while(iNeedAnotherNumber){
    do {
        myCurrentRandomNumber = generateRandomNumber(a, b);
    //repeat this until the number is not in the list
    } while (randomNumbersPicked.contains(new Integer(myCurrentRandomNumber)));
    //here there is a unique random number, do what you will
    System.out.println("A new number has been picked: " + myCurrentRandomNumber);
    //add the number to the list so it wont be picked again
    randomNumbersPicked.add(new Integer(myCurrentRandomNumber));
}

此致! Dknacht.