...

View Full Version : Shuffling Arrays



Lerura
06-12-2012, 08:36 AM
Running toSource() on a shuffled array, I found that an array shuffled by
a common function:

function Shuffle(Arr){
TempArr=[];
while(Arr.length){TempArr.push(Arr.splice(CalculatedNumber,1));}
while(TempArr.length){Arr.push(TempArr.pop();}
return Arr;
}

gains an extra dimension.
(most shuffle functions found in these forums, are quite similar to this).

Effect:

MyArray=;
ImgElement.src=Myarray[0]; // gives: ImgElement.src=ImgSrc1;
Shuffle(MyArray);
ImgElement.src=Myarray[0]; // gives: ImgElement.src=[ImgSrc[I]X];
In spite of the extra dimension, it would still give the desired outcome.

But sometimes multi-dimensionals array are shuffled, and then this extra dimension will cause troubles.
(often used for banners):

MyArray=[,[ImgSrc2,Link2],[ImgSrc3,Link3]];
ImgElement.src=Myarray[0][0]; // gives: ImgElement.src=ImgSrc1;
LinkElement.href=Myarray[0][1]; // gives: LinkElement.href=ImgSrc1;
Shuffle(MyArray);
ImgElement.src=Myarray[0][0]; // gives: ImgElement.src=[ImgSrc[I]X,LinkX]; OOPS!
LinkElement.href=Myarray[0][1]; // gives: LinkElement.href=undefined; OOPS!


Solution:

... while(Arr.length){TempArr.push(Arr.splice(CalculatedNumber,1)[0]);} ...

Addressing the above problem and wanting to use the same function for both:
shuffling an array.
(Usually Shuffle(MyArray);
and
shuffling an copy of the array (without shuffling the original array).
(Usually MyArrayCopy = MyArray.slice(0); Shuffle(MyArrayCopy);)
- I came up with this:

function shuffle(Arr){
var NewArr=Arr.slice(0);
var Range=NewArr.length;
while(Range>0){
NewArr.push(NewArr.splice(Math.floor(Math.random()*Range),1)[0]);
Range--;
}
return NewArr;
};

Usage:
Shuffling an array is done by: Array=shuffle(Array);
Making a shuffled Copy is done by: ArrayCopy=shuffle(OrgArray);



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum