<p>First off, this question is ripped out from <a href="https://stackoverflow.com/questions/56215/interesting-interview-questions#56291">this</a> question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me.</p>

<p>Assume that you have a algorithm that generates randomness. Now how do you test it?
Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm?</p>

<p>To add some theory to the problem -
A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!.</p>

<p>What is the chance that you, after shuffling, will get A, K, Q, J ... of each suit in a sequence? Answer 1 / 52!</p>

<p>So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more...</p>

<p>How would you black box test a shuffling algorithm for randomness?</p>

[{'answer_id': 56420, 'author': 'Deinumite', 'author_id': 5219, 'author_profile': 'https://Stackoverflow.com/users/5219', 'pm_score': 2, 'selected': False, 'text': '<p>Shuffle alot, and then record the outcomes (if im reading this correctly). I remember seeing comparisons of "random number generators". They just test it over and over, then graph the results.</p>\n\n<p>If it is truly random the graph will be mostly even.</p>\n'}, {'answer_id': 56428, 'author': 'kranzky', 'author_id': 5442, 'author_profile': 'https://Stackoverflow.com/users/5442', 'pm_score': 2, 'selected': False, 'text': "<p>The only way to test for randomness is to write a program that attempts to build a predictive model for the data being tested, and then use that model to try to predict future data, and then showing that the uncertainty, or entropy, of its predictions tend towards maximum (i.e. the uniform distribution) over time. Of course, you'll always be uncertain whether or not your model has captured all of the necessary context; given a model, it'll always be possible to build a second model that generates non-random data that looks random to the first. But as long as you accept that the orbit of Pluto has an insignificant influence on the results of the shuffling algorithm, then you should be able to satisfy yourself that its results are acceptably random.</p>\n\n<p>Of course, if you do this, you might as well use your model <em>generatively</em>, to actually create the data you want. And if you do that, then you're back at square one.</p>\n"}, {'answer_id': 56447, 'author': 'Dan Dyer', 'author_id': 5171, 'author_profile': 'https://Stackoverflow.com/users/5171', 'pm_score': 6, 'selected': True, 'text': '<p>Statistics.  The de facto standard for testing RNGs is the <a href="https://web.archive.org/web/20150103230339/http://stat.fsu.edu/pub/diehard/" rel="nofollow noreferrer">Diehard suite</a> (originally available at <a href="http://stat.fsu.edu/pub/diehard" rel="nofollow noreferrer">http://stat.fsu.edu/pub/diehard</a>).  Alternatively, the <a href="ftp://ftp.fourmilab.ch/web/random/index.html" rel="nofollow noreferrer">Ent program</a> provides tests that are simpler to interpret but less comprehensive.</p>\n\n<p>As for shuffling algorithms, use a well-known algorithm such as <a href="http://en.wikipedia.org/wiki/Knuth_shuffle" rel="nofollow noreferrer">Fisher-Yates</a> (a.k.a "Knuth Shuffle").  The shuffle will be uniformly random so long as the underlying RNG is uniformly random.  If you are using Java, this algorithm is available in the standard library (see <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#shuffle(java.util.List)" rel="nofollow noreferrer">Collections.shuffle</a>).</p>\n\n<p>It probably doesn\'t matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained <a href="http://blog.uncommons.org/2008/04/10/a-java-programmers-guide-to-random-numbers-part-3-seeding/" rel="nofollow noreferrer">here</a>).</p>\n'}, {'answer_id': 56452, 'author': 'Baltimark', 'author_id': 1179, 'author_profile': 'https://Stackoverflow.com/users/1179', 'pm_score': 0, 'selected': False, 'text': '<p>I\'m not fully following your question. You say</p>\n\n<blockquote>\n  <p>Assume that you have a algorithm that generates randomness. Now how do you test it?</p>\n</blockquote>\n\n<p>What do you mean? If you\'re assuming you can generate randomness, there\'s no need to test it. </p>\n\n<p>Once you have a good random number generator, creating a random permutation is easy (e.g. Call your cards 1-52. Generate 52 random numbers assigning each one to a card in order, and then sort according to your 52 randoms) . You\'re not going to destroy the randomness of your good RNG by generating your permutation. </p>\n\n<p>The difficult question is whether you can trust your RNG.  <a href="http://csrc.nist.gov/groups/ST/toolkit/rng/index.html" rel="nofollow noreferrer">Here\'s</a> a sample link to people discussing that issue in a specific context. </p>\n'}, {'answer_id': 56460, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 3, 'selected': False, 'text': '<p>First, it is impossible to know for sure if a certain finite output is "truly random" since, as you point out, <a href="http://www.virtualp.us/Dilbert-Oct_25_001.jpg" rel="noreferrer">any output is possible</a>.</p>\n\n<p>What can be done, is to take a sequence of outputs and check various measurements of this sequence against what is more likely.  You can derive a sort of confidence score that the generating algorithm is doing a good job.</p>\n\n<p>For example, you could check the output of 10 different shuffles.  Assign a number 0-51 to each card, and take the average of the card in position 6 across the shuffles.  The convergent average is 25.5, so you would be surprised to see a value of 1 here.  You could use the central limit theorem to get an estimate of how likely each average is for a given position.</p>\n\n<p>But we shouldn\'t stop here!  Because this algorithm could be fooled by a system that only alternates between two shuffles that are designed to give the exact average of 25.5 at each position.  How can we do better?</p>\n\n<p>We expect a uniform distribution (equal likelihood for any given card) at each position, across different shuffles.  So among the 10 shuffles, we could try to verify that the choices \'look uniform.\'  This is basically just a reduced version of the original problem.  You could check that the standard deviation looks reasonable, that the min is reasonable, and the max value as well.  You could also check that other values, such as the closest two cards (by our assigned numbers), also make sense.</p>\n\n<p>But we also can\'t just add various measurements like this ad infinitum, since, given enough statistics, any particular shuffle will appear highly unlikely for some reason (e.g. this is one of very few shuffles in which cards X,Y,Z appear in order).  So the big question is: which is the right set of measurements to take?  Here I have to admit that I don\'t know the best answer.  However, if you have a certain application in mind, you can choose a good set of properties/measurements to test, and work with those -- this seems to be the way cryptographers handle things.</p>\n'}, {'answer_id': 56466, 'author': 'Ian G', 'author_id': 5764, 'author_profile': 'https://Stackoverflow.com/users/5764', 'pm_score': 2, 'selected': False, 'text': "<p>There's a lot of theory on testing randomness. For a very simple test on a card shuffling algorithm you could do a lot of shuffles and then run a chi squared test that the probability of each card turning up in any position was uniform. But that doesn't test that consecutive cards aren't correlated so you would also want to do tests on that.</p>\n\n<p>Volume 2 of Knuth's Art of Computer Programming gives a number of tests that you could use in sections 3.3.2 (Empirical tests) and 3.3.4 (The Spectral Test) and the theory behind them.</p>\n"}, {'answer_id': 56476, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 0, 'selected': False, 'text': '<p>Testing 52! possibilities is of course impossible.  Instead, try your shuffle on smaller numbers of cards, like 3, 5, and 10.  Then you can test billions of shuffles and use a histogram and the chi-square statistical test to prove that each permutation is coming up an "even" number of times.</p>\n'}, {'answer_id': 56509, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 0, 'selected': False, 'text': '<p>No code so far, therefore I copy-paste a testing part from <a href="https://stackoverflow.com/questions/56215#56379">my answer</a> to the original question.</p>\n\n<pre><code>  // ...\n  int main() {\n    typedef std::map&lt;std::pair&lt;size_t, Deck::value_type&gt;, size_t&gt; Map;\n    Map freqs;    \n    Deck d;\n    const size_t ntests = 100000;\n\n    // compute frequencies of events: card at position\n    for (size_t i = 0; i &lt; ntests; ++i) {\n      d.shuffle();\n      size_t pos = 0;\n      for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos) \n        ++freqs[std::make_pair(pos, *j)]; \n    }\n\n    // if Deck.shuffle() is correct then all frequencies must be similar\n    for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)\n      std::cout &lt;&lt; "pos=" &lt;&lt; j-&gt;first.first &lt;&lt; " card=" &lt;&lt; j-&gt;first.second \n                &lt;&lt; " freq=" &lt;&lt; j-&gt;second &lt;&lt; std::endl;    \n  }\n</code></pre>\n\n<p>This code does not test randomness of underlying pseudorandom number generator. Testing PRNG randomness is a whole branch of science.</p>\n'}, {'answer_id': 56576, 'author': 'Dan Dyer', 'author_id': 5171, 'author_profile': 'https://Stackoverflow.com/users/5171', 'pm_score': 3, 'selected': False, 'text': '<p>Here\'s one simple check that you can perform.  It uses generated random numbers to estimate Pi.  It\'s not proof of randomness, but poor RNGs typically don\'t do well on it (they will return something like 2.5 or 3.8 rather ~3.14).</p>\n\n<p>Ideally this would be just one of many tests that you would run to check randomness.</p>\n\n<p>Something else that you can check is the <a href="http://en.wikipedia.org/wiki/Standard_deviation" rel="noreferrer">standard deviation</a> of the output.  The expected standard deviation for a uniformly distributed population of values in the range 0..n approaches n/sqrt(12).</p>\n\n<pre><code>/**\n * This is a rudimentary check to ensure that the output of a given RNG\n * is approximately uniformly distributed.  If the RNG output is not\n * uniformly distributed, this method will return a poor estimate for the\n * value of pi.\n * @param rng The RNG to test.\n * @param iterations The number of random points to generate for use in the\n * calculation.  This value needs to be sufficiently large in order to\n * produce a reasonably accurate result (assuming the RNG is uniform).\n * Less than 10,000 is not particularly useful.  100,000 should be sufficient.\n * @return An approximation of pi generated using the provided RNG.\n */\npublic static double calculateMonteCarloValueForPi(Random rng,\n                                                   int iterations)\n{\n    // Assumes a quadrant of a circle of radius 1, bounded by a box with\n    // sides of length 1.  The area of the square is therefore 1 square unit\n    // and the area of the quadrant is (pi * r^2) / 4.\n    int totalInsideQuadrant = 0;\n    // Generate the specified number of random points and count how many fall\n    // within the quadrant and how many do not.  We expect the number of points\n    // in the quadrant (expressed as a fraction of the total number of points)\n    // to be pi/4.  Therefore pi = 4 * ratio.\n    for (int i = 0; i &lt; iterations; i++)\n    {\n        double x = rng.nextDouble();\n        double y = rng.nextDouble();\n        if (isInQuadrant(x, y))\n        {\n            ++totalInsideQuadrant;\n        }\n    }\n    // From these figures we can deduce an approximate value for Pi.\n    return 4 * ((double) totalInsideQuadrant / iterations);\n}\n\n/**\n * Uses Pythagoras\' theorem to determine whether the specified coordinates\n * fall within the area of the quadrant of a circle of radius 1 that is\n * centered on the origin.\n * @param x The x-coordinate of the point (must be between 0 and 1).\n * @param y The y-coordinate of the point (must be between 0 and 1).\n * @return True if the point is within the quadrant, false otherwise.\n */\nprivate static boolean isInQuadrant(double x, double y)\n{\n    double distance = Math.sqrt((x * x) + (y * y));\n    return distance &lt;= 1;\n}\n</code></pre>\n'}, {'answer_id': 56731, 'author': 'Tnilsson', 'author_id': 4165, 'author_profile': 'https://Stackoverflow.com/users/4165', 'pm_score': -1, 'selected': False, 'text': '<p>Pondering it myself, what I would do is something like:</p>\n\n<p>Setup (Pseudo code)</p>\n\n<pre><code>// A card has a Number 0-51 and a position 0-51\nint[][] StatMatrix = new int[52][52]; // Assume all are set to 0 as starting values\nShuffleCards();\nForEach (card in Cards) {\n   StatMatrix[Card.Position][Card.Number]++;\n}\n</code></pre>\n\n<p>This gives us a matrix 52x52 indicating how many times a card has ended up at a certain position. Repeat this a large number of times (I would start with 1000, but people better at statistics than me may give a better number).</p>\n\n<p>Analyze the matrix</p>\n\n<p>If we have perfect randomness and perform the shuffle an infinite number of times then for each card and for each position the number of times the card ended up in that position is the same as for any other card. Saying the same thing in a different way:</p>\n\n<pre><code>statMatrix[position][card] / numberOfShuffle = 1/52.\n</code></pre>\n\n<p>So I would calculate how far from that number we are.</p>\n'}, {'answer_id': 39882841, 'author': 'jgmjgm', 'author_id': 1918268, 'author_profile': 'https://Stackoverflow.com/users/1918268', 'pm_score': 0, 'selected': False, 'text': "<p>For a quick test, you can always try compressing it. Once it doesn't compress, then you can move onto other tests.</p>\n\n<p>I've tried dieharder but it refuses to work for a shuffle. All tests fail. It is also really stodgy, it wont let you specify the range of values you want or anything like that.</p>\n"}]
['https://Stackoverflow.com/questions/56411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4165/']