标题可能有点混乱,但我真的不知道如何解释这一点。我有一个对象列表,在本例中是位置,这些位置可以被玩家占用。如果所选位置已被占用,我如何尝试查找新位置,并继续此操作,直到找到未占用的位置?
我已经知道有20个位置,我可以手动检查每个位置,看看是否有人占用,但有没有更好的方法呢?
下面是我的代码片段。
List<Location> spawnList = arena.getManager().getRandomSpawns(); // Returns a list of possible locations
Location random = spawnList.get(new Random().nextInt(spawnList.size())); // Selects a random location from the list
if (random.isOccupied()) {
    /* Location is occupied, find another one from the list, and continue doing this until non-occupied location is found */
}抱歉,如果你不明白,我不知道一个好的方式来解释这一点。
发布于 2013-11-17 19:58:10
简单的方法是在循环中随机化一个位置,直到找到一个:
List<Location> spawnList = arena.getManager().getRandomSpawns(); // Returns a list of possible locations
Location random = spawnList.get(new Random().nextInt(spawnList.size())); // Selects a random location from the list
while (random.isOccupied()) {
    random = spawnList.get(new Random().nextInt(spawnList.size()));
}这里的问题是,如果大多数位置已经被占用,这可能需要很长时间。
一种“更安全”的方法,无论预占位置的百分比如何,都承诺相同的性能顺序,可以将位置列表打乱,然后简单地迭代它:
List<Location> spawnList = new LinkedList<Location>(arena.getManager().getRandomSpawns());
Location random = null;
for (Location loc : spawnList) {
    if (!loc.isOccupied()) {
        random = loc;
    }
}https://stackoverflow.com/questions/20030317
复制相似问题