The following handler creates a nonrepeating random list of
n numbers (Refer to Chapter 8 for details on the
random() function.) The trick is to place the numbers 1 through
n into random locations throughout the list as it is built.
Example 6-23. Creating a List of Random Numbers
on randomNumberList n -- Initialize an empty list set myList = [ ] -- Create a list with the requested number of elements repeat with x = 1 to n -- Insert the next number in a random place in the list addAt (myList, random(x), x) end repeat return myList end randomNumberList put randomNumberList (10) -- [8, 10, 7, 5, 1, 3, 9, 4, 2, 6]
The following incorrect routine (which you’ll often see used) will likely result in some numbers being repeated in the list. It incorrectly adds random numbers that may already exist in the list because the
random() function may generate the same number multiple times. See "How Random Is Random?" in Chapter 8 for details.
Example 6-24. Incorrect (Nonrandom) List Creation
on incorrectRandom n -- Initialize an empty list set myList = [ ] -- Create a list with the requested number of elements repeat with x = 1 to n -- Add a random number to the list add (myList, random(n)) end repeat return myList end incorrectRandom put incorrectRandom (10) -- [9, 1, 6, 4, 4, 10, 2, 3, 9, 4]
This handler returns a randomized version of any linear list or property list, leaving the original list intact. Note that this randomizes an existing list, which differs from creating ...