Snippet Saturday: quick random choice


Today’s Snippet Saturday (actually, Sunday) is a quick shortcut for choosing one of several strings, objects, etc. randomly.

Now, I wouldn’t really recommend using this code in a project. There are ways to do the same thing that are much more readable and less error prone. Instead, I thought it was an interesting experiment to show off some of how AS3′s syntax works for those of you who may not have seen something like this.

What’s happening here? Let’s break it down.

  • ["Alpha", "Bravo", "Charlie"] – Here we are instantiating a new array and populating it with three strings. This is essentially the same as:
    var a:Array = new Array();
    a[0] = "Alpha";
    a[1] = "Bravo";
    a[2] = "Charlie";
  • [...] – next is another pair of square brackets. This is an array access operator. In other words, everything between the two brackets will be evaluated as the index of the array to retrieve.
  • int(...) – This is an explicit type-cast to an int. That means that everything inside those parentheses is evaluated and flash attempts to convert from whatever data type it is to an integer. In the case of decimal numbers, they are rounded down so this is similar to using Math.floor().
  • Math.random() * 3 – random() of course produces a random floating point (decimal) number between 0.0 and (almost but not quite) 1.0. Multiplying that number by 3 (the length of the array) produces a number between 0.0 and 3.0 (technically, between 0 and 2.99999999etc).

The result, an array is created with three strings, a random number between 0.0 and (almost) 3.0 is generated, it is rounded down to an int between 0 and 2, that number is used as the index of the array to look up. The result will be randomly one of the three strings.

I hope you found this interesting!

Tagged ,
  • Hannes

    Well, actually, 0 <= Math.random() < 1 is always true, so you can safely ignore the out-of-range-thing :)

  • Mims H Wright

    Oh, good to know! I’ll update.