You can use Int32.Random in OCL expressions when you need a random zero-based integer, for example to choose a length or an item position from a collection.
Generate a random Int32
Use the following form:
Int32.Random(x)
x is the exclusive upper bound. The result is an Int32 in the range 0..x-1.
| Expression | Possible result values |
|---|---|
Int32.Random(1)
|
0
|
Int32.Random(5)
|
0, 1, 2, 3, or 4
|
Int32.Random(100)
|
0 through 99; it never returns 100
|
Use this zero-based result directly where a zero-based value is required. If you use the result with a collection's at operation, add 1, because the example below uses positions starting at 1.
Generate a random string
The following expression creates a string with a random length from 7 through 11 characters. Each character is selected from the specified character sequence.
let characters = 'ABCDEFGHJKLMNPQRST23456789'.toCharArray in (
let wordlength = Int32.Random(5)+7 in (
Sequence{1..wordlength}->collect(a|
characters->at(Int32.Random(characters->size)+1)
)->asSeparatedList('')
)
)
The expression works as follows:
toCharArrayconverts the character string into a character collection namedcharacters.Int32.Random(5)+7produces a length from 7 to 11:Int32.Random(5)produces 0 to 4, then the expression adds 7.Sequence{1..wordlength}creates one iteration for each character position.- During each iteration,
Int32.Random(characters->size)selects a zero-based random position from the available characters. Adding1supplies the position used bycharacters->at(...). collectgathers the selected characters, andasSeparatedList()joins them without a separator.
The character source excludes visually similar characters such as I, O, 0, and 1. Change the source string when your use case requires a different allowed character set.
Limits and behavior
- This operation is documented for
Int32. There is no random function onInt64. - The exact algorithm used to produce random values can vary by implementation. Do not depend on a particular sequence of values.
- The upper bound is not included. To select among
navailable positions, useInt32.Random(n).
