views:

150

answers:

4

What will prompt one to use this method?

Update : I see the point now. I like the reason of Uri "Shuffling is not a trivial algorithm". That is quite true.

+4  A: 

Um, if you have a collection, and you want to shuffle it...

The most obvious example would be a card game, where you have objects representing individual cards, and a collection representing the deck which you want to shuffle.

Another example might be if you're presenting the user with multiple answers in a questionnaire, and you don't want there to be any bias due to the ordering of the answers - so you present each user a shuffled set of answers to pick from.

Jon Skeet
+1  A: 

Well, imagine you're modeling a deck of cards. Shuffle would be one of the first functions you'd write.

Anytime you'd want to randomize the contents of a collection, you'd use shuffle.

Alan
+10  A: 

There can be many reasons one would want to randomly shuffle an ordered sequence of elements. For instance, a deck of cards.

Shuffling is not a trivial algorithm, just as sorting isn't - So it is common enough to necessitate a library function.

As to why a list - obviously it has to be an ordered collection, thus not any general Collection. Only list and its subtypes are guaranteed to be ordered. The Collections class does not provide operations for arrays, but you could (and probably should, for performance) pass an ArrayList to this method.

Uri
+1 for the last paragraph
jensgram
... in fact the implementation is pretty trivial. Each element gets a new index, if the slot is already occupied, the collection (or iterator) calculates the next free slot.
Andreas_D
@Andreas_D don't underestimate it, you have to be careful to use an algo in which all permutations are equally likely, so it's not completely trivial - see http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
Jesper
... just looked at the actual implementation in Collections. There it is solved pretty easy. But maybe not optimal.
Andreas_D
I've seen the permutation algorithm appearing in job interviews, so it is definitely not complete trivial. I also use Collections.sort() even though I know how to write quicksort :)
Uri
+1  A: 

Some ideas how you could use this method:

  • Shuffle cards in a game
  • Randomize an array in a test case for a sorting algorithm
  • Shuffling test cases in your test suite to make sure they don't depend on each other
  • If you try to solve an NP-complete problem like the traveling salesman, one approach is to take the input, shuffle it several times and then use the result with the shortest length. This gives you a solution which runs in O(N) time (where N is the number of nodes).
Aaron Digulla