🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators random
This page was created by Peter on 2019-12-19. Last edited by Wikiadmin on 2026-07-29.

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:

  1. toCharArray converts the character string into a character collection named characters.
  2. Int32.Random(5)+7 produces a length from 7 to 11: Int32.Random(5) produces 0 to 4, then the expression adds 7.
  3. Sequence{1..wordlength} creates one iteration for each character position.
  4. During each iteration, Int32.Random(characters->size) selects a zero-based random position from the available characters. Adding 1 supplies the position used by characters->at(...).
  5. collect gathers the selected characters, and asSeparatedList() 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 on Int64.
  • 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 n available positions, use Int32.Random(n).

See also