Post Reply  Post Thread 


Randomizing Data with JavaScript
Author Message
geneticthylon
Started Website


Posts: 23
Group: Newbie
Joined: Jul 2008
Status: Offline
Reputation: 0
Post: #1
Randomizing Data with JavaScript

Often I want to show data in random order. Sometimes I just want to pick a few random things out of many. Just as often I want to show all of the information, but in a randomized order, similar to shuffling a deck of cards. To do this we can use the JavaScript sorting algorithm in combination with a customized sorting comparison function that will randomize the sorted order.

The comparison function returns a value greater than zero or less than zero depending on which element should be sorted first. When the sorting algorithm is executed the data will be randomized if the comparison function gives each comparison of elements an equal probability of being greater than zero or less than zero.

Code:
<script type="text/javascript">
randomComparison = function(a, b) {
return Math.random()-.5;
};  
domainList.sort(randomComparison);
showList(domainList);
</script>


Some high-speed sorting algorithms are unstable, and might not result in all data being truly randomized. In a sense, one could say that the sorting algorithm divides up the data too fast for the randomizing to occur. A truly random shuffling has the property that each element has the same probability of being assigned to each location, or equivalently, each permutation of objects is equally likely. As far as I know, Safari is the only browser which may have an unstable sorting algorithm, resulting in the domain uuuuu.us being sorted to the last position most of the time, although other domains appear to be randomly placed. Unstable sorting algorithms may be fine, depending on the application.

There are also iterative methods for sorting. Iterative sorting methods are useful because the computational cost of one iteration is O(N) rather than O(n log N). A precise estimate is typically from N/2 to 2N. The data is not completely sorted after one iteration, but that's fine when the data ranking is based on subjective criteria such as clicking popularity or Google PageRank. Usually a good iterative sorting method guarantees that at least the lowest and highest ranked items are sorted to the correct positions.

07-29-2008 06:30 PM
Find all posts by this user Digg this Post! Add Post to del.icio.us Bookmark Post in Technorati Furl this Post! Add blinklist Add Mongolia Add Netscape Reddit! Stumble Quote this message in a reply
Post Reply  Post Thread 

View a Printable Version
Send this Thread to a Friend
Subscribe to this Thread | Add Thread to Favorites

Forum Jump: