简体   繁体   中英

How can I select a random element from an array based on the value of one of it's object properties?

If I have an array like this

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);

How can I select a random resource that has an availability greater than 0? Here is my current attempt:

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--;

}

One very easy solution:

  1. Use Lists instead of Arrays, and then turn to Collections.shuffle() - that method puts your elements into a random order!
  2. Then iterate the array, and pick the first element that fulfills (all) your condition(s).

我想你必须首先过滤你的数组以获得大于 0 的可用性,并且只有在这个调用new Random().nextInt(filteredResources.length)才能生成随机数。

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] is what you require.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM