Home > AS2, AS3 > Array Randomness

Array Randomness

One of the simple things that I use (and get asked about) a lot is a way to get random values from an array, here a couple of ways of doing it.

The simplest way of getting random values from an array is by creating a random index number and using it to access the array:

//Array you want to pull values from
var myArray:Array = ["hello", "world", 11, 8, 86, {prop: "value"}];

//Trace a random value from the array
trace(getRandomValue(myArray));

function getRandomValue(array:Array):*{
	//Generate a random number to use as an index for the array
	var index:Number = Math.floor( Math.random() * array.length );
	//Return the value associated with the random index
	return array[index];
}

If you try tracing out the value more than once, you’ll notice that sometimes you get the same value two or more times in a row. What if we just want to pull a unique random value from the array? We can do that by removing the selected value from the array so next time we ask for a random value, the previous values that were chosen will not be available again:

var myArray:Array = ["hello", "world", 11, 8, 86, {prop: "value"}];

trace("Original Array: "+myArray);
trace(getRandomValue(myArray));
trace("Original Array: "+myArray);

function getRandomValue(array:Array):*{
	//Generate a random number to use as an index for the array
	var index:Number = Math.floor( Math.random() * array.length );
	//Remove the selected value from the array using the splice method, and return it
	return array.splice(index, 1)[0];
}

If you run the code above, you’ll notice that the value selected by our getRandomValue() function edits the array and removes the value so next time we ask for another random value, it won’t be there for the function to select.

This is all good, but what happens if we want to get a unique random value without editing the original array? This is where the slice() method comes in to help, it returns a duplicate of the array you’re slicing:

var myArray:Array = ["hello", "world", 11, 8, 86, {prop: "value"}];

//Create a copy of the original array and assign it to a new variable
var arrayCopy:Array = myArray.slice();

trace(getRandomValue(arrayCopy));
trace("Original Array: "+myArray);
trace("Duplicate Array: "+arrayCopy);

function getRandomValue(array:Array):*{
	//Generate a random number to use as an index for the array
	var index:Number = Math.floor( Math.random() * array.length );
	//Remove the selected value from the array using the splice method, and return it
	return array.splice(index, 1)[0];
}

In our code above, we create a duplicate of our original array and use it to get unique random values. This prevents us from editing the original.

Pretty simple, right?

Categories: AS2, AS3 Tags:
  1. No comments yet.
  1. No trackbacks yet.