How would you write a shuffle algorithm?
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 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.