'How do I randomly output string to multiple labels from array without repeats
I am trying to make a basketball playoff simulator. I have an array for east conference teams and west conference teams. I want to randomly output the team names to the first 4 labels on each side with no repeats. How do I generate random unique seeds for each team.
private void btnSeedActionPerformed(java.awt.event.ActionEvent evt) {
lblSeriesWins.setText(String.valueOf("0"));
String TeamName = (String)jComboBox1.getSelectedItem();
String Raptors = "Raptors";
String Bucks = "Bucks";
String Phila = "76ers";
String Celtics = "Celtics";
String [ ] eastTeams = {"Raptors","Bucks", "76ers", "Celtics"};
Random random1 = new Random();
int PickEast = random1.nextInt(eastTeams.length);
lblFirstTeamEast.setText(String.valueOf(eastTeams[PickEast]));
lblSecondTeamEast.setText(String.valueOf(eastTeams[PickEast]));
lblThirdTeamEast.setText(String.valueOf(eastTeams[PickEast]));
lblFourthTeamEast.setText(String.valueOf(eastTeams[PickEast]));
String[ ] westTeams = {"Lakers", "Warriors", "Suns", "Grizzlies"};
Random random2 = new Random();
int PickWest = random2.nextInt(westTeams.length);
lblFirstTeamWest.setText(String.valueOf(westTeams[PickWest]));
lblSecondTeamWest.setText(String.valueOf(westTeams[PickWest]));
lblThirdTeamWest.setText(String.valueOf(westTeams[PickWest]));
lblFourthTeamWest.setText(String.valueOf(westTeams[PickWest]));
Solution 1:[1]
You could put the names in a list and then shuffle the list, giving you a random order with no duplicates:
List<String> eastTeams = new ArrayList<>(List.of("Raptors", "Bucks", "76ers", "Celtics"));
Collections.shuffle(eastTeams);
lblFirstTeamEast.setText(eastTeams.get(0));
lblSecondTeamEast.setText(eastTeams.get(1));
lblThirdTeamEast.setText(eastTeams.get(2));
lblFourthTeamEast.setText(eastTeams.get(3));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | flwd |