Weighted Random Selection in Java
When selecting a random item from a set, it's often desirable to bias the selection towards items with higher associated weights. In Java, this can be achieved using a NavigableMap, a specialized data structure specifically tailored for this purpose.
The RandomCollection class, implemented using a NavigableMap, allows weighted items to be added and retrieves random items based on their respective weights. To create a RandomCollection, simply specify a random generator (optional, or use the default Random).
Adding items to the RandomCollection is straightforward. Each item is associated with a weight, which represents its probability of being selected. The total weight is maintained as new items are added.
To select a random item, a random number between 0 and the total weight is generated. The NavigableMap's higherEntry() method is then used to retrieve the first entry with a weight greater than the random number. The value associated with this entry is the randomly selected item.
Example:
RandomCollection<String> rc = new RandomCollection<>(); rc.add(40, "dog").add(35, "cat").add(25, "horse"); for (int i = 0; i < 10; i++) { System.out.println(rc.next()); }
This code will generate a random sequence of animals ("dog", "cat", "horse") weighted according to their probabilities.
The above is the detailed content of How can I implement Weighted Random Selection in Java?. For more information, please follow other related articles on the PHP Chinese website!