Created
January 24, 2012 04:24
-
-
Save raws/1667807 to your computer and use it in GitHub Desktop.
Weighted randomization in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.NavigableMap; | |
import java.util.Random; | |
import java.util.TreeMap; | |
public class WeightedCollection<E> { | |
private NavigableMap<Integer, E> map = new TreeMap<Integer, E>(); | |
private Random random; | |
private int total = 0; | |
public WeightedCollection() { | |
this(new Random()); | |
} | |
public WeightedCollection(Random random) { | |
this.random = random; | |
} | |
public void add(int weight, E object) { | |
if (weight <= 0) return; | |
total += weight; | |
map.put(total, object); | |
} | |
public E next() { | |
int value = random.nextInt(total) + 1; // Can also use floating-point weights | |
return map.ceilingEntry(value).getValue(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment