And of course it has the usual problem of generating permutations using a pseudo random number generater: Even for moderately sized collections, the number of permutations is far larger than the number of differnt initialization states of many common PRNGs, so even if an algorithm looks correct, it may not be able to generate all permutations. For example, a 63 bit linear congruential shift generator has 2^63 = 9x10^18 possible sequences, while there are about 52! = 80x10^66 permutations of 52 cards.
is there some random number generator in a C-like language i should investigate, as opposed to using srand() and rand()?
Actually, if your game is not about real money, this problem might be more of an academic curiosity, but there are some algorithms with very long periods, start at one of these pages to look for an algorithm with weaknesses that you can live with:
- http://en.wikipedia.org/wiki/Mersenne_twister
- http://en.wikipedia.org/wiki/Blum_Blum_Shub
- http://en.wikipedia.org/wiki/Pseudorandom_number_generator
This is a problem, but it will be a problem no matter what algorithm you choose. You can always use something like http://www.random.org/ or special hardware, but I'd just look to /dev/random and whatever your default psudo-random generator is for your platform.
2^32 = 4294967296
100! is about 10^158
So for just 100 items, you're already missing most of your outcome space. You might switch to a generator with a bigger seed. For this example with 100 items, you need at least
log(100 !) / log(2) = 524.764993
bits in your seed. For N items to be sorted, you need about NlogN bits in your seed. So if you're trying to actually make each outcome possible, then no matter which clever algorithm you use to go from random numbers to a shuffled sequence, you've already lost.
But, as I remarked earlier, if this is just for a game that is for fun where opponents can't cheat you or other players out of large amounts of money by predicting which permutations may or may not occurr, you may get away with whatever PRNG you have at hand and only swap is out once many players start to complain that they had this very hand one or two billon games ago.
(N.b.: this post ended up being mostly the same point as fhars, only phrased differently.)
However, this is tricky to achieve. It requires either:
- an infinite source of random numbers
- a psuedo random number generator whose pool size (the # of random numbers it can generate) is an even multiple of N! (If not, then it have bias towards certain shuffles almost by definition.)
Here's what happens when someone does it all wrong -- the wrong shuffle algorithm and, far more devastatingly, a poor PRNG choice:
http://www.cigital.com/papers/download/developer_gambling.ph...
(Consider that if your PRNG takes a 32-bit seed, there will be at most be 2^32 possible shuffles, even with a correctly perfect shuffling algorithm --- few enough for an attacker to pre-calculate every possible shuffle to use against you.)