Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick random element from array, but unique

Tags:

java

arrays

I have array of countries. I want to pick 5 random countries from my array list, but I want them to be unique. This is what I have so far:

String allCountries[] = {"Finland", "Latvia", "Poland", "Afghanistan", "Albania", "Algeria"};

String country1 = (allCountries[new Random().nextInt(allCountries.length)]);
String country2 = (allCountries[new Random().nextInt(allCountries.length)]);
String country3 = (allCountries[new Random().nextInt(allCountries.length)]);
String country4 = (allCountries[new Random().nextInt(allCountries.length)]);
String country5 = (allCountries[new Random().nextInt(allCountries.length)]);

What is the best way to compare those strings while generating random elements?

Edit:

I expressed myself bad. The problem I have is that I don't want string country1, country 2 etc. to be same... so I want them to be always different.

Solution:

Collections.shuffle(Arrays.asList(allCountries));
like image 620
Badr Hari Avatar asked Jul 18 '11 12:07

Badr Hari


1 Answers

Shuffle the array and then slice the first 5 elements.

This will guarantee 5 unique random elements.

like image 171
alex Avatar answered Sep 30 '22 03:09

alex