This post originated from an RSS feed registered with Java Buzz
by Mike Shoemaker.
Original Post: How would you write a shuffle algorithm?
Feed Title: Unruly Rambling (java category)
Feed URL: http://www.shoesobjects.com/blog/feed.xml?flavor=rss20&category=java
Feed Description: My thoughts on software, technology, and life in general
As I'm beginning to write my card game application, I've approached the unit test where I need to shuffle the deck. I've implemented it based on Knuth's Shuffle algorithm. My question is, what are some clever ways that other programmers have implemented it?
My current implementation works like this.
Put all 52 cards in an array
For Loop starting at element 51, working backwards
Generate random number between 0 and loop element index
Swap current element card with the element at the random index generated in previous step
Finish when loop index reaches the zero element.
Delima's with current implementation
Is there a bias with generating a random number between 0 and the loop index? I'm doing so with java.util.Random
Would multiple shuffle iterations over the deck solve this?
Is it worth refactoring the shuffle algorithm to use the strategy pattern so I can have multiple implementations of shuffle? After all, this is a simple command line game, not Harrah's next killer online gambling app.