0

First of all im new with coding in Java. I'm coding a program that is calculating random probabilities with a total sum of 100%. For example: Participant 1: 20% chance to win. Participant 2 : 25% chance to win. Participant 3: 45% chance to win. Participant 4: 10% chance to win.

How do I actually pick a winnner? My guess was to check if a random number (0-100) lies between an interval. For example: Participant 1 has a range between 0 and 20. Participant 2 has a range between 20 and 45 and so on.

But how do I actually implement this in Java? Thanks for your help!

GG_Phoenix
  • 17
  • 5
  • Does this answer your question? [Random weighted selection in Java](https://stackoverflow.com/questions/6409652/random-weighted-selection-in-java) – Mohameth Feb 13 '21 at 23:25

2 Answers2

1

One way to do this is, take a pseudo random generator (Math.random()) and let it generate a float between 0 and 1. You would then multiply it with 100 to get into the range of 0 to 100. If this final value is smaller than the percent of the chance, the participant would win.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35
1

A good solution would be to put participants in exclusives plages ([1, 20]; [21, 45]; [46, 90] and [91, 100]), pick a random number and select the participant that falls inside :

        Random r = new Random();
        int randomNumber = r.nextInt(100) + 1;
        
        Map<String, Integer> map = new HashMap<String, Integer>() {{
            put("Alice", 20);
            put("Juan", 25);
            put("Michael", 10);
            put("Natasha", 45);
        }};
        
        String winner = "";
        int currentPlage[] = {0, 0};
        for (String participant : map.keySet()) {
            currentPlage[0] = currentPlage[1] + 1;
            currentPlage[1] = map.get(participant) + currentPlage[0] - 1;
            
            if (randomNumber >= currentPlage[0] && 
                    randomNumber <= currentPlage[1]) {
                winner = participant;
                break;
            }
        }
        
        
        System.out.println(winner);
Mohameth
  • 376
  • 2
  • 10
  • BTW @Leuteris answer doesn't work, in your example case participant 2 would have a 5% chance of winning (The participant with 20 will get every number coming below that) – Mohameth Feb 14 '21 at 00:54