Skip to content
Advertisement

Drawing raffle numbers out of list that can have duplicates in Java

I was trying to learn programming by writing code with friends, we are all new though and are stuck with this raffle program.

Players can earn multiple raffle tickets. The raffle tickets are written down in a new row in an ArrayList when they are earned. It looks like this: “PlayerA PlayerB PlayerB PlayerC PlayerD PlayerE PlayerF”

Now we want to draw x random winners but no one can win twice.

I have a while loop to generate x winners. If the size of my list with winning numbers is >=1 I want to check if the random winning number is already in the list OR associated with a player name that has already won.

The Array List starts at 0, so if I already drew number 1 (PlayerB), I cannot draw number 2 (PlayerB), as PlayerB cannot win twice.

This code makes sense in my head and I only get each number once but I still get e.g. number 1 and 2, which should not happen as both belong to PlayerB.

while (WinnerNumberList.size() < amountOfWinners)
        {  
            Integer randomNumber = rng.nextInt(myEntryList.size());
            
            if(WinnerNumberList.size() < 1) {
                WinnerNumberList.add(randomNumber);
            }
            else {
                if(!(WinnerNumberList.contains(randomNumber))) {
                    for(int i=0; i<WinnerNumberList.size(); i++) {
                        if((myEntryList.get(randomNumber)).equals(myEntryList.get(i))) {
                            break;
                        }
                        else {
                            if(!(WinnerNumberList.contains(randomNumber))) {
                                WinnerNumberList.add(randomNumber);
                            }
                        }
                    }
                }
            }
        }

Can anyone tell me where I am missing something, please?

Advertisement

Answer

Why not do it like this. This will be partly pseudocode since I don’t know all the details.

while (playerList.size() > 0) {
     Integer randomNumber = rng.nextInt(playerList.size());
     String player = playerList.get(randomNumber);
     if (player is winner) {
          System.out.println(player  + " wins!");
          // remove all occurences of that player
          playerList.removeIf(p -> p.equals(player));
      }
}

The above simply removes all instances of the same player from the list if that player won.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement