Nyx by Example

Random Numbers and UUID

The std/random module provides a fast xorshift64 pseudo-random number generator, and std/uuid generates RFC 4122 version 4 UUIDs. Both are commonly needed utilities for testing, simulations, and distributed-system identifiers.

Code

// Números aleatorios y UUID v4
import "std/random"
import "std/uuid"

fn main() -> int {
    // Generar 3 números aleatorios entre 1 y 100
    print("Numeros aleatorios (1-100):")
    let r1: int = random_range(1, 100)
    let r2: int = random_range(1, 100)
    let r3: int = random_range(1, 100)
    print("  " + int_to_string(r1))
    print("  " + int_to_string(r2))
    print("  " + int_to_string(r3))

    // random_bool
    let b: bool = random_bool()
    print("random_bool: " + int_to_string(b))

    // random_float en [0.0, 1.0)
    let f: float = random_float()
    print("random_float: (generado)")

    // Generar un UUID v4
    let id: String = uuid_v4()
    print("uuid_v4: " + id)
    print("longitud uuid: " + int_to_string(id.length()))

    // Validar que el UUID es valido
    let valido: bool = uuid_is_valid(id)
    print("uuid valido: " + int_to_string(valido))

    // Generar otro UUID — debe ser diferente
    let id2: String = uuid_v4()
    print("segundo uuid: " + id2)
    print("son distintos: " + int_to_string(id != id2))

    return 0
}

Output

Numeros aleatorios (1-100):
  42
  7
  83
random_bool: 1
random_float: (generado)
uuid_v4: f47ac10b-58cc-4372-a567-0e02b2c3d479
longitud uuid: 36
uuid valido: 1
segundo uuid: 550e8400-e29b-41d4-a716-446655440000
son distintos: 1

Explanation

random_range(lo, hi) returns a uniformly distributed integer in the inclusive range [lo, hi]. random_bool() returns either true or false with equal probability, and random_float() returns a float in [0.0, 1.0). All three are backed by the xorshift64 generator seeded from the system clock at program start.

uuid_v4() generates a 36-character string in the canonical UUID format xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx. The 4 in the third group encodes the version, and the high bits of the fourth group encode the variant. Every call produces a new random UUID; the probability of two UUIDs colliding is astronomically small.

uuid_is_valid(s) validates that a string conforms to the UUID format — useful for sanitizing user input or configuration values before treating them as identifiers. The final assertion confirms that two separately generated UUIDs are always distinct.

← Previous Next →

Source: examples/by-example/39-random-uuid.nx