2017-01-10 49 views
-1

如果我有这样的如何根据其中一个对象属性的值从数组中选择一个随机元素?

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

你的代码很混乱......那里面有什么变数?你的意思是r。 – vilpe89

+0

这段代码还有两个循环,因为我没有认为它们是相关的,所以我没有包含这些代码。道歉。 – ShoeLace1291

+0

@ ShoeLace1291什么不工作? – brso05

回答

0

我想你必须先过滤您的阵列有一个可用性大于0,仅此调用new Random().nextInt(filteredResources.length)后,生成随机数。

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]是你所需要的。

+0

这是无效的代码..... –

+0

我想现在我的代码是好的。 @JordiCastilla –

1

一个非常简单的解决办法:

  1. 使用列表,而不是数组,然后转到Collections.shuffle() - 该方法使你的元素融入到一个随机的顺序!
  2. 然后迭代该数组,然后选取满足(全部)您的条件的元素第一个元素。
相关问题