Nick L
Nick L

Reputation: 167

How to pull elements from an enum without getting repetitions

I've been trying to pull values from an enum and store them as a String in an array. However, depending on a variable, the values have to be unique, i.e. the same value can't be used twice.

I've used the following code to pull values:

public enum Colour
{
    ROOD, GEEL, GROEN, BLAUW, PAARS;

    public Colour getRandomColour(Random rn)
    {
        return values()[rn.nextInt(values().length)];
    }
}

However, this can give duplicate values.

It seems that the values of my enum refuse to be put in code blocks. Sorry!

EDIT:

for (int i = 0; i < code.length; i++) 
            code[i] = kleur.getRandomColour(rn).toString();

It fills up the array 'code'. The array-length depends on several factors but it will always be smaller than or equal to the amount of values in the enum.

Upvotes: 1

Views: 729

Answers (3)

Nick L
Nick L

Reputation: 167

For those still wondering, I might have found a good solution. Store the values of the array in an ArrayList. Using a for-loop to pull a value from the ArrayList then remove that index, essentially eliminating duplicates.

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 51892

Use a temporary list to check if the new value already exist and continue to generate a new value until a unique is found.

for (int i = 0; i < code.length; i++) {
   String next = kleur.getRandomColour(rn).toString();
   List<String> tempList = Arrays.arrayAsList(code);
   while (tempList.contains(next);
     next = kleur.getRandomColour(rn).toString();
   }
   code[i] = next;
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

You could populate a list with all values from your Colour enum, shuffle, and then just access values sequentially:

List<Colour> colourList = Arrays.asList(Colour.values());
Collections.shuffle(colourList);

Then, just iterate the list and access the colors in order, which of course should be random since the collection was shuffled:

for (Colour c : colourList) {
    // do something with c
}

You could also go with your current approach, and store the colors into a set, rather than an ArrayList. But the problem there is that you may draw a duplicate value any number of times, and the chances of that happening as the set increases in size will go up.

Upvotes: 1

Related Questions