0

I'm trying to get this as the output:

How many colours do you need?

user inputs a number say 3

Result:

gets 3 RANDOM colours from a list of choices

My problem is that yes the user gets 3 random colours but some of them are repeated. I end up getting,

red
blue
red

I've tried using a set but I don't know how to write it in a way that it'll pick out 3 shuffled items in said set.

How I'm selecting random colors:

colours obj = new colours();

for (int i = 0; i < X; i++) {
    System.out.println(obj.randommm(list)); 
}

public String randommm(List<String> list) {
    int index = random.nextInt(list.size()); return list.get(index); 
}
Alex
  • 3,111
  • 6
  • 27
  • 43
RH's
  • 3
  • 1
  • How are you selecting your random colors – k_g Jan 10 '15 at 05:49
  • colours obj = new colours(); for(int i = 0; i < X; i++){ System.out.println(obj.randommm(list)); } } public String randommm(List list) { int index = random.nextInt(list.size()); return list.get(index); } } – RH's Jan 10 '15 at 06:01
  • possible duplicate of [best way to pick a random subset from a collection?](http://stackoverflow.com/questions/136474/best-way-to-pick-a-random-subset-from-a-collection) – Basilevs Jan 10 '15 at 07:39

2 Answers2

0

You can just check if the list already contains the item before adding it.

Assuming you already have some list of colors:

List<Color> allMyColors = something;

Then you could do something like:

int userInput = 3;
Random rand = new Random();
List<Color> myColors = new ArrayList<Color>();
while(myColors.size() < userInput){
    int index = rand.next(allMyColors.size());
    if(!myColors.contains(allMyColors.get(index))){
        myColors.add(allMyColors.get(index));
    }
}

You could of course follow this same principal with a set and shorten it up a bit:

int userInput = 3;
Random rand = new Random();
Set<Color> myColors = new HashSet<Color>();
while(myColors.size() < userInput){
    myColors.add(allMyColors.get(rand.next(allMyColors.size())));
}

Note that these are NOT the most efficient solutions you could arrive at. They will, however, probably suit most needs.

RutledgePaulV
  • 2,568
  • 3
  • 24
  • 47
0

Another option is to just shuffle the list each time and then take the first n items:

Collections.shuffle(allMyColors);
List<Color> selected = allMyColors.stream().limit(n).collect(Collectors.toList());

This is likely to be more efficient as it only randomises once unless the list of colours is very long in which case shuffle should probably be avoided. That seems pretty unlikely here.

It also deals with the situation in which n > allMyColors.size() because limit automatically truncates to the length of the stream.

sprinter
  • 27,148
  • 6
  • 47
  • 78