9

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));
5
  • 3
    You don't want them to be unique? If so why do you need to compare them, what you have should work fine. Commented Jul 18, 2011 at 12:38
  • Your title and question are conflicting. Do you or do you not want unique? Commented Jul 18, 2011 at 12:39
  • You don't or you do? Please clarify the contradicting title. Commented Jul 18, 2011 at 12:39
  • Sorry, I expressed myself bad... I will change the question. Commented Jul 18, 2011 at 12:40
  • @alex: Maybe convert that to an answer? Commented Jul 18, 2011 at 12:40

1 Answer 1

19

Shuffle the array and then slice the first 5 elements.

This will guarantee 5 unique random elements.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent idea... I also added the code to my question. Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.