One-liner syndrom

Jeff Atwood talks about card shuffling algorithms in a recent blog post.

As it turns out, the easiest way to implement a shuffle is by sorting. It’s not exactly faster, as the typical sort is O(n log n) compared to the O(n) of the Knuth Fisher-Yates shuffle algorithm. We’ll just sort by a random number– in this case, a GUID.

   var cards = Enumerable.Range(0, 51);
   var shuffledcards = cards.OrderBy(a => Guid.NewGuid());

So we can ultimately implement a secure, unbiased shuffle as a one-liner in a modern programming language.

The obligatory nerd response here is to bang out the one-liner in your language of choice. Here’s one for Python:

>>> from random import random
>>> shuffled = [ b for (a,b) in sorted((random(), x) for x in cards) ]

Posted in , | | Leave a response

Leave a Reply