JRS: In article <c6pbc.506$_K3.466 (AT) nwrdny01 (DOT) gnilink.net>, seen in
news:comp.lang.javascript, Vladdy <vlad (AT) klproductions (DOT) com> posted at
Sat, 3 Apr 2004 02:14:32 :
Quote:
Jeff Thies wrote:
I'd like to randomly sort an array. A good method?
Array.prototype.swap = function(index1,index2)
{ var temp = this[index1];
this[index1] = this[index2];
this[index2] = temp;
return;
}
Array.prototype.shuffle = function()
{ for(var i=0; i<this.length; i++)
{ ind1 = Math.floor(Math.random()*this.length);
ind2 = Math.floor(Math.random()*this.length);
this.swap(ind1,ind2);
}
return;
} |
It would be interesting to find out whether a swap method is better than
in-line code in such cases. In Pascal one could pass a pointer, to
avoid repeated indexing - there ought to be a way in JS for setting a
variable to point to A[b] rather than setting to a copy of A[b] if A[b]
is a number and not an object ...
Your code calls Math.random ten times to shuffle 5 elements; it should
therefore be slower than the efficient method which calls it only five
times.
For 5 elements, your code gets a random in 1..5 ten times; there are
therefore 5^10 equi-probable possible routes and still 5! outcomes; the
former is not a multiple of the latter; therefore, Lasse's tests for
evenness will show the method to be faulty. It's hard to beat Knuth;
and, in this case, not worth trying; OTTINMODNPPSODNPDW.
Note that in some browsers Math.random() can occasionally give (at
least) 1.0; in that case, ISTM that an instance of "undefined" will
appear, if not shuffled out again. FAQ 4.22 is therefore incompletely
reliable; follow its third link.
function Randum(N) { return (N*(Math.random()%1))|0 } // %1 : Opera
also seems slightly faster (for me) than using Math.floor, though the
upper bound is lower.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)