gpt4 book ai didi

java - 如果 ArrayList 的大小发生变化,如何从其中选择一个随机元素?

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:14 25 4
gpt4 key购买 nike

在我的代码中,“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);
}
}
}

最佳答案

谢谢,伙计们。你们太棒了。我会尝试您的所有建议,但我已经提出了一个可行的解决方案。我没有从列表中删除项目,而是给了它们一个值,我将通过 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);
}
}
}

关于java - 如果 ArrayList 的大小发生变化,如何从其中选择一个随机元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53708871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com