While reading through some of Jeff Atwood's old blog entries, I stumbled across this gem: The Danger of Naivete. In it, Jeff discussed the pitfalls the can befall a programmer who implements a naive algorithm and calls it a day. Consider an algorithm to randomly reorder an array. If you have a collection of items to reorder, the naive approach is to enumerate each element and swap its position with an element in some other randomly-selected position. However, such an algorithm (as we discuss in this article), does not have an even distribution of results - certain permutations are more likely than others when starting from a set point.
Jeff's blog entry caught my attention because of a past article I wrote here on 4Guys, Randomly Reordering an Array. That article, written back in 2000, showed various techniques for reordering an array in classic ASP using VBScript. And, wouldn't you know it, the first technique uses the exact same naive algorithm Jeff warns about in his blog post! Oops! (I've since updated the old article.)
After learning of the problems with the naive algorithm I decided to spend some time exploring approaches that produce valid distributions.
This article shows why the naive algorithm produces less than ideal results and includes code for two alternative solutions.
Read on to learn more!
Read More >
