[英]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 ..等等
將所有有效數字放入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);
您可以將已經選擇的數字添加到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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.