Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.shuffle(List list)

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.

like image 759
fastcodejava Avatar asked May 31 '10 06:05

fastcodejava


4 Answers

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.

like image 148
Uri Avatar answered Nov 08 '22 13:11

Uri


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.

like image 23
Jon Skeet Avatar answered Nov 08 '22 14:11

Jon Skeet


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.

like image 32
Alan Avatar answered Nov 08 '22 14:11

Alan


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).
like image 28
Aaron Digulla Avatar answered Nov 08 '22 15:11

Aaron Digulla