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`

Example 6-23. Creating a List of Random Numbers

on randomNumberList n-- Initialize an empty listset myList = [ ]-- Create a list with the requested number of elementsrepeat with x = 1 to n-- Insert the next number in a random place in the listaddAt (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 listset myList = [ ]-- Create a list with the requested number of elementsrepeat with x = 1 to n-- Add a random number to the listadd (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 ...

Start Free Trial

No credit card required