我有一个随机选择器代码,可以从1到6中选择随机数。 你可以给我一个方法,如何从随机选择列表中排除挑选的数字..
import java.util.Random;
Random rand = new Random();
int n = rand.nextInt(6) + 1;
就像前者一样: 1.2.3.4.5.6 随机选择= 5 1.2.3.4.6 随机选择= 2 1.3.4.6 等等 ty提前家伙
答案 0 :(得分:0)
将所有有效数字放入ArrayList,然后从列表中选择一个随机索引。然后从列表中删除该号码并重复。
我的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);
答案 1 :(得分:0)
您可以将已经拾取的数字添加到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。