39 / Advanced

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.

39-random-uuid.nxSource →
// Números aleatorios y UUID v4
import "std/random"
import "std/uuid"

// bool -> texto: int_to_string() espera un int y un bool no se convierte solo,
// así que la conversión se escribe explícita.
fn si_no(b: bool) -> String {
    if b { return "si" }
    return "no"
}

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: " + si_no(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: " + si_no(valido))

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

    return 0
}
Illustrative outputstdout
Numeros aleatorios (1-100):
  9
  5
  35
random_bool: si
random_float: (generado)
uuid_v4: 3d0702c0-6c28-4ecf-b36c-0281c464bea4
longitud uuid: 36
uuid valido: si
segundo uuid: 6b14c32d-27b3-4c1a-83e8-d6a093a5f501
son distintos: si

How it works

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.