Thursday, May 8, 2025

Random numbers in Golf

Generating random numbers is important in a wide range of applications. For instance, session IDs often use random numbers; they are also used in generating passwords; another example is load balancing where (say instead of round-robin), the next available process to serve a request is chosen randomly; some applications (like gambling) depend on random qualities; any kind of simulation would heavily rely on random numbers; financial and polling applications use random samples to determine outcomes and policies. The list of possible uses is pretty long.

So with that in mind, generating random numbers in Golf is easy. The most common way is random-string statement:
 random-string to rnd
 p-out rnd new-line

By default "rnd" will be a random string of length 20 consisting of digits (0-9) and letters (a-z and A-Z).

You can specify the length desired:
 random-string to rnd length 100

which will generate a random string of length 100.

You can also insist that it'd be made of digits only:
 random-string to rnd length 100 number

And you can make a binary random string, meaning each byte is ranging from 0-255 in value with:
 random-string to rnd length 100 binary

Of course, such a string could have a zero byte in it. Not to worry, since Golf keeps track of string lengths, and using this string (for instance copying) will perform correctly.

Note that when we say "random" we really mean pseudo-random. Achieving absolutely random value is more in the domain of mother Nature and quantum mechanics. However, Golf strives to deliver very good randomness, which is based on local process properties, such as Process ID (PID) and varied current time.

If you'd like to take the randomness a notch up, then you can use random-crypto statement. This uses a cryptographically secure pseudo random generator (CSPRNG) from OpenSSL library, which is closer to a truly random notion. Note however, for most purposes by far, a random-string will suffice. It delivers good randomness that's suitable for most applications and is much faster than random-crypto, which really should be used for cryptographic purposes only. random-crypto has "length" clause only and it produces binary values always, as is usually the case with cryptography.