Generating a random enum value continuously withou

2019-07-01 11:59发布

问题:

I have a enum Teams that I want to randomise. So i have:

public enum Teams { TEAM1, TEAM2, TEAM3, TEAM4, TEAM5, TEAM6; }

I then have a random method to generate the value randomly:

public static Teams getRandomTeam() {
    return Teams.values()[(int) (Math.random() * Teams.values().length)];
}

Which does return a randomly generated team, however I need, once a team is generated, say TEAM2, it cannot be generated again.

I'm using:

System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());
System.out.println("The team is " + getRandomTeam());

(which I know is wrong because it's calling the method over and over.

At the minute when I run the program the out put could be:

The team is: TEAM2

The team is: TEAM2

The team is: TEAM4

The team is: TEAM2

The team is: TEAM3

The team is: TEAM2

But I need my program to output the an enum value once and once only. Thanks

回答1:

Simply use Collections.shuffle.

List<Team> teams = new ArrayList<>();
Collections.addAll(teams, Team.values());
Collections.shuffle(teams);


回答2:

It is better to shuffle collection and return elements one by one.

  private static List<Teams> tList;

  private static void regenerateList() {
      tList = new ArrayList<Teams>(Arrays.asList(Teams.values()));
      Collections.shuffle(tList);
  }

  public static Teams getRandomTeam() {
      if (tList.size() > 0) {
         return tList.remove(0);
      } else {
          //handle as you wish: return null or regenerate the list 
         regenerateList();
         return getrandomTeam();
      }
  }


回答3:

What about this? It is recursive!

public static enum TEAMS {
    TEAM1, TEAM2, TEAM3, TEAM4, TEAM5, TEAM6;
}

TEAMS[] teams = TEAMS.values();
Random rnd = new Random();

public TEAMS getnextRandomTeam() {
    int indx = rnd.nextInt(teams.length);
    TEAMS t = teams[indx];
    teams[indx] = null;
    return t == null ? getnextRandomTeam() : t;
}


回答4:

Use Collections shuffle method:

List<Teams> teams = new ArrayList<Teams>(Arrays.asList(Teams.values()));
int index = Integer.MAX_VALUE;

public Teams getRandomTeam() {
    if (index >= teams.size()) {
        Collections.shuffle(teams);
        index = 0;
    }
    return teams.get(index++);
}

This code returns all values in a random order, and resets the list when exhausted to repeat the process indefinitely.