In comp.lang.javascript message <
[email protected]>
, Tue, 11 Dec 2007 13:57:37, Erwin Moller <Since_humans_read_this_I_am_s
(e-mail address removed)> posted:
That is a very bad way, in principle, of shuffling. <FAQENTRY> Don't do
that. </FAQENTRY>. Method sort is, IIRC, defined to require a stable
comparison; and with an unstable comparison the result is undefined. It
might never finish ... . Follow Knuth.
I don't think that can be accomplished in 1 go.
Probably simplest approach is:
1) Create an array MyIndexes, containing 0,1,2,3....
Put in there the number of elements your original array contains.
Doesn't matter which since they have the same amount of items.
2) randomize MyIndexes
No need for using 1 & 2 to get that. A slight simplification of the
standard shuffling algorithm gives a dealing algorithm.
function Shuffle(Q) { var J, K, T
for (J=Q.length-1 ; J>0 ; J--)
{ K = Random(J+1) ; T = Q[J] ; Q[J] = Q[K] ; Q[K] = T }
return Q }
function Deal(N) { var J, K, Q = new Array(N)
for (J=0 ; J<N ; J++)
{ K = Random(J+1) ; Q[J] = Q[K] ; Q[K] = J }
return Q }
Those could no doubt be modified to look more similar.
3) read out MyIndexes, and rebuild the 2 arrays based on the found
indexes in MyIndexes.
or 3a) Don't rebuild the arrays, but use MyIndexes to determine the
order in which they are read out.
Another approach - create a new array of objects (or of arrays) in which
each object (or array) contains the corresponding elements of the
original arrays. AOO[1] is {k:key1, v:value1} etc. Now randomize the
array of objects, then either read out into separate arrays or use as
they are.
Yet another approach - use the function Shuffle above, but modified to
take several array arguments (or an array of array arguments) and to
have a single main loop which exchanges elements in the same manner in
each array.
The OP should have noted what the FAQ says about shuffle.
It's a good idea to read the newsgroup c.l.j and its FAQ. See below.