Class BiasedRandomPicker<E>

java.lang.Object
tk.airshipcraft.commonlib.utils.math.BiasedRandomPicker<E>
Type Parameters:
E - The type of object that can be picked.

public class BiasedRandomPicker<E> extends Object
This class allows for random selection of objects based on assigned probabilities. It is particularly useful when objects need to be picked with non-uniform chances, enabling the creation of biased random outcomes according to specified weights.
Since:
2023-04-03
Version:
1.0.0
Author:
notzune
  • Constructor Summary

    Constructors
    Constructor
    Description
    Constructs a BiasedRandomPicker with a map of objects and their associated probabilities.
  • Method Summary

    Modifier and Type
    Method
    Description
    double
    Retrieves the probability of an object being picked by this BiasedRandomPicker instance.
    Randomly selects an object from the pool, considering the assigned chances.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • BiasedRandomPicker

      public BiasedRandomPicker(Map<E,Double> chances)
      Constructs a BiasedRandomPicker with a map of objects and their associated probabilities. The total sum of all provided chances must equal 1, within a tolerance of 10^(-6). A chance of 0 indicates that the object will never be picked, while a chance of 1 indicates certainty.
      Parameters:
      chances - A map where each key is an object to pick and each value is the chance of picking that object.
      Throws:
      IllegalArgumentException - If the provided map is null, contains null values, or if the sum of chances is not 1.
  • Method Details

    • getRandom

      public E getRandom()
      Randomly selects an object from the pool, considering the assigned chances. If the configuration is malformed, there is an extremely low probability that this method may return null, but such a case is highly unlikely (less than 10^(-120)).
      Returns:
      A randomly picked element based on the biased chances.
    • getChance

      public double getChance(E e)
      Retrieves the probability of an object being picked by this BiasedRandomPicker instance. If the object was not assigned an explicit chance, a default of 0.0 is returned.
      Parameters:
      e - The object for which to retrieve the selection chance.
      Returns:
      The probability of the object being picked.