Reputation: 37
Does Collections.shuffle
guarantee the resulting list is not sorted in ascending or descending order?
Suppose I have a list of Strings letters
containing "a", "b", "c", "d".
After Collections.shuffle(letters)
will letters
ever be equal to a-b-c-d or d-c-b-a?
If letters
can end up ordered, is there a way to prevent Collections.shuffle
from leaving the list sorted in ascending or descending order?
Upvotes: 0
Views: 163
Reputation: 13663
Of course it doesn't, because then it wouldn't be a random shuffle. Just because those two permutations look ordered to us humans doesn't mean they should be avoided when selecting a random permutation.
If you do want to avoid ascending and descending order, you can shuffle in a loop checking whether the list is ordered.
while (isSorted(list) || isSorted(list, Comparator.reverseOrder())
Collections.shuffle(list);
with an appropriate implementation of isSorted
. (Note that this will be an infinite loop for a 0 or 1 element list!)
Upvotes: 6