   Randomness Contents

# Randomness

Scam has a few functions for generating pseudo-random numbers. Although the word randomly is used in the chapter, pseudo-randomly would be a more accurate term.

## Built-in Random Functions

The built-in functions are randomInt, randomMax, and randomSeed.

### randomMax()

This function, which takes no arguments, returns the largest integer that can be returned from the randomInt function.

### randomInt()

This function, which takes no arguments, returns a randomly generated number between 0 and `(randomMax)`, inclusive.

### randomSeed(seed)

This function, which takes a positive integer as an argument, resets the state of Scam's pseudo-random number generator. If a program uses randomInt without resetting the random state, the same sequence of pseudo-random numbers will be generated each time the program is run. To generate a different sequence each time, a common trick is to set the state with the current time at the start of the program:

```    (randomSeed (integer (time)))
```

Note that `(integer (time))` changes rather slowly, as computers go, since it marks the number of seconds since the beginning of the epoch. So setting the seed once at the beginning of a program is probably OK; setting the seed multiple times within a program may be problematic.

## The random library

The random library, included with the expression:

```    (include "random.lib")
```

adds the following functions: randomReal, randomRange, shuffle, and flip.

### randomReal()

This function, which takes no arguments, returns a real number between 0 (inclusive) and 1 (exclusive).

### randomRange(low,high)

This function returns an integer between low (inclusive) and high (exclusive). To randomly retrieve a value from a collection named items, one might use the expression:

```    (getElement items (randomRange 0 (length items)))
```

### shuffle(items)

This function, which takes a list or an array as an argument, randomly rearranges the values in the given collection.

### flip()

This function, which takes no arguments, randomly returns integer 0 or integer 1. It is used to simulate coin flips.

lusth@cs.ua.edu   Randomness Contents