Solution - Task 1

EventSimulator
 avatar
unknown
java
2 years ago
2.3 kB
3
Indexable
import java.util.HashMap;
import java.util.Random;

class EventSimulator {

    //this simulator method has logic to select among key inputs in main method , and their likely chances to occur in totalOccurrences.

    // the simulator method uses a random number to select an outcome based on their probabilities. It iterates through the 'hm' map,
    // accumulating the probabilities until it finds an outcome whose cumulative probability comes nearer to the generated random number.

    // main thing to note that event occurrence is totally 'biased' on hashmap input value (that is probability of event provided in input) ,
    // higher the number higher the chances of occurring
    private static Object simulator(HashMap<Object, Integer> hm) {

        int randomNumber = new Random().nextInt(100);
        int growingProbability = 0;

        for (HashMap.Entry<Object, Integer> inputProbabilities : hm.entrySet()) {
            growingProbability = growingProbability + inputProbabilities.getValue();
            if (randomNumber <= growingProbability) {
                return inputProbabilities.getKey();
            }
        }

        throw new RuntimeException ("400 Bad Request");
    }

    public static void main(String[] args) {

        // hard coded outcomes and their probabilities
        HashMap<Object, Integer> hm = new HashMap<>();
        hm.put(1,10);
        hm.put(2,30);
        hm.put(3,15);
        hm.put(4,15);
        hm.put(5,30);
        hm.put(6,0);

        //uncomment this and comment above dice probability to check for coin occurrence
//        hm.put("head",35);
//        hm.put("tail",65);

        //
        int totalOccurrences = 1000;
        HashMap<Object, Integer> occurrenceCount = new HashMap<>();

        for (int i = 0; i < totalOccurrences; i++) {
            Object obj = simulator(hm);
            Integer count = occurrenceCount.get(obj);
            if (count == null) {
                occurrenceCount.put(obj, 1);
            } else {
                occurrenceCount.put(obj, count + 1);
            }
        }

        //print occurrences
        for (HashMap.Entry<Object, Integer> entry : occurrenceCount.entrySet()) {
            System.out.println("Chances to occur " +entry.getKey() + " is " +entry.getValue() + " times.");
        }
    }
}