I needed to create code for a number of indexed elements to be displayed in a random order.
Or, for example: I have a CD with ten tracks, and I want to play them in a random order, so I need to create an Array with ten elements; each element a unique number from 1 to 10.
Or: a deck of numbered cards gets shuffled:
private var shuffle:Array;
private function fillShuffle(shuffleLength:int):void {
shuffle = new Array();
// set the first element:
shuffle.push(Math.ceil(Math.random() * shuffleLength)); // from 1 to shuffleLength
for (var i:int = 1; i < shuffleLength; i++) {
fillShufflePos(i, shuffleLength);
}
trace(shuffle);
}
private function fillShufflePos(shufflePos:int, shuffleLength:int):void {
var nextElement = Math.ceil(Math.random() * shuffleLength);
var isUnique:Boolean = true;
for (var i:int = 0; i < shufflePos; i++) {
if (shuffle* == nextElement) {
isUnique = false;
}
}
if (isUnique) {
shuffle.push(nextElement);
} else {
fillShufflePos(shufflePos, shuffleLength);
}
}
Is there a more efficient way to create an Array like this?