Skip to content

Random Functions

Random number and sampling functions.

Summary

Function Signature Description
random -> number Generate random number between 0 and 1
random_choice array -> any Pick a random element from an array
random_int number, number -> number Generate a random integer in an inclusive range [min, max]
sample array, number -> array Random sample from array
shuffle array -> array Randomly shuffle array

Functions

random

Generate random number between 0 and 1

Signature: -> number

Examples:

# Random float
random() -> 0.123456...
# Random 0-99
floor(multiply(random(), `100`)) -> 42

random_choice

Pick a random element from an array

Signature: array -> any

Examples:

# Random element
random_choice(['a', 'b', 'c']) -> 'b'
# Empty array returns null
random_choice([]) -> null

random_int

Generate a random integer in an inclusive range [min, max]

Signature: number, number -> number

Examples:

# Random integer 1-10
random_int(`1`, `10`) -> 7
# Coin flip
random_int(`0`, `1`) -> 0

sample

Random sample from array

Signature: array, number -> array

Examples:

# Sample 2 items
sample([1, 2, 3, 4], `2`) -> [3, 1]
# Sample 1 item
sample(['a', 'b', 'c'], `1`) -> ['b']
# Always returns n items
length(sample([1, 2, 3], `2`)) -> 2

shuffle

Randomly shuffle array

Signature: array -> array

Examples:

# Shuffle numbers
shuffle([1, 2, 3]) -> [2, 3, 1]
# Preserves length
length(shuffle([1, 2, 3])) -> 3