Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random enum value continuously without getting the same value twice

Tags:

java

enums

random

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

like image 202
Ron Avatar asked Dec 05 '22 09:12

Ron


1 Answers

Simply use Collections.shuffle.

List<Team> teams = new ArrayList<>();
Collections.addAll(teams, Team.values());
Collections.shuffle(teams);
like image 178
Grzegorz Żur Avatar answered Feb 08 '23 23:02

Grzegorz Żur