问题
I have a list with N elements, I want to randomize its order.
Preferably with the least computation, and being able to use up memory (duplicating the total).
So far I've come up with:
- create new empty list, take first element from original list, insert it in new list on random position, order of magnitude seems O(N*N) but no extra memory is used.
- create a new ArrayList(capacity N) (so access is O(1)), create a new hashSet and insert all possible positions (N), take the first element of the original List and insert it in a random position of the new arrayList, remove this position form the hashSet because ti has been used.
- create a new HashSet, add all elemnts to this hashSet, and iterate over the set to create a new List and hope the order in the hashSet is random.
Seems to me the least expensive is the third option, but i'm unsure of how random the result would be. Any suggestions?
回答1:
The best way to shuffle a list is using the standard library method Collections.shuffle.
List lst = getListFromSomewhere();
Collections.shuffle(lst);
If you want to do it yourself, read up on the Fisher-Yates shuffle algorithm.
回答2:
Collections.shuffle(list); what you are looking for.
回答3:
Others already mentioned about shuffle, but if you are using gwt, shuffle is not supported and you may have to code it. Here's one approach:
public static void shuffleList(final List<String> list) {
int length = list.size();
Random random = new Random();
for (int i = 0; i < length; i++) {
// Swap index
int swap = i + random.nextInt(length - i);
// Store temporarily
String temp = list.get(i);
// Set the values
list.set(i, list.get(swap));
list.set(swap, temp);
}
}
To use, just do-
shuffleList(listOfStringsToShuffle);
来源:https://stackoverflow.com/questions/19050524/reorder-a-list-to-randomize-its-order-in-java