ActionScript 3.0 Cookbook: Chapter 5, Arrays
Pages: 1, 2, 3, 4, 5, 6, 7, 8

Section 5.12: Randomizing the Elements of an Array

Problem

You want to randomize the elements of an array.

Solution

Use the sort( ) method with a compare function that randomly returns a positive or negative number.

Discussion

There are lots of scenarios in which you might plausibly want to randomize the elements of an array. For example, you may have a game in which you want to randomize the letters of a word. Since you already know how to split the letters into elements of an array using the split( ) method, you may need to randomize those elements. Or perhaps you are making a card game where each element in the array is a card, and you want to shuffle the deck.

There is more than one way to accomplish the task. However, one of the simplest ways is to create a compare function that randomly returns a positive or negative number, and use it in the sort( ) method. See Recipe 5.11 for more information on compare functions.

The following is probably the simplest possible compare function for the job:

function randomSort(elementA:Object, elementB:Object):Number {
    return Math.random( ) - .5
}

Math.random( ) returns a number between 0.0 and 1.0. If you subtract 0.5 from that number, you'll get a random number between -0.5 and 0.5. Remember that in a compare function, returning a negative number means to order the first element first, and a positive number tells the sort( ) method to put the second element first. Since the odds you'll return are 50/50, the resulting order of the array is completely random.

The following is an example of randomizing an array:

var numbers:Array = new Array( );
for(var i:int=0;i<20;i++) {
    numbers[i] = i;
}
numbers.sort(randomSort);
for(var i:int=0;i<numbers.length;i++) {
    trace(numbers[i]);
}

This creates an array of 20 sequential numbers, and then randomizes and displays them. You can verify that the order is now quite random.

See Also

Recipe 5.11 for more information on compare functions.

Section 5.13: Getting the Minimum or Maximum Element

Problem

You want to retrieve the minimum or maximum element from an array of numbers.

Solution

Sort the array numerically, and then retrieve the first or last element from the sorted array.

Discussion

You can quickly retrieve the minimum or maximum value from an array by sorting it. The following example illustrates how to do just that:

var scores:Array = [10, 4, 15, 8];
scores.sort(Array.NUMERIC);
trace("Minimum: " + scores[0]);
trace("Maximum: " + scores[scores.length - 1]);

Of course, if the existing order of the array is important, you'll want to make a copy of the array before sorting it. See Recipe 5.8.

You can optionally use the ArrayUtilities.min( ) and ArrayUtilities.max( ) methods.

See Also

Recipe 5.8


This excerpt is from ActionScript 3.0 Cookbook. Well before Ajax and Windows Presentation Foundation, Macromedia Flash provided the first method for building "rich" web pages. Now, Adobe is making Flash a full-fledged development environment, and learning ActionScript 3.0 is key. That's a challenge for even the most experienced Flash developer. This Cookbook offers more than 300 solutions to solve a wide range of coding dilemmas, so you can learn to work with the new version right away.

buy button

Section 5.14: Comparing Arrays

Problem

You want to compare two arrays to see if they are equivalent.

Solution

Loop through each element of both arrays and compare them.

Discussion

Since arrays are reference datatypes, using an equality operator with two array variables only checks to see if they point to the same spot in memory. For example:

var letters:Array = ["a", "b", "c", "d"];
var lettersPointer:Array = letters;
trace(letters == lettersPointer);  // Displays: true

However, if two arrays are equivalent yet don't point to the same spot in memory, an equality operation returns false:

var letters1:Array = ["a", "b", "c", "d"];
var letters2:Array = ["a", "b", "c", "d"];
trace(letters1 == letters2];  // Displays: false

Instead, you can loop through each of the elements of the arrays and compare them:

var equivalent:Boolean = true;
for(var i:int = 0; i < letters1.length; i++) {
    if(letters1[i] != letters2[i]) {
        equivalent = false;
        break;
    }
}
trace(equivalent);  // Displays: true

Optionally, you can use the ArrayUtilities.equals( ) method. This method requires two parameters: the references to the two arrays to compare. The method returns a Boolean value that indicates whether the arrays are equivalent or not:

var letters1:Array = ["a", "b", "c", "d"];
var letters2:Array = ["a", "b", "c", "d"];
trace(ArrayUtilities.equals(letters1, letters2));
// Displays: true

By default, the order of the elements has to match in the two arrays. If you don't care whether the order of the elements matches, you can specify a third parameter for the equals( ) method; a Boolean value indicating whether or not the order should be disregarded:

var letters1:Array = ["a", "b", "c", "d"];
var letters2:Array = ["b", "a", "d", "c"];
trace(ArrayUtilities.equals(letters1, letters2));
// Displays: false
trace(ArrayUtilities.equals(letters1, letters2, true));
// Displays: true

The equals( ) method is fairly simple. The code is explained in the comments in the following code block:

public static function equals(arrayA:Array, 
                              arrayB:Array,
                              bNotOrdered:Boolean):Boolean {

    // If the two arrays don't have the same number of elements,
    // they obviously are not equivalent.
    if(arrayA.length != arrayB.length) {
        return false;
    }

    // Create a copy of each so that anything done to the copies 
    // doesn't affect the originals.
    var arrayACopy:Array = arrayA.concat( );
    var arrayBCopy:Array = arrayB.concat( );

    // If the order of the elements of the two arrays doesn't 
    // matter, sort the two copies so the order of the copies 
    // matches when comparing.
    if(bNotOrdered) {
        arrayACopy.sort( );
        arrayBCopy.sort( );
    }

    // Loop through each element of the arrays, and compare them. 
    // If they don't match, delete the copies and return false.
    for(var i:int = 0; i < arrayACopy.length; i++) {
        if(arrayACopy[i] != arrayBCopy[i]) {
            delete arrayACopy;
            delete arrayBCopy;
            return false;
        }
    }

    // Otherwise the arrays are equivalent. 
    // So delete the copies and return true.
    delete arrayACopy;
    delete arrayBCopy;
    return true;
}

Section 5.15: Creating an Associative Array

Problem

You want to create an array that uses named elements instead of numbered indexes.

Solution

Create an associative array.

Discussion

When working with sets of data in which each element has a specific meaning or importance, a typical, number-indexed array doesn't always suffice.

For example, if you are working with a set of data such as the names of members of a committee, a number-indexed array is sufficient:

var aMembers:Array = new Array("Franklin", "Gina", "Sindhu");

Pages: 1, 2, 3, 4, 5, 6, 7, 8

Next Pagearrow