Making a Random Selection from an Array

This tutorial addresses the following question from a reader:

Thank you for your well written (and well commented) tutorial on creating XML based quizzes in Flash. We are finding it very informative here in our classroom. One question is puzzling me: How would I change the actionscript code to enable the quiz to present a random set of questions from a longer list? For example, could I have the quiz present just 4 random questions from an XML file containing 20 questions in total?

This is a general issue, whether you are trying to scramble images, randomly choose quiz problems, or simulating the dealing of a hand of playing cards. In the present tutorial, we show how to accomplish a random selection of a subset of a given array of objects. To minimize the “overhead” in our example, we will set up an array of strings, each representing a playing card in a standard deck of 52 cards. The applet allows the user to specify the number of cards that should be randomly selected, which we think of as a “hand” in a card game. The code uses a function (which we call getHand because of the context) that can easily be copied for use in any situation where a random subset of a set of objects needs to be chosen.

Click the link below to see the applet and download the source code.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s