mardi 30 mai 2017

How can I maintain probability across multiple executions in Java

Firstly I am not the greatest with Math, so please excuse any ignorance relating to that. I am trying to maintain probability based randomness across multiple executions but I am failing. I have this input in a JSONObject

{
   "option1": 25,
   "option2":25,
   "option3" :10,
   "option4" :40
}

This is my function that selects a value from the above JSONObject based on the probability assigned:

public static String selectRandomoptions(JSONObject options) {
    String selectedOption = null;

    if (options != null) {

        int maxChance = 0;
        for (String option : options.keySet()) {
            maxChance += options.getInt(option);
        }

        if (maxChance < 100) {
            maxChance = 100;
        }

        Random r = new Random();
        Integer randomValue = r.nextInt(maxChance);

        int chance = 0;
        for (String option : options.keySet()) {
            chance += options.getInt(option);
            if (chance >= randomValue) {
                selectedOption = options.toLowerCase();
                break;
            }
        }
    }
}

the function behaves within a reasonable error margin if I call it x amount of times in a single execution ( tested 100+ calls), the problem is that I am running this every hour to generates some sample data in an event-driven app to verify our analytics process/data but we need it to be somewhat predictable, at least within a reasonable margin?

Has anyone any idea how I might approach this? I would rather not have to persist anything but I am not opposed to it if it makes sense or reduces complexity/time.




Aucun commentaire:

Enregistrer un commentaire