[英]How can I choose a random element from an ArrayList if it changes size?
在我的代碼“ count0
”中,“ count1
”和“ count2
”接收隨機值,而“ totalCount”是它們的總和。 在這里我簡化了它。
使用此代碼,我可以選擇ArrayList的一個隨機元素,但是,例如,如果“ count0”等於0,則它不僅會在第一次而且每次迭代時都從ArrayList中刪除索引0,如果發生這種情況,則會導致錯誤。 這個想法是如何從食品儲藏室中隨機選擇食材,用盡后仍然可以從其余的儲藏室中選擇。
感謝您的幫助=)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class RndNumArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int totalCount=4, count0=1, count1=1, count2=2;
Random rnd = new Random();
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(0, 1, 2));
while(totalCount > 0){
int rand = rnd.nextInt(numbers.size());
int num = numbers.get(rand);
if (num == 0) {
count0--;
if (ccount0 == 0) {
numbers.remove(0);
}
}
if (num == 1) {
count1--;
if (count1 == 0) {
numbers.remove(1);
}
}
if (num == 2) {
count2--;
if (count2 == 0) {
numbers.remove(2);
}
}
totalCount--;
System.out.println(num);
}
}
}
使用兩個列表計數(您擁有多少個產品)和數字(產品編號):
public static void main(final String[] args)
{
final int totalCount = 4;
final Random rnd = new Random();
final List<Integer> numbers = new ArrayList<>(Arrays.asList(0, 1, 2));
final List<Integer> counts = new ArrayList<>(Arrays.asList(1, 1, 2));
for (int i = 1; i < totalCount; i++)
{
final int rand = rnd.nextInt(numbers.size());
final int num = numbers.get(rand);
int count = counts.get(rand);
count--;
if (count < 1)
{
numbers.remove(rand);
counts.remove(rand);
}else
{
counts.set(rand, count);
}
System.out.println(num);
}
}
或者您可以刪除編號列表,如果產品編號始終為0、1、2、3 ...
多謝你們。 你們真棒。 我會嘗試您的所有建議,但我想出了一個可行的解決方案。 我沒有從列表中刪除項目,而是給了它們一個值,我可以通過do-while來控制它們,以便您僅選擇可用的值。
我的代碼是對吸煙問題(線程和同步)的修改。 在我的代碼中,每位吸煙者都有一定數量的雪茄,可以在其余雪茄之前吃完,因此代理人不必為他放食。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class RndNumArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int totalCount=4, count0=1, count1=1, count2=2;
Random rnd = new Random();
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(0, 1, 2));
while(totalCount>0){
int rand;
int num;
do{
rand = rnd.nextInt(numbers.size());
num = numbers.get(rand);
} while(num==3);
if (num == 0) {
count0--;
if (ccount0 == 0) {
numbers.set(0,3);
}
}
if (num == 1) {
count1--;
if (count1 == 0) {
numbers.set(1,3);
}
}
if (num == 2) {
count2--;
if (count2 == 0) {
numbers.set(2,3);
}
}
totalCount--;
System.out.println(num);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.