I am working on a project where I have a base Array that consists of 5 numerical elements. Using this base array, I use a
for loop to create a new Array consisting of 250 elements (50 interations of the base array).
Here is the code, which works flawlessly:
Code:
var myArray:Array = new Array ();
// Loop through base elements to load the new array.
for (var i:Number = 0; i < 50; i++) { // 50 = multiples of base array to equal 250 elements
// push the designated elements into myArray
myArray.push (48, 49, 50, 56, 57);
}
My issue now is that I need to
shuffle or
randomize this new Array (250 elements) so that the same number (base Array element)
does not appear consecutively. I've located several randomization and shuffling code examples, but I can't seem to customize any of them to fit my particular need.
Here is what I am currently using, but I suspect that because of the limited number of base elements (5), I still get several instances of the same element appearing consecutively..., sometimes even 3 or 4 times consecutively.
Code:
// Shuffles the array's elements in place.
function shuffle (theArray) {
for (var currentElement = 0, previousElement = currentElement; currentElement < theArray.length; currentElement++){
// Remember the value of the CURRENT array element
var thisElementValue = theArray[currentElement];
// Remember the value of the LAST array element
var lastElementValue = theArray[previousElement];
// Pick a random index from the array
var randIdx = myRandom(0, theArray.length - 1);
// Ensure the selected array value does NOT match the previous array value
if (thisElementValue != lastElementValue) {
theArray[currentElement] = theArray[randIdx];
theArray[randIdx] = thisElementValue;
}
}
myNewArray = theArray;
}
// Returns an integer in the minVal to maxVal range. Used in the array shuffle.
function myRandom (minVal, maxVal) {
do {
// Keep picking a number until it is not 1
var r = Math.random();
} while (r == 1);
return minVal + Math.floor(r * (maxVal + 1 - minVal));
}
// Initiates the Array shuffle function from above
shuffle(myArray);
Any suggestions, tips, or just pointing me in the right direction would be greatly appreciated. This one issue has been kicking my butt for a day or so now, so it's time to pose the question to the
real experts.
TheMediaBoy