java random chance

Solutions on MaxInterview for java random chance by the best coders in the world

showing results for - "java random chance"
Marion
21 Mar 2020
1import java.util.Map;
2import java.util.concurrent.ThreadLocalRandom;
3
4public class RandomChance {
5
6    private final Map<?, Double> map;
7    private final ThreadLocalRandom random = ThreadLocalRandom.current();
8
9    /**
10     *
11     * @param map This map can contain any object as the key and must contain a double as the chance for that key to be chosen
12     */
13    public RandomChance(Map<?, Double> map) {
14        this.map = map;
15    }
16
17    /**
18     * @param input  is the double you wish to check
19     * @param first  is the first double that the input must be between
20     * @param second is the second double the input needs to be between
21     * @return will return true if input is between first and second
22     */
23    private boolean isBetween(double input, double first, double second) {
24        return input <= Math.max(first, second) && input >= Math.min(first, second);
25    }
26    
27    /**
28     * 
29     * @return will loop through the map passed into the constructor and randomly pick a value based on the chance provided
30     */  
31    public Object get() {
32        double total = map.values().stream().mapToDouble(e -> e).sum();
33        double placeHolder = 0.0;
34        double randomNumber = random.nextDouble(total);
35        for (Object obj : map.keySet()) {
36            double upperBound = placeHolder + map.get(obj);
37            if (isBetween(randomNumber, placeHolder, upperBound)) {
38                return obj;
39            } else {
40                placeHolder = upperBound;
41            }
42        }
43        return null;
44    }
45}