The object of this puzzle is to take a deck of 52 cards and shuffle it so that each card is in a random position.
Given (i.e. assumed to exist already):
- A length-52 array of integers representing the deck. When you start,
deckcontains exactly one of each card in some unknown order.
- A function,
int rand(int min, int max), that returns a random integer between
max, inclusive. You can assume that this function is truly random.
swapfunction that takes two ints (by reference) and runs the XOR swap algorithm. If you call
swap(x, y), the values of
ywill be exchanged.
deckshould contain exactly one of each integer from 0 to 51 (inclusive), in a completely random order.
- You can't declare any variables. Call
randas much as you like, but you can't declare any variables of your own.
deckcan be a global variable, or you can take it in as a parameter.
- Obviously you can change what's in
deck(that's the point), but you can't change its size.
- Card values don't really matter, but let's say they're valued in S-H-C-D order, so 0 is the ace of spades, 12 is the king of spades, and 51 is the king of diamonds.
- Execution time doesn't matter, but true randomness does.
- You can write this in any language, but no fair using stuff like PHP's
- This isn't really code golf, but feel free to minimize/obfuscate your code. Even without removing whitespace, IIRC I can do it in something like 4 lines in C# or PHP.
I have a test program somewhere around here that plots the frequency of each card in each position. I'll post it when I get the chance, or you can write you own for a little extra credit.
Edit: Here's some test code to check for randomness in your results:
- C# tester codebehind: http://pastebin.com/Z0y9mCEt
- ASP.NET: http://pastebin.com/RiuW7g25
- Stub with the
randutility methods: http://pastebin.com/atAvhuB3
As a testing method it's not terribly strong, but it makes it easy to visualize severe problems in the shuffling. Ideally, the result should look like snow without any apparent pattern. Certain mistakes in the randomization will cause noticeable patterns in the result. It also throws an exception if you don't have exactly one of every card.
Here's an example of the visualizer's output comparing two shuffle methods, one truly random and the other one only partially so:
As you can see, patterns in the results should be easy to spot.