Home  >  Article  >  Java  >  How can I implement Weighted Random Selection in Java?

How can I implement Weighted Random Selection in Java?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 19:58:03628browse

How can I implement Weighted Random Selection in Java?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn