mercredi 4 novembre 2020

How can I pick a random enum when everyone has different probabilities?

I know here in stackoverflow there is already a question about how to randomly select an enum. In the example code, every letter has the same probability of being selected. But how would I rewrite the code when not every enum has the same probability? For example: A has a probability of 50%, B of 30%, C of 15% and D of 5%.

public enum Letter {
  A,
  B,
  C,
  D;

  private static final List<Letter> VALUES =
    Collections.unmodifiableList(Arrays.asList(values()));
  private static final int SIZE = VALUES.size();
  private static final Random RANDOM = new Random();

  public static Letter randomLetter()  {
    return VALUES.get(RANDOM.nextInt(SIZE));
  }
}



Aucun commentaire:

Enregistrer un commentaire