Thnks for the reply TheCanadian. Your method makes sense, but I need to keep the original array intact as I have other other functions that use it. Is there another way to select x number of random elements from an array?
If each item exists only once there can be still a repetition when it wraps around. So, that’s a special case you might want to handle. The simplest method would be to check if the currently drawn item matches the previous one and if so draw again. While that slightly skews the distribution, it’s probably good enough.
Durrr, you’re right, ignore me and my brainfart. :lol:
I think you meant [FONT=Courier New]slice [/FONT]though, not [FONT=Courier New]splice[/FONT]. Obviously, they both work, but if you start trying to only return certain elements you’ll start ripping them out of the original.
var myArray:Array = ["cat", "dog", "rat"]
var tempArray = myArray.splice();
tempArray = [];
trace(tempArray); //traces nothing
trace(myArray); //traces the original array
[QUOTE=Anogar;2343321]Durrr, you’re right, ignore me and my brainfart. :lol:
I think you meant [FONT=Courier New]slice [/FONT]though, not [FONT=Courier New]splice[/FONT]. Obviously, they both work, but if you start trying to only return certain elements you’ll start ripping them out of the original. [/QUOTE]
Ignore my brainfart :hugegrin:
[QUOTE=dthought;2343324]Forgive my ignorance here, but wouldn’t using the new operator solve this without slice / splicing?
var myArray:Array = new Array('cat', 'dog','bird');
var otherArray:Array = new Array(myArray);
otherArray.push('fish');
trace (myArray == otherArray);
[/QUOTE]
No because that pushes the entire original array as the first element of the new one:
var myArray:Array = new Array('cat', 'dog','bird');
var otherArray:Array = new Array(myArray);
trace(otherArray[0] is Array); //true
var indices = new Array();
var selectedSprites:Array = new Array(); // to hold the ones we pick
for(var i:int = 0; i<indices.length; i++)
{
indices* = i;
}
for(i = 0; i < 4; i++) // say you want to pick 4 sprites
{
// pick a random position in indices
var r = Math.floor(Math.random()*indices.length);
// get the sprite in that position
var pickedSprite = tempTileArray[r];
// add that sprite to our selection
selectedSprites.push(pickedSprite);
// remove that position from indices
indices.splice(i,1);
}