dimanche 19 mai 2019

Randomly select from HashMap with certain probability

I am trying to get a random item from a HashMap based on it's chance. I tried writing a code for testing, for it and it seemed to work fine which is:

while (true) {
    int random = new Random().nextInt(100);

    if (random < 5) {
        finalValue = 1;
        break;
    } else if (random < 10) {
        finalValue = 2;
        break;
    } else if (random < 50) {
        finalValue = 3;
        break;
    } else if (random < 70) {
        finalValue = 4;
        break;
    }
}
System.out.printf(finalValue);

The problem for me is that this would work if the chances where always the same, but for me it is customization on a configuration file.
Currently I store the configuration data on an HashMap like this HashMap<Integer, HashMap<String, Object>> Where the integer is the ID of the item to be selected and inside the other HashMap there is data like for example the chance is stored there and name of the item.
How can I select a random value from this HashMap based on it's own chance?




Aucun commentaire:

Enregistrer un commentaire