在Java中,给定 n个 项目,每个项目的权重为 w ,一个人如何从集合中选择机会等于 w 的随机项目?
假设每个权重是0.0到1.0的两倍,并且集合中的权重之和为1。Item.getWeight()返回Item的权重。
Item[] items = …;
// Compute the total weight of all items together double totalWeight = 0.0d; for (Item i : items) { totalWeight += i.getWeight(); } // Now choose a random item int randomIndex = -1; double random = Math.random() * totalWeight; for (int i = 0; i < items.length; ++i) { random -= items[i].getWeight(); if (random <= 0.0d) { randomIndex = i; break; } } Item myRandomItem = items[randomIndex];