如果我有这样的数组
resources[0] = new Resource("Brick", 0x990000, 3);
resources[1] = new Resource("Wool", 0xFFFFFF, 4);
resources[2] = new Resource("Lumber", 0x006600, 4);
resources[3] = new Resource("Stone", 0x999999, 3);
resources[4] = new Resource("Wheat", 0xFFFF33, 4);
resources[5] = new Resource("Wasteland", 0xcc9966, 1);
如何选择可用性大于0的随机资源?这是我目前的尝试:
int[] diceSpaces = {2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12};
diceSpaces = shuffleArray(diceSpaces);
for(int i = 0; i < diceSpaces.length; i++){
Resource currentResource = null;
for(int r = 0; r < resources.length; r++){
int tryResource = new Random().nextInt(resources.length);
if(diceSpaces[i] != 7){
if(resources[tryResource].available > 0){
currentResource = resources[tryResource];
break;
}
} else {
currentResource = resources[5];
break;
}
}
currentResource.available--;
}
答案 0 :(得分:1)
一个非常简单的解决方案:
答案 1 :(得分:0)
我认为你必须首先过滤你的数组以获得大于0的可用性,并且只有在此调用new Random().nextInt(filteredResources.length)
之后才能生成随机数。
答案 2 :(得分:0)
Resource availableResources[] = new Resource[resources.length];
int count = 0;
for(int r = 0; r < resources.length; r++){
if(resources[r].available > 0){
availableResources[count++] = resources[tryResource];
}
}
int RandomResource = (rand.nextInt(count));
availableResources[randomResource]
就是您所需要的。