What was I thinking?: we can't just pick a random number once.
Unsmoke that crack. git-svn-id: https://samskivert.googlecode.com/svn/trunk@2916 6335cc39-0255-0410-8fd6-9bcaacd3b74c
This commit is contained in:
@@ -146,18 +146,20 @@ public class Randoms
|
|||||||
* Pick a random key from the specified mapping of weight values, or return
|
* Pick a random key from the specified mapping of weight values, or return
|
||||||
* <code>ifEmpty</code> if no mapping has a weight greater than 0.
|
* <code>ifEmpty</code> if no mapping has a weight greater than 0.
|
||||||
*
|
*
|
||||||
|
* <p><b>Implementation note:</b> a random number is generated for every entry with a
|
||||||
|
* non-zero weight.
|
||||||
|
*
|
||||||
* @throws IllegalArgumentException if any weight is less than 0.
|
* @throws IllegalArgumentException if any weight is less than 0.
|
||||||
*/
|
*/
|
||||||
public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty)
|
public <T> T pick (Map<? extends T, ? extends Number> weightMap, T ifEmpty)
|
||||||
{
|
{
|
||||||
T pick = ifEmpty;
|
T pick = ifEmpty;
|
||||||
double r = _r.nextDouble();
|
|
||||||
double total = 0.0;
|
double total = 0.0;
|
||||||
for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) {
|
for (Map.Entry<? extends T, ? extends Number> entry : weightMap.entrySet()) {
|
||||||
double weight = entry.getValue().doubleValue();
|
double weight = entry.getValue().doubleValue();
|
||||||
if (weight > 0.0) {
|
if (weight > 0.0) {
|
||||||
total += weight;
|
total += weight;
|
||||||
if ((r * total) < weight) {
|
if ((_r.nextDouble() * total) < weight) {
|
||||||
pick = entry.getKey();
|
pick = entry.getKey();
|
||||||
}
|
}
|
||||||
} else if (weight < 0.0) {
|
} else if (weight < 0.0) {
|
||||||
|
|||||||
Reference in New Issue
Block a user