## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# List Utilities

## Randomized Lists

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