Generating a random enum value continuously withou

2019-07-01 12:29发布

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

4条回答
The star\"
2楼-- · 2019-07-01 12:31

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.

查看更多
男人必须洒脱
3楼-- · 2019-07-01 12:44

Simply use Collections.shuffle.

List<Team> teams = new ArrayList<>();
Collections.addAll(teams, Team.values());
Collections.shuffle(teams);
查看更多
神经病院院长
4楼-- · 2019-07-01 12:47

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;
}
查看更多
可以哭但决不认输i
5楼-- · 2019-07-01 12:53

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();
      }
  }
查看更多
登录 后发表回答