Undefined
Undefined

Reputation: 1929

Random permutation of letters

I have cities: A, B, C, D, E

How can I generate an initial solution in Java that contains all of these elements once? For example: BCDAE

Currently I'm generating a solution in order ABCDE then mixing it up, is there an easier way to do this I'm just not thinking of?

Upvotes: 2

Views: 1272

Answers (1)

Bohemian
Bohemian

Reputation: 424953

I would use the Collections API to give me a one-liner:

List<String> letters;
Collections.shuffle(letters);

Collections.shuffle() puts the elements in a random order.

Here's a little test. Every time you run this, you'll get random order output:

public static void main( String[] args ) {
    List<String> letters = Arrays.asList( "A", "B", "C", "D", "E" );
    Collections.shuffle( letters );
    System.out.println( letters );
}

Upvotes: 4

Related Questions