Programming Search⌘K

Taskcore

Generate random numbers

Also called random integer in a range, roll a die, shuffle a list, seed a random number generator, secure random token.

Get a random integer in a range with no modulo bias, shuffle a list, repeat a sequence with a seed, and make a token with a cryptographically secure generator.

Task

Write four functions. int_in_range returns an integer from lo to hi, and each value has equal probability. shuffle puts a list in a random order, and each order has equal probability. A seeded generator gives the same numbers each time it gets the same seed. token_hex(n) gives n random bytes from a cryptographically secure generator as 2n lowercase hexadecimal digits.

A random result changes on each run, so each function takes a word source: a function that returns an integer from 0 to 2^32 - 1. The cases give fixed words, and the tests check the exact results and that each word was used.

int_in_range uses the method of OpenBSD arc4random_uniform. Let n = hi - lo + 1. Take the next word w. If w < 2^32 mod n, reject it and take the next word. Then return lo + (w mod n). Each remainder now comes from the same number of words. n can be 2^32, and lo and hi can be at the ends of the signed 64-bit range.

shuffle is the Fisher-Yates method. For i from the last index down to 1, it gets j = int_in_range(0, i) and swaps items i and j.

Solutions

Each solution also has a seeded word source and a secure word source. In real code, use the range and shuffle functions of the library where they exist. The solutions write their own so that one contract tests each language.

  • Python. random.Random(seed).getrandbits(32) is the seeded source, and secrets.randbits(32) is the secure source. random.randint(a, b) and random.shuffle(x) do the same work in the library. The random module must not be used for security. secrets.token_hex(n) converts each byte to two hex digits.
  • JavaScript and TypeScript (Node.js). Math.random() has no seed that the user can set, so the solution has a SplitMix64 generator on bigint as the seeded source. crypto.getRandomValues fills a Uint32Array for the secure source. crypto.randomBytes(n).toString("hex") makes the token. crypto.randomInt avoids modulo bias, but its range must be less than 2^48.
  • Java. The class Random specifies its algorithms, so new Random(seed) gives the same sequence in each Java implementation. nextInt(bound) rejects values that give an uneven distribution. SecureRandom is cryptographically strong. HexFormat.of() writes lowercase digits with no delimiter.
  • C#. new Random(seed) is the seeded source, but its algorithm can change between major versions of .NET. RandomNumberGenerator.GetBytes is the secure source, and RandomNumberGenerator.GetHexString(2 * n, lowercase: true) makes the token. Random.Shuffle does the shuffle in the library.
  • Go. rand.New(rand.NewPCG(seed, 0)).Uint32 from math/rand/v2 is the seeded source. The documentation says that this package is not for security, and points to crypto/rand. rand.Read from crypto/rand never returns an error and fills the buffer, and hex.EncodeToString makes the token. rand.IntN and rand.Shuffle give a range and a shuffle in the library.
  • Rust. std::random is a nightly-only experimental API, so the solution for stable Rust has SplitMix64 as the seeded source, and reads /dev/urandom as the secure source, so it runs only on Unix-like systems.
  • C. The solution has SplitMix64 as the seeded source. POSIX getentropy in <unistd.h> fills a buffer of at most GETENTROPY_MAX bytes from a cryptographically secure generator, so token_hex asks for the bytes in parts. A word source is a function pointer with a context pointer.
  • C++. A word source is any object that returns an unsigned 32-bit value when called, so std::mt19937 is one. std::mt19937 is a mersenne_twister_engine with fixed parameters. The secure source calls getentropy. std::shuffle does the shuffle in the library.
  • Bash. A word source is a function that sets REPLY. RANDOM gives 0 to 32767, and an assignment to it sets the seed, so the seeded source joins the bits of three values. SRANDOM cannot be seeded, and the manual does not say that it is secure, so the secure source reads /dev/urandom with od. Linux random(4) says that /dev/urandom is cryptographically secure against attackers without local root access, after the generator has its seed.

A program that must give the same output can print a seeded value or a property. The Python documentation says that random() gives the same sequence for the same seed in later versions. The other methods can change:

import random
import secrets

rng = random.Random(42)
print(rng.random())
first = [rng.randint(1, 6) for _ in range(10)]
rng.seed(42)
rng.random()
print("same seed, same rolls:", first == [rng.randint(1, 6) for _ in range(10)])
token = secrets.token_hex(16)
print("token length:", len(token))
print("lowercase hex:", all(c in "0123456789abcdef" for c in token))
Output
0.6394267984578837
same seed, same rolls: True
token length: 32
lowercase hex: True

SplitMix64 uses only 64-bit integer arithmetic, so a seed gives the same output on each platform:

fn splitmix64(state: &mut u64) -> u64 {
    *state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
    let mut z = *state;
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^ (z >> 31)
}

fn main() {
    let mut state = 0;
    for _ in 0..3 {
        println!("{:#018x}", splitmix64(&mut state));
    }
}
Output
0xe220a8397b1dcdaf
0x6e789e6aa1b965f4
0x06c45d188009454f

Edge cases

The cases are in cases/basic.jsonl, cases/edge.jsonl and cases/shuffle.jsonl.

  • one-value: lo = hi. Each result is lo. It still takes one word, as the contract requires.
  • reject-low-words: for a die, 2^32 mod 6 is 4, so the words 0 and 3 are rejected and the word 4 gives 5.
  • accept-least: the word 4 is equal to 2^32 mod 6, which is the least word that is accepted.
  • power-of-two: when n divides 2^32, no word is rejected.
  • worst-case: n = 2^31 + 1. Almost half of the words are rejected, so a result can take many words.
  • full-unsigned-32 and full-signed-32: n = 2^32. 2^32 mod n is 0, so each word is accepted and the result is lo + w. A 32-bit computation of n or of 2^32 mod n overflows here.
  • near-int64-max, near-int64-min and wide-int64: hi - lo and lo + w mod n must not overflow at the ends of the signed 64-bit range. Java, C# and Rust use unsigned arithmetic for the difference.
  • empty and one-item: no swap, and no word is used.
  • two-items-swap and two-items-keep: one word decides the order.
  • reject-in-shuffle: the first word for i = 2 is rejected, so the shuffle takes three words for three items.
  • duplicates and non-ascii: the shuffle moves items and does not look at them.

Pitfalls

  • A remainder is biased. RANDOM % 6 in Bash maps 32768 values to 6 results. 32768 is not a multiple of 6, so 0 and 1 come more often. The bias is small here, but it grows with n. For n = 2^31 + 1 and a 32-bit word, each value below 2^31 - 1 is twice as probable as the other two values:

This code runs but gives a wrong answer on purpose.

counts=(0 0 0 0 0 0)
for ((r = 0; r <= 32767; r++)); do
    counts[r % 6]=$((counts[r % 6] + 1))
done
echo "${counts[@]}"
Output
5462 5462 5461 5461 5461 5461
  • Math.abs of the least int is negative. The Java line Math.abs(rng.nextInt()) % n is biased. When nextInt returns Integer.MIN_VALUE, Math.abs returns the same negative value, so the result is negative. Use rng.nextInt(n):

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        int word = Integer.MIN_VALUE;
        System.out.println(Math.abs(word));
        System.out.println(Math.abs(word) % 6);
    }
}
Output
-2147483648
-2
  • A swap with any index is not a fair shuffle. If each item swaps with a random index from the full list, n items give n^n paths of the same probability. 27 paths cannot fall evenly on 6 orders. Swap item i only with an index from 0 to i:

This code runs but gives a wrong answer on purpose.

from collections import Counter
from itertools import product

counts = Counter()
for path in product(range(3), repeat=3):
    order = list("abc")
    for i, j in enumerate(path):
        order[i], order[j] = order[j], order[i]
    counts["".join(order)] += 1
for order, count in sorted(counts.items()):
    print(order, count)
Output
abc 4
acb 5
bac 5
bca 5
cab 4
cba 4
  • A general-purpose generator is not for secrets. Python random, JavaScript Math.random, Go math/rand/v2 and C rand are not cryptographically secure. cppreference says that rand gives no guarantee of quality. For tokens, keys and passwords, use secrets, crypto.getRandomValues, SecureRandom, RandomNumberGenerator, crypto/rand or getentropy.
  • std::random_device can be deterministic. cppreference says that an implementation can use a pseudo-random engine for it, and then each object can give the same sequence. Do not use it as the only source of a secret.
  • A seed does not always give the same numbers in a new version. .NET does not guarantee that Random stays the same across major versions. Python guarantees only random(). If a test needs fixed numbers for all versions, write the generator, as the solutions do with SplitMix64, or give the words to the code.

Code

The build runs the native tests of each language in a pinned toolchain.

random_numbers.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/generate-random-numbers/.
"""Random integers in a range, a shuffle, a seeded generator and tokens."""

import random
import secrets
from collections.abc import Callable, MutableSequence

type WordSource = Callable[[], int]
"""A function that returns a random integer from 0 to 2**32 - 1."""


def int_in_range(next_word: WordSource, lo: int, hi: int) -> int:
    """Return an integer from lo to hi, each with equal probability.

    A word below 2**32 % n is rejected, so that each remainder w % n
    comes from the same number of words. In real code, random.randint
    and secrets.randbelow do this work.
    """
    n = hi - lo + 1
    if not 1 <= n <= 1 << 32:
        raise ValueError("need lo <= hi and at most 2**32 values")
    least = (1 << 32) % n
    while True:
        word = next_word()
        if word >= least:
            return lo + word % n


def shuffle[T](next_word: WordSource, items: MutableSequence[T]) -> None:
    """Shuffle items in place with the Fisher-Yates method."""
    for i in range(len(items) - 1, 0, -1):
        j = int_in_range(next_word, 0, i)
        items[i], items[j] = items[j], items[i]


def seeded_words(seed: int) -> WordSource:
    """Return a word source that gives the same words for the same seed."""
    rng = random.Random(seed)
    return lambda: rng.getrandbits(32)


def secure_words() -> WordSource:
    """Return a word source from the secure generator of the system."""
    return lambda: secrets.randbits(32)


def token_hex(nbytes: int) -> str:
    """Return nbytes secure random bytes as 2 * nbytes hexadecimal digits."""
    return secrets.token_hex(nbytes)
test_random_numbers.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/generate-random-numbers/.

import re

import pytest

from random_numbers import int_in_range, secure_words, seeded_words, shuffle, token_hex

RANGE_CASES = [
    ("coin", [5, 2, 7], 0, 1, 3, [1, 0, 1]),
    ("no-results", [], 1, 6, 0, []),
    ("die", [7, 12, 1000000, 4294967295], 1, 6, 4, [2, 1, 5, 4]),
    ("negative-range", [100, 2000000000, 4294967294], -10, 10, 3, [6, -5, -8]),
    ("one-value", [0, 99], 5, 5, 2, [5, 5]),
    ("reject-low-words", [0, 3, 4], 1, 6, 1, [5]),
    ("accept-least", [3, 4, 9], 0, 5, 2, [4, 3]),
    ("power-of-two", [0, 4294967295], 0, 7, 2, [0, 7]),
    ("worst-case", [2147483646, 2147483647], 0, 2147483648, 1, [2147483647]),
    ("full-unsigned-32", [0, 4294967295, 123456789], 0, 4294967295, 3, [0, 4294967295, 123456789]),
    ("full-signed-32", [0, 2147483648, 4294967295], -2147483648, 2147483647, 3, [-2147483648, 0, 2147483647]),
    ("near-int64-max", [4294967295, 6], 9223372036854775798, 9223372036854775807, 2, [9223372036854775803, 9223372036854775804]),
    ("near-int64-min", [4294967295, 9], -9223372036854775808, -9223372036854775799, 2, [-9223372036854775803, -9223372036854775799]),
    ("wide-int64", [4294967295, 0], 9223372032559808512, 9223372036854775807, 2, [9223372036854775807, 9223372032559808512]),
]

SHUFFLE_CASES = [
    ("empty", [], [], []),
    ("one-item", [], ["a"], ["a"]),
    ("two-items-swap", [0], ["a", "b"], ["b", "a"]),
    ("two-items-keep", [1], ["a", "b"], ["a", "b"]),
    ("five-items", [7, 3, 4, 1], ["a", "b", "c", "d", "e"], ["a", "e", "b", "d", "c"]),
    ("reject-in-shuffle", [0, 2, 0], ["a", "b", "c"], ["b", "a", "c"]),
    ("duplicates", [1, 1], ["x", "x", "y"], ["x", "y", "x"]),
    ("non-ascii", [4294967295, 4294967294, 0], ["é", "日本", "🙂", "a"], ["日本", "é", "🙂", "a"]),
]


def fake_words(words):
    """Return a word source that gives words in order, and a check that all were used."""
    it = iter(words)
    return (lambda: next(it)), (lambda: next(it, None) is None)


@pytest.mark.parametrize(("name", "words", "lo", "hi", "count", "want"), RANGE_CASES)
def test_int_in_range(name, words, lo, hi, count, want):
    source, used_all = fake_words(words)
    assert [int_in_range(source, lo, hi) for _ in range(count)] == want, name
    assert used_all(), name


@pytest.mark.parametrize(("name", "words", "items", "want"), SHUFFLE_CASES)
def test_shuffle(name, words, items, want):
    source, used_all = fake_words(words)
    shuffle(source, items)
    assert items == want, name
    assert used_all(), name


@pytest.mark.parametrize(("lo", "hi"), [(1, 0), (0, 1 << 32)])
def test_int_in_range_rejects_bad_range(lo, hi):
    with pytest.raises(ValueError):
        int_in_range(lambda: 0, lo, hi)


def test_same_seed_same_words():
    a, b, c = seeded_words(42), seeded_words(42), seeded_words(43)
    first = [a() for _ in range(10)]
    assert first == [b() for _ in range(10)]
    assert first != [c() for _ in range(10)]
    assert all(0 <= w < 1 << 32 for w in first)


def test_secure_words_in_range():
    source = secure_words()
    assert all(1 <= int_in_range(source, 1, 6) <= 6 for _ in range(100))


@pytest.mark.parametrize("nbytes", [0, 1, 16, 32])
def test_token_hex(nbytes):
    token = token_hex(nbytes)
    assert re.fullmatch(f"[0-9a-f]{{{2 * nbytes}}}", token)


def test_tokens_differ():
    assert token_hex(16) != token_hex(16)
random_numbers.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

#include "random_numbers.hpp"

#include <algorithm>
#include <array>
#include <climits>
#include <unistd.h>
#if defined(__APPLE__)
#include <sys/random.h>  // macOS declares getentropy here, not in <unistd.h>.
#endif

// POSIX puts the limit of one call to getentropy in GETENTROPY_MAX. macOS does
// not define it, and its manual gives 256 bytes.
#ifndef GETENTROPY_MAX
#define GETENTROPY_MAX 256
#endif

namespace random_numbers {

std::uint32_t secure_word() {
    std::uint32_t w;
    if (getentropy(&w, sizeof w) != 0) {
        throw std::runtime_error("getentropy failed");
    }
    return w;
}

std::string token_hex(std::size_t nbytes) {
    static constexpr char digits[] = "0123456789abcdef";
    std::string out;
    out.reserve(2 * nbytes);
    std::array<unsigned char, GETENTROPY_MAX> chunk;
    for (std::size_t done = 0; done < nbytes;) {
        const std::size_t len = std::min(nbytes - done, chunk.size());
        if (getentropy(chunk.data(), len) != 0) {
            throw std::runtime_error("getentropy failed");
        }
        for (std::size_t k = 0; k < len; ++k) {
            out += digits[chunk[k] >> 4];
            out += digits[chunk[k] & 0xf];
        }
        done += len;
    }
    return out;
}

}  // namespace random_numbers
random_numbers.hpp 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

#ifndef RANDOM_NUMBERS_HPP
#define RANDOM_NUMBERS_HPP

#include <concepts>
#include <cstddef>
#include <cstdint>
#include <span>
#include <stdexcept>
#include <string>
#include <utility>

namespace random_numbers {

// A word source returns a random integer from 0 to 2^32 - 1. std::mt19937 is one.
template <typename W>
concept word_source = std::invocable<W&> && std::convertible_to<std::invoke_result_t<W&>, std::uint64_t>;

inline constexpr std::uint64_t words = std::uint64_t{1} << 32;

// Returns an integer from lo to hi, each with equal probability. A word below
// 2^32 % n is rejected, so that each remainder comes from the same number of
// words. Throws std::invalid_argument if hi < lo or the range has more than
// 2^32 values.
template <word_source W>
std::int64_t int_in_range(W& next_word, std::int64_t lo, std::int64_t hi) {
    // The unsigned difference is exact, also when hi - lo overflows.
    const std::uint64_t span = static_cast<std::uint64_t>(hi) - static_cast<std::uint64_t>(lo);
    if (hi < lo || span >= words) {
        throw std::invalid_argument("need lo <= hi and at most 2^32 values");
    }
    const std::uint64_t n = span + 1;
    const std::uint64_t least = words % n;
    for (;;) {
        const std::uint64_t word = static_cast<std::uint64_t>(next_word()) & (words - 1);
        if (word >= least) {
            // The sum is at most hi, so the conversion back to int64 is exact.
            return static_cast<std::int64_t>(static_cast<std::uint64_t>(lo) + word % n);
        }
    }
}

// Shuffles items in place with the Fisher-Yates method.
template <typename T, word_source W>
void shuffle(W& next_word, std::span<T> items) {
    for (std::size_t i = items.size() > 0 ? items.size() - 1 : 0; i > 0; --i) {
        const auto j = static_cast<std::size_t>(int_in_range(next_word, 0, static_cast<std::int64_t>(i)));
        using std::swap;
        swap(items[i], items[j]);
    }
}

// A word source from getentropy. Throws std::runtime_error if getentropy fails.
std::uint32_t secure_word();

// Returns nbytes secure random bytes as 2 * nbytes lowercase hexadecimal
// digits. Throws std::runtime_error if getentropy fails.
std::string token_hex(std::size_t nbytes);

}  // namespace random_numbers

#endif
test_random_numbers.cpp 140 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

#include <cstdint>
#include <cstdio>
#include <random>
#include <regex>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>

#include "random_numbers.hpp"

namespace {

struct range_case {
    const char* name;
    std::vector<std::uint32_t> words;
    std::size_t nwords;
    std::int64_t lo, hi;
    std::size_t count;
    std::vector<std::int64_t> want;
};

const std::vector<range_case> range_cases = {
    {"coin", {UINT32_C(5), UINT32_C(2), UINT32_C(7)}, 3, INT64_C(0), INT64_C(1), 3, {INT64_C(1), INT64_C(0), INT64_C(1)}},
    {"no-results", {}, 0, INT64_C(1), INT64_C(6), 0, {}},
    {"die", {UINT32_C(7), UINT32_C(12), UINT32_C(1000000), UINT32_C(4294967295)}, 4, INT64_C(1), INT64_C(6), 4, {INT64_C(2), INT64_C(1), INT64_C(5), INT64_C(4)}},
    {"negative-range", {UINT32_C(100), UINT32_C(2000000000), UINT32_C(4294967294)}, 3, INT64_C(-10), INT64_C(10), 3, {INT64_C(6), INT64_C(-5), INT64_C(-8)}},
    {"one-value", {UINT32_C(0), UINT32_C(99)}, 2, INT64_C(5), INT64_C(5), 2, {INT64_C(5), INT64_C(5)}},
    {"reject-low-words", {UINT32_C(0), UINT32_C(3), UINT32_C(4)}, 3, INT64_C(1), INT64_C(6), 1, {INT64_C(5)}},
    {"accept-least", {UINT32_C(3), UINT32_C(4), UINT32_C(9)}, 3, INT64_C(0), INT64_C(5), 2, {INT64_C(4), INT64_C(3)}},
    {"power-of-two", {UINT32_C(0), UINT32_C(4294967295)}, 2, INT64_C(0), INT64_C(7), 2, {INT64_C(0), INT64_C(7)}},
    {"worst-case", {UINT32_C(2147483646), UINT32_C(2147483647)}, 2, INT64_C(0), INT64_C(2147483648), 1, {INT64_C(2147483647)}},
    {"full-unsigned-32", {UINT32_C(0), UINT32_C(4294967295), UINT32_C(123456789)}, 3, INT64_C(0), INT64_C(4294967295), 3, {INT64_C(0), INT64_C(4294967295), INT64_C(123456789)}},
    {"full-signed-32", {UINT32_C(0), UINT32_C(2147483648), UINT32_C(4294967295)}, 3, INT64_C(-2147483648), INT64_C(2147483647), 3, {INT64_C(-2147483648), INT64_C(0), INT64_C(2147483647)}},
    {"near-int64-max", {UINT32_C(4294967295), UINT32_C(6)}, 2, INT64_C(9223372036854775798), INT64_C(9223372036854775807), 2, {INT64_C(9223372036854775803), INT64_C(9223372036854775804)}},
    {"near-int64-min", {UINT32_C(4294967295), UINT32_C(9)}, 2, INT64_MIN, INT64_C(-9223372036854775799), 2, {INT64_C(-9223372036854775803), INT64_C(-9223372036854775799)}},
    {"wide-int64", {UINT32_C(4294967295), UINT32_C(0)}, 2, INT64_C(9223372032559808512), INT64_C(9223372036854775807), 2, {INT64_C(9223372036854775807), INT64_C(9223372032559808512)}},
};

struct shuffle_case {
    const char* name;
    std::vector<std::uint32_t> words;
    std::size_t nwords;
    std::vector<std::string> items, want;
    std::size_t count;
};

const std::vector<shuffle_case> shuffle_cases = {
    {"empty", {}, 0, {}, {}, 0},
    {"one-item", {}, 0, {"a"}, {"a"}, 1},
    {"two-items-swap", {UINT32_C(0)}, 1, {"a", "b"}, {"b", "a"}, 2},
    {"two-items-keep", {UINT32_C(1)}, 1, {"a", "b"}, {"a", "b"}, 2},
    {"five-items", {UINT32_C(7), UINT32_C(3), UINT32_C(4), UINT32_C(1)}, 4, {"a", "b", "c", "d", "e"}, {"a", "e", "b", "d", "c"}, 5},
    {"reject-in-shuffle", {UINT32_C(0), UINT32_C(2), UINT32_C(0)}, 3, {"a", "b", "c"}, {"b", "a", "c"}, 3},
    {"duplicates", {UINT32_C(1), UINT32_C(1)}, 2, {"x", "x", "y"}, {"x", "y", "x"}, 3},
    {"non-ascii", {UINT32_C(4294967295), UINT32_C(4294967294), UINT32_C(0)}, 3, {"é", "日本", "🙂", "a"}, {"日本", "é", "🙂", "a"}, 4},
};

// A word source that gives the words in order.
struct fake_words {
    const std::vector<std::uint32_t>& words;
    std::size_t next = 0;

    std::uint32_t operator()() { return words.at(next++); }
};

int failures = 0;

void check(bool ok, const std::string& name, const char* what) {
    if (!ok) {
        std::printf("FAIL %s: %s\n", name.c_str(), what);
        ++failures;
    }
}

template <typename F>
bool throws(F f) {
    try {
        f();
    } catch (const std::invalid_argument&) {
        return true;
    }
    return false;
}

}  // namespace

int main() {
    using namespace random_numbers;
    for (const auto& c : range_cases) {
        fake_words f{c.words};
        std::vector<std::int64_t> got;
        for (std::size_t k = 0; k < c.count; ++k) {
            got.push_back(int_in_range(f, c.lo, c.hi));
        }
        check(got == c.want, c.name, "wrong values");
        check(f.next == c.words.size(), c.name, "did not use all words");
    }
    for (const auto& c : shuffle_cases) {
        fake_words f{c.words};
        std::vector<std::string> items = c.items;
        shuffle(f, std::span{items});
        check(items == c.want, c.name, "wrong order");
        check(f.next == c.words.size(), c.name, "did not use all words");
    }
    auto zero = [] { return std::uint32_t{0}; };
    check(throws([&] { int_in_range(zero, 1, 0); }), "bad-range", "hi < lo");
    check(throws([&] { int_in_range(zero, 0, std::int64_t{1} << 32); }), "bad-range", "2^32 + 1 values");
    check(throws([&] { int_in_range(zero, INT64_MIN, INT64_MAX); }), "bad-range", "2^64 values");

    std::mt19937 a(42), b(42), c(43);
    bool same = true, other = true;
    for (int k = 0; k < 10; ++k) {
        const auto wa = a();
        same = same && wa == b();
        other = other && wa == c();
    }
    check(same, "same-seed", "different words");
    check(!other, "other-seed", "same words");

    for (int k = 0; k < 100; ++k) {
        const auto v = int_in_range(secure_word, 1, 6);
        check(v >= 1 && v <= 6, "secure-words", "out of range");
    }
    for (std::size_t n : {0, 1, 16, 32, 300}) {
        const std::string token = token_hex(n);
        check(std::regex_match(token, std::regex("[0-9a-f]*")) && token.size() == 2 * n, "token-hex", "wrong digits");
    }
    check(token_hex(16) != token_hex(16), "tokens-differ", "equal");

    if (failures > 0) {
        std::printf("%d failures\n", failures);
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
RandomNumbers.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

import java.security.SecureRandom;
import java.util.Collections;
import java.util.HexFormat;
import java.util.List;
import java.util.Random;
import java.util.function.IntSupplier;

/** Random integers in a range, a shuffle, a seeded generator and tokens. */
public final class RandomNumbers {
    private static final long WORDS = 1L << 32;
    private static final SecureRandom SECURE = new SecureRandom();

    private RandomNumbers() {}

    /**
     * Returns an integer from lo to hi, each with equal probability. nextWord gives all 32 bits of
     * an int, and the method reads them as an unsigned value. A word below 2^32 % n is rejected,
     * so that each remainder comes from the same number of words.
     */
    public static long intInRange(IntSupplier nextWord, long lo, long hi) {
        // hi - lo can overflow a long, but read as unsigned it is the true difference.
        if (hi < lo || Long.compareUnsigned(hi - lo, WORDS - 1) > 0) {
            throw new IllegalArgumentException("need lo <= hi and at most 2^32 values");
        }
        long n = hi - lo + 1;
        long least = WORDS % n;
        while (true) {
            long word = Integer.toUnsignedLong(nextWord.getAsInt());
            if (word >= least) {
                return lo + word % n;
            }
        }
    }

    /** Shuffles items in place with the Fisher-Yates method. */
    public static void shuffle(IntSupplier nextWord, List<?> items) {
        for (int i = items.size() - 1; i > 0; i--) {
            int j = (int) intInRange(nextWord, 0, i);
            Collections.swap(items, i, j);
        }
    }

    /** Returns a word source that gives the same words for the same seed. */
    public static IntSupplier seededWords(long seed) {
        return new Random(seed)::nextInt;
    }

    /** Returns a word source from the secure generator of the platform. */
    public static IntSupplier secureWords() {
        return SECURE::nextInt;
    }

    /** Returns nbytes secure random bytes as 2 * nbytes lowercase hexadecimal digits. */
    public static String tokenHex(int nbytes) {
        byte[] bytes = new byte[nbytes];
        SECURE.nextBytes(bytes);
        return HexFormat.of().formatHex(bytes);
    }
}
RandomNumbersTest.java 127 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.List;
import java.util.function.IntSupplier;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;

class RandomNumbersTest {
    static Stream<Arguments> rangeCases() {
        return Stream.of(
                Arguments.of("coin", new long[] {5L, 2L, 7L}, 0L, 1L, 3, List.of(1L, 0L, 1L)),
                Arguments.of("no-results", new long[] {}, 1L, 6L, 0, List.of()),
                Arguments.of("die", new long[] {7L, 12L, 1000000L, 4294967295L}, 1L, 6L, 4, List.of(2L, 1L, 5L, 4L)),
                Arguments.of("negative-range", new long[] {100L, 2000000000L, 4294967294L}, -10L, 10L, 3, List.of(6L, -5L, -8L)),
                Arguments.of("one-value", new long[] {0L, 99L}, 5L, 5L, 2, List.of(5L, 5L)),
                Arguments.of("reject-low-words", new long[] {0L, 3L, 4L}, 1L, 6L, 1, List.of(5L)),
                Arguments.of("accept-least", new long[] {3L, 4L, 9L}, 0L, 5L, 2, List.of(4L, 3L)),
                Arguments.of("power-of-two", new long[] {0L, 4294967295L}, 0L, 7L, 2, List.of(0L, 7L)),
                Arguments.of("worst-case", new long[] {2147483646L, 2147483647L}, 0L, 2147483648L, 1, List.of(2147483647L)),
                Arguments.of("full-unsigned-32", new long[] {0L, 4294967295L, 123456789L}, 0L, 4294967295L, 3, List.of(0L, 4294967295L, 123456789L)),
                Arguments.of("full-signed-32", new long[] {0L, 2147483648L, 4294967295L}, -2147483648L, 2147483647L, 3, List.of(-2147483648L, 0L, 2147483647L)),
                Arguments.of("near-int64-max", new long[] {4294967295L, 6L}, 9223372036854775798L, 9223372036854775807L, 2, List.of(9223372036854775803L, 9223372036854775804L)),
                Arguments.of("near-int64-min", new long[] {4294967295L, 9L}, Long.MIN_VALUE, -9223372036854775799L, 2, List.of(-9223372036854775803L, -9223372036854775799L)),
                Arguments.of("wide-int64", new long[] {4294967295L, 0L}, 9223372032559808512L, 9223372036854775807L, 2, List.of(9223372036854775807L, 9223372032559808512L))
        );
    }

    static Stream<Arguments> shuffleCases() {
        return Stream.of(
                Arguments.of("empty", new long[] {}, List.of(), List.of()),
                Arguments.of("one-item", new long[] {}, List.of("a"), List.of("a")),
                Arguments.of("two-items-swap", new long[] {0L}, List.of("a", "b"), List.of("b", "a")),
                Arguments.of("two-items-keep", new long[] {1L}, List.of("a", "b"), List.of("a", "b")),
                Arguments.of("five-items", new long[] {7L, 3L, 4L, 1L}, List.of("a", "b", "c", "d", "e"), List.of("a", "e", "b", "d", "c")),
                Arguments.of("reject-in-shuffle", new long[] {0L, 2L, 0L}, List.of("a", "b", "c"), List.of("b", "a", "c")),
                Arguments.of("duplicates", new long[] {1L, 1L}, List.of("x", "x", "y"), List.of("x", "y", "x")),
                Arguments.of("non-ascii", new long[] {4294967295L, 4294967294L, 0L}, List.of("é", "日本", "🙂", "a"), List.of("日本", "é", "🙂", "a"))
        );
    }

    /** A word source that gives the words in order. */
    private static final class FakeWords implements IntSupplier {
        private final long[] words;
        private int next;

        FakeWords(long[] words) {
            this.words = words;
        }

        @Override
        public int getAsInt() {
            return (int) words[next++];
        }

        boolean usedAll() {
            return next == words.length;
        }
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("rangeCases")
    void intInRange(String name, long[] words, long lo, long hi, int count, List<Long> want) {
        FakeWords source = new FakeWords(words);
        List<Long> got = LongStream.range(0, count).mapToObj(k -> RandomNumbers.intInRange(source, lo, hi)).toList();
        assertEquals(want, got, name);
        assertTrue(source.usedAll(), name);
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("shuffleCases")
    void shuffle(String name, long[] words, List<String> items, List<String> want) {
        FakeWords source = new FakeWords(words);
        List<String> got = new ArrayList<>(items);
        RandomNumbers.shuffle(source, got);
        assertEquals(want, got, name);
        assertTrue(source.usedAll(), name);
    }

    @Test
    void badRangeThrows() {
        assertThrows(IllegalArgumentException.class, () -> RandomNumbers.intInRange(() -> 0, 1, 0));
        assertThrows(IllegalArgumentException.class, () -> RandomNumbers.intInRange(() -> 0, 0, 1L << 32));
        assertThrows(IllegalArgumentException.class, () -> RandomNumbers.intInRange(() -> 0, Long.MIN_VALUE, Long.MAX_VALUE));
    }

    @Test
    void sameSeedSameWords() {
        IntSupplier a = RandomNumbers.seededWords(42);
        IntSupplier b = RandomNumbers.seededWords(42);
        IntSupplier c = RandomNumbers.seededWords(43);
        List<Integer> first = Stream.generate(a::getAsInt).limit(10).toList();
        assertEquals(first, Stream.generate(b::getAsInt).limit(10).toList());
        assertNotEquals(first, Stream.generate(c::getAsInt).limit(10).toList());
    }

    @Test
    void secureWordsInRange() {
        IntSupplier source = RandomNumbers.secureWords();
        for (int i = 0; i < 100; i++) {
            long v = RandomNumbers.intInRange(source, 1, 6);
            assertTrue(v >= 1 && v <= 6);
        }
    }

    @ParameterizedTest
    @ValueSource(ints = {0, 1, 16, 32})
    void tokenHex(int nbytes) {
        assertTrue(RandomNumbers.tokenHex(nbytes).matches("[0-9a-f]{" + 2 * nbytes + "}"));
    }

    @Test
    void tokensDiffer() {
        assertNotEquals(RandomNumbers.tokenHex(16), RandomNumbers.tokenHex(16));
    }
}
random_numbers.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

#define _DEFAULT_SOURCE

#include "random_numbers.h"

#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#if defined(__APPLE__)
#include <sys/random.h> // macOS declares getentropy here, not in <unistd.h>.
#endif

#define WORDS (UINT64_C(1) << 32)

// POSIX puts the limit of one call to getentropy in GETENTROPY_MAX. macOS does
// not define it, and its manual gives 256 bytes.
#ifndef GETENTROPY_MAX
#define GETENTROPY_MAX 256
#endif

bool int_in_range(random_words *next_word, void *ctx, int64_t lo, int64_t hi, int64_t *out) {
    // The unsigned difference is exact, also when hi - lo overflows int64_t.
    uint64_t span = (uint64_t)hi - (uint64_t)lo;
    if (hi < lo || span >= WORDS) {
        return false;
    }
    uint64_t n = span + 1;
    uint64_t least = WORDS % n;
    for (;;) {
        uint64_t word = next_word(ctx);
        if (word >= least) {
            // The sum is at most hi, so it fits. The unsigned addition avoids
            // the overflow of lo + (int64_t)r when r > INT64_MAX - lo.
            *out = (int64_t)((uint64_t)lo + word % n);
            return true;
        }
    }
}

static void swap_bytes(unsigned char *a, unsigned char *b, size_t size) {
    for (size_t k = 0; k < size; k++) {
        unsigned char t = a[k];
        a[k] = b[k];
        b[k] = t;
    }
}

bool shuffle(random_words *next_word, void *ctx, void *items, size_t count, size_t size) {
    if (count > WORDS) {
        return false;
    }
    unsigned char *base = items;
    for (size_t i = count > 0 ? count - 1 : 0; i > 0; i--) {
        int64_t j;
        int_in_range(next_word, ctx, 0, (int64_t)i, &j);
        if ((size_t)j != i) {
            swap_bytes(base + i * size, base + (size_t)j * size, size);
        }
    }
    return true;
}

uint32_t splitmix64_word(void *ctx) {
    struct splitmix64 *g = ctx;
    uint64_t z = (g->state += UINT64_C(0x9e3779b97f4a7c15));
    z = (z ^ (z >> 30)) * UINT64_C(0xbf58476d1ce4e5b9);
    z = (z ^ (z >> 27)) * UINT64_C(0x94d049bb133111eb);
    z ^= z >> 31;
    return (uint32_t)(z >> 32);
}

uint32_t secure_word(void *ctx) {
    (void)ctx;
    uint32_t w;
    if (getentropy(&w, sizeof w) != 0) {
        abort();
    }
    return w;
}

bool token_hex(size_t nbytes, char *out, size_t size) {
    static const char digits[] = "0123456789abcdef";
    if (nbytes > (SIZE_MAX - 1) / 2 || size < 2 * nbytes + 1) {
        return false;
    }
    unsigned char chunk[GETENTROPY_MAX];
    size_t done = 0;
    while (done < nbytes) {
        size_t len = nbytes - done < sizeof chunk ? nbytes - done : sizeof chunk;
        if (getentropy(chunk, len) != 0) {
            return false;
        }
        for (size_t k = 0; k < len; k++) {
            out[2 * (done + k)] = digits[chunk[k] >> 4];
            out[2 * (done + k) + 1] = digits[chunk[k] & 0xf];
        }
        done += len;
    }
    out[2 * nbytes] = '\0';
    return true;
}
random_numbers.h 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

#ifndef RANDOM_NUMBERS_H
#define RANDOM_NUMBERS_H

#include <stddef.h>
#include <stdint.h>

// A word source returns a random integer from 0 to 2^32 - 1. ctx is its state.
typedef uint32_t random_words(void *ctx);

// Stores in *out an integer from lo to hi, each with equal probability, and
// returns true. Returns false if hi < lo or the range has more than 2^32
// values. A word below 2^32 % n is rejected, so that each remainder comes
// from the same number of words.
bool int_in_range(random_words *next_word, void *ctx, int64_t lo, int64_t hi, int64_t *out);

// Shuffles count items of size bytes each in place with the Fisher-Yates
// method. Returns false if count is more than 2^32.
bool shuffle(random_words *next_word, void *ctx, void *items, size_t count, size_t size);

// SplitMix64 (Steele, Lea and Flood), as in the reference code of Sebastiano
// Vigna. The same seed gives the same words.
struct splitmix64 {
    uint64_t state;
};

// A word source: the top 32 bits of the next output of a struct splitmix64.
uint32_t splitmix64_word(void *ctx);

// A word source from getentropy. It aborts if getentropy fails. ctx is unused.
uint32_t secure_word(void *ctx);

// Writes nbytes secure random bytes as 2 * nbytes lowercase hexadecimal
// digits and a null byte to out, and returns true. Returns false if size is
// less than 2 * nbytes + 1 or if getentropy fails.
bool token_hex(size_t nbytes, char *out, size_t size);

#endif
test_random_numbers.c 160 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

#include "random_numbers.h"

#include <inttypes.h>
#include <stdio.h>
#include <string.h>

struct range_case {
    const char *name;
    uint32_t words[8];
    size_t nwords;
    int64_t lo, hi;
    size_t count;
    int64_t want[8];
};

static const struct range_case range_cases[] = {
    {"coin", {UINT32_C(5), UINT32_C(2), UINT32_C(7)}, 3, INT64_C(0), INT64_C(1), 3, {INT64_C(1), INT64_C(0), INT64_C(1)}},
    {"no-results", {}, 0, INT64_C(1), INT64_C(6), 0, {}},
    {"die", {UINT32_C(7), UINT32_C(12), UINT32_C(1000000), UINT32_C(4294967295)}, 4, INT64_C(1), INT64_C(6), 4, {INT64_C(2), INT64_C(1), INT64_C(5), INT64_C(4)}},
    {"negative-range", {UINT32_C(100), UINT32_C(2000000000), UINT32_C(4294967294)}, 3, INT64_C(-10), INT64_C(10), 3, {INT64_C(6), INT64_C(-5), INT64_C(-8)}},
    {"one-value", {UINT32_C(0), UINT32_C(99)}, 2, INT64_C(5), INT64_C(5), 2, {INT64_C(5), INT64_C(5)}},
    {"reject-low-words", {UINT32_C(0), UINT32_C(3), UINT32_C(4)}, 3, INT64_C(1), INT64_C(6), 1, {INT64_C(5)}},
    {"accept-least", {UINT32_C(3), UINT32_C(4), UINT32_C(9)}, 3, INT64_C(0), INT64_C(5), 2, {INT64_C(4), INT64_C(3)}},
    {"power-of-two", {UINT32_C(0), UINT32_C(4294967295)}, 2, INT64_C(0), INT64_C(7), 2, {INT64_C(0), INT64_C(7)}},
    {"worst-case", {UINT32_C(2147483646), UINT32_C(2147483647)}, 2, INT64_C(0), INT64_C(2147483648), 1, {INT64_C(2147483647)}},
    {"full-unsigned-32", {UINT32_C(0), UINT32_C(4294967295), UINT32_C(123456789)}, 3, INT64_C(0), INT64_C(4294967295), 3, {INT64_C(0), INT64_C(4294967295), INT64_C(123456789)}},
    {"full-signed-32", {UINT32_C(0), UINT32_C(2147483648), UINT32_C(4294967295)}, 3, INT64_C(-2147483648), INT64_C(2147483647), 3, {INT64_C(-2147483648), INT64_C(0), INT64_C(2147483647)}},
    {"near-int64-max", {UINT32_C(4294967295), UINT32_C(6)}, 2, INT64_C(9223372036854775798), INT64_C(9223372036854775807), 2, {INT64_C(9223372036854775803), INT64_C(9223372036854775804)}},
    {"near-int64-min", {UINT32_C(4294967295), UINT32_C(9)}, 2, INT64_MIN, INT64_C(-9223372036854775799), 2, {INT64_C(-9223372036854775803), INT64_C(-9223372036854775799)}},
    {"wide-int64", {UINT32_C(4294967295), UINT32_C(0)}, 2, INT64_C(9223372032559808512), INT64_C(9223372036854775807), 2, {INT64_C(9223372036854775807), INT64_C(9223372032559808512)}},
};

struct shuffle_case {
    const char *name;
    uint32_t words[8];
    size_t nwords;
    const char *items[8];
    const char *want[8];
    size_t count;
};

static const struct shuffle_case shuffle_cases[] = {
    {"empty", {}, 0, {}, {}, 0},
    {"one-item", {}, 0, {"a"}, {"a"}, 1},
    {"two-items-swap", {UINT32_C(0)}, 1, {"a", "b"}, {"b", "a"}, 2},
    {"two-items-keep", {UINT32_C(1)}, 1, {"a", "b"}, {"a", "b"}, 2},
    {"five-items", {UINT32_C(7), UINT32_C(3), UINT32_C(4), UINT32_C(1)}, 4, {"a", "b", "c", "d", "e"}, {"a", "e", "b", "d", "c"}, 5},
    {"reject-in-shuffle", {UINT32_C(0), UINT32_C(2), UINT32_C(0)}, 3, {"a", "b", "c"}, {"b", "a", "c"}, 3},
    {"duplicates", {UINT32_C(1), UINT32_C(1)}, 2, {"x", "x", "y"}, {"x", "y", "x"}, 3},
    {"non-ascii", {UINT32_C(4294967295), UINT32_C(4294967294), UINT32_C(0)}, 3, {"é", "日本", "🙂", "a"}, {"日本", "é", "🙂", "a"}, 4},
};

// A word source that gives the words in order.
struct fake_words {
    const uint32_t *words;
    size_t len, next;
};

static uint32_t fake_word(void *ctx) {
    struct fake_words *f = ctx;
    if (f->next >= f->len) {
        fprintf(stderr, "no more words\n");
        return 0;
    }
    return f->words[f->next++];
}

static int failures;

static void check(bool ok, const char *name, const char *what) {
    if (!ok) {
        printf("FAIL %s: %s\n", name, what);
        failures++;
    }
}

static void test_ranges(void) {
    for (size_t i = 0; i < sizeof range_cases / sizeof range_cases[0]; i++) {
        const struct range_case *c = &range_cases[i];
        struct fake_words f = {c->words, c->nwords, 0};
        for (size_t k = 0; k < c->count; k++) {
            int64_t got;
            check(int_in_range(fake_word, &f, c->lo, c->hi, &got), c->name, "returned false");
            check(got == c->want[k], c->name, "wrong value");
        }
        check(f.next == f.len, c->name, "did not use all words");
    }
}

static void test_shuffles(void) {
    for (size_t i = 0; i < sizeof shuffle_cases / sizeof shuffle_cases[0]; i++) {
        const struct shuffle_case *c = &shuffle_cases[i];
        struct fake_words f = {c->words, c->nwords, 0};
        const char *items[8];
        memcpy(items, c->items, sizeof items);
        check(shuffle(fake_word, &f, items, c->count, sizeof items[0]), c->name, "returned false");
        for (size_t k = 0; k < c->count; k++) {
            check(strcmp(items[k], c->want[k]) == 0, c->name, "wrong order");
        }
        check(f.next == f.len, c->name, "did not use all words");
    }
}

static void test_bad_ranges(void) {
    int64_t out;
    check(!int_in_range(secure_word, nullptr, 1, 0, &out), "bad-range", "hi < lo");
    check(!int_in_range(secure_word, nullptr, 0, INT64_C(1) << 32, &out), "bad-range", "2^32 + 1 values");
    check(!int_in_range(secure_word, nullptr, INT64_MIN, INT64_MAX, &out), "bad-range", "2^64 values");
}

static void test_splitmix64(void) {
    static const uint32_t want[] = {3184996902, 686809907, 1196582743, 1478287871, 163338330};
    struct splitmix64 g = {42};
    for (size_t k = 0; k < 5; k++) {
        check(splitmix64_word(&g) == want[k], "splitmix64", "differs from the reference code");
    }
    struct splitmix64 a = {7}, b = {7}, c = {8};
    bool same = true, other = true;
    for (int k = 0; k < 10; k++) {
        uint32_t wa = splitmix64_word(&a);
        same = same && wa == splitmix64_word(&b);
        other = other && wa == splitmix64_word(&c);
    }
    check(same, "same-seed", "different words");
    check(!other, "other-seed", "same words");
}

static void test_secure(void) {
    for (int k = 0; k < 100; k++) {
        int64_t v;
        check(int_in_range(secure_word, nullptr, 1, 6, &v) && v >= 1 && v <= 6, "secure-words", "out of range");
    }
    static const size_t sizes[] = {0, 1, 16, 32, 300};
    for (size_t i = 0; i < sizeof sizes / sizeof sizes[0]; i++) {
        char buf[601];
        check(token_hex(sizes[i], buf, sizeof buf), "token-hex", "returned false");
        check(strlen(buf) == 2 * sizes[i], "token-hex", "wrong length");
        check(strspn(buf, "0123456789abcdef") == 2 * sizes[i], "token-hex", "not lowercase hex");
    }
    char a[33], b[33], small[32];
    check(token_hex(16, a, sizeof a) && token_hex(16, b, sizeof b) && strcmp(a, b) != 0, "tokens-differ", "equal");
    check(!token_hex(16, small, sizeof small), "token-hex-small", "returned true");
}

int main(void) {
    test_ranges();
    test_shuffles();
    test_bad_ranges();
    test_splitmix64();
    test_secure();
    if (failures > 0) {
        printf("%d failures\n", failures);
        return 1;
    }
    printf("ok\n");
    return 0;
}
RandomNumbers.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

using System.Security.Cryptography;

/// <summary>Random integers in a range, a shuffle, a seeded generator and tokens.</summary>
public static class RandomNumbers
{
    private const ulong Words = 1UL << 32;

    /// <summary>
    /// Returns an integer from lo to hi, each with equal probability. A word below 2^32 % n is
    /// rejected, so that each remainder comes from the same number of words.
    /// </summary>
    public static long IntInRange(Func<uint> nextWord, long lo, long hi)
    {
        // hi - lo can overflow a long, but as a ulong it is the true difference.
        ulong span = unchecked((ulong)(hi - lo));
        if (hi < lo || span >= Words)
        {
            throw new ArgumentException("need lo <= hi and at most 2^32 values");
        }
        ulong n = span + 1;
        ulong least = Words % n;
        while (true)
        {
            uint word = nextWord();
            if (word >= least)
            {
                return unchecked(lo + (long)(word % n));
            }
        }
    }

    /// <summary>Shuffles items in place with the Fisher-Yates method.</summary>
    public static void Shuffle<T>(Func<uint> nextWord, IList<T> items)
    {
        for (int i = items.Count - 1; i > 0; i--)
        {
            int j = (int)IntInRange(nextWord, 0, i);
            (items[i], items[j]) = (items[j], items[i]);
        }
    }

    /// <summary>Returns a word source that gives the same words for the same seed.</summary>
    public static Func<uint> SeededWords(int seed)
    {
        var random = new Random(seed);
        return () => (uint)random.NextInt64(1L << 32);
    }

    /// <summary>Returns a word source from the secure generator of the platform.</summary>
    public static Func<uint> SecureWords() =>
        () => BitConverter.ToUInt32(RandomNumberGenerator.GetBytes(sizeof(uint)));

    /// <summary>Returns nbytes secure random bytes as 2 * nbytes lowercase hexadecimal digits.</summary>
    public static string TokenHex(int nbytes) =>
        RandomNumberGenerator.GetHexString(2 * nbytes, lowercase: true);
}
RandomNumbersTests.cs 114 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

using System.Text.RegularExpressions;
using Xunit;

public sealed class RandomNumbersTests
{
    public static TheoryData<string, uint[], long, long, int, long[]> RangeCases => new()
    {
        { "coin", new uint[] {5u, 2u, 7u}, 0L, 1L, 3, [1L, 0L, 1L] },
        { "no-results", new uint[] {}, 1L, 6L, 0, [] },
        { "die", new uint[] {7u, 12u, 1000000u, 4294967295u}, 1L, 6L, 4, [2L, 1L, 5L, 4L] },
        { "negative-range", new uint[] {100u, 2000000000u, 4294967294u}, -10L, 10L, 3, [6L, -5L, -8L] },
        { "one-value", new uint[] {0u, 99u}, 5L, 5L, 2, [5L, 5L] },
        { "reject-low-words", new uint[] {0u, 3u, 4u}, 1L, 6L, 1, [5L] },
        { "accept-least", new uint[] {3u, 4u, 9u}, 0L, 5L, 2, [4L, 3L] },
        { "power-of-two", new uint[] {0u, 4294967295u}, 0L, 7L, 2, [0L, 7L] },
        { "worst-case", new uint[] {2147483646u, 2147483647u}, 0L, 2147483648L, 1, [2147483647L] },
        { "full-unsigned-32", new uint[] {0u, 4294967295u, 123456789u}, 0L, 4294967295L, 3, [0L, 4294967295L, 123456789L] },
        { "full-signed-32", new uint[] {0u, 2147483648u, 4294967295u}, -2147483648L, 2147483647L, 3, [-2147483648L, 0L, 2147483647L] },
        { "near-int64-max", new uint[] {4294967295u, 6u}, 9223372036854775798L, 9223372036854775807L, 2, [9223372036854775803L, 9223372036854775804L] },
        { "near-int64-min", new uint[] {4294967295u, 9u}, long.MinValue, -9223372036854775799L, 2, [-9223372036854775803L, -9223372036854775799L] },
        { "wide-int64", new uint[] {4294967295u, 0u}, 9223372032559808512L, 9223372036854775807L, 2, [9223372036854775807L, 9223372032559808512L] },
    };

    public static TheoryData<string, uint[], string[], string[]> ShuffleCases => new()
    {
        { "empty", new uint[] {}, [], [] },
        { "one-item", new uint[] {}, ["a"], ["a"] },
        { "two-items-swap", new uint[] {0u}, ["a", "b"], ["b", "a"] },
        { "two-items-keep", new uint[] {1u}, ["a", "b"], ["a", "b"] },
        { "five-items", new uint[] {7u, 3u, 4u, 1u}, ["a", "b", "c", "d", "e"], ["a", "e", "b", "d", "c"] },
        { "reject-in-shuffle", new uint[] {0u, 2u, 0u}, ["a", "b", "c"], ["b", "a", "c"] },
        { "duplicates", new uint[] {1u, 1u}, ["x", "x", "y"], ["x", "y", "x"] },
        { "non-ascii", new uint[] {4294967295u, 4294967294u, 0u}, ["é", "日本", "🙂", "a"], ["日本", "é", "🙂", "a"] },
    };

    /// <summary>A word source that gives the words in order.</summary>
    private sealed class FakeWords(uint[] words)
    {
        private int next;

        public uint Next() => words[next++];

        public bool UsedAll => next == words.Length;
    }

    [Theory]
    [MemberData(nameof(RangeCases))]
    public void IntInRange(string name, uint[] words, long lo, long hi, int count, long[] want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        var source = new FakeWords(words);
        long[] got = [.. Enumerable.Range(0, count).Select(_ => RandomNumbers.IntInRange(source.Next, lo, hi))];
        Assert.Equal(want, got);
        Assert.True(source.UsedAll);
    }

    [Theory]
    [MemberData(nameof(ShuffleCases))]
    public void Shuffle(string name, uint[] words, string[] items, string[] want)
    {
        Assert.False(string.IsNullOrEmpty(name));
        var source = new FakeWords(words);
        string[] got = [.. items];
        RandomNumbers.Shuffle(source.Next, got);
        Assert.Equal(want, got);
        Assert.True(source.UsedAll);
    }

    [Fact]
    public void BadRangeThrows()
    {
        Assert.Throws<ArgumentException>(() => RandomNumbers.IntInRange(() => 0, 1, 0));
        Assert.Throws<ArgumentException>(() => RandomNumbers.IntInRange(() => 0, 0, 1L << 32));
        Assert.Throws<ArgumentException>(() => RandomNumbers.IntInRange(() => 0, long.MinValue, long.MaxValue));
    }

    [Fact]
    public void SameSeedSameWords()
    {
        Func<uint> a = RandomNumbers.SeededWords(42), b = RandomNumbers.SeededWords(42), c = RandomNumbers.SeededWords(43);
        uint[] first = [.. Enumerable.Range(0, 10).Select(_ => a())];
        Assert.Equal(first, Enumerable.Range(0, 10).Select(_ => b()));
        Assert.NotEqual(first, Enumerable.Range(0, 10).Select(_ => c()));
    }

    [Fact]
    public void SecureWordsInRange()
    {
        var source = RandomNumbers.SecureWords();
        for (int i = 0; i < 100; i++)
        {
            Assert.InRange(RandomNumbers.IntInRange(source, 1, 6), 1, 6);
        }
    }

    [Theory]
    [InlineData(0)]
    [InlineData(1)]
    [InlineData(16)]
    [InlineData(32)]
    public void TokenHex(int nbytes)
    {
        Assert.Matches(new Regex($"^[0-9a-f]{{{2 * nbytes}}}$"), RandomNumbers.TokenHex(nbytes));
    }

    [Fact]
    public void TokensDiffer()
    {
        Assert.NotEqual(RandomNumbers.TokenHex(16), RandomNumbers.TokenHex(16));
    }
}
randomNumbers.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

import { getRandomValues, randomBytes } from "node:crypto";

const WORDS = 1n << 32n;
const MASK64 = (1n << 64n) - 1n;

/**
 * Returns an integer from lo to hi, each with equal probability. lo and hi
 * are bigints, so that the whole signed 64-bit range works. A word below
 * 2^32 % n is rejected, so that each remainder comes from the same number of
 * words.
 * @param {() => number} nextWord returns an integer from 0 to 2^32 - 1
 * @param {bigint} lo
 * @param {bigint} hi
 * @returns {bigint}
 */
export function intInRange(nextWord, lo, hi) {
  const n = hi - lo + 1n;
  if (n < 1n || n > WORDS) {
    throw new RangeError("need lo <= hi and at most 2^32 values");
  }
  const least = WORDS % n;
  for (;;) {
    const word = BigInt(nextWord());
    if (word >= least) {
      return lo + (word % n);
    }
  }
}

/**
 * Shuffles items in place with the Fisher-Yates method.
 * @template T
 * @param {() => number} nextWord
 * @param {T[]} items
 */
export function shuffle(nextWord, items) {
  for (let i = items.length - 1; i > 0; i--) {
    const j = Number(intInRange(nextWord, 0n, BigInt(i)));
    [items[i], items[j]] = [items[j], items[i]];
  }
}

/**
 * Returns a word source that gives the same words for the same seed. Node.js
 * has no seeded generator, so this is SplitMix64 (Steele, Lea and Flood),
 * as in the reference code of Sebastiano Vigna, with the top 32 bits of each
 * output.
 * @param {bigint} seed
 * @returns {() => number}
 */
export function seededWords(seed) {
  let state = BigInt.asUintN(64, seed);
  return () => {
    state = (state + 0x9e3779b97f4a7c15n) & MASK64;
    let z = state;
    z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK64;
    z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK64;
    z ^= z >> 31n;
    return Number(z >> 32n);
  };
}

/** @returns {() => number} a word source from the secure generator */
export function secureWords() {
  return () => getRandomValues(new Uint32Array(1))[0];
}

/**
 * Returns nbytes secure random bytes as 2 * nbytes hexadecimal digits.
 * @param {number} nbytes
 * @returns {string}
 */
export function tokenHex(nbytes) {
  return randomBytes(nbytes).toString("hex");
}
randomNumbers.test.js 100 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

import assert from "node:assert/strict";
import { test } from "node:test";
import { intInRange, secureWords, seededWords, shuffle, tokenHex } from "./randomNumbers.js";

const rangeCases = [
  ["coin", [5, 2, 7], 0n, 1n, 3, [1n, 0n, 1n]],
  ["no-results", [], 1n, 6n, 0, []],
  ["die", [7, 12, 1000000, 4294967295], 1n, 6n, 4, [2n, 1n, 5n, 4n]],
  ["negative-range", [100, 2000000000, 4294967294], -10n, 10n, 3, [6n, -5n, -8n]],
  ["one-value", [0, 99], 5n, 5n, 2, [5n, 5n]],
  ["reject-low-words", [0, 3, 4], 1n, 6n, 1, [5n]],
  ["accept-least", [3, 4, 9], 0n, 5n, 2, [4n, 3n]],
  ["power-of-two", [0, 4294967295], 0n, 7n, 2, [0n, 7n]],
  ["worst-case", [2147483646, 2147483647], 0n, 2147483648n, 1, [2147483647n]],
  ["full-unsigned-32", [0, 4294967295, 123456789], 0n, 4294967295n, 3, [0n, 4294967295n, 123456789n]],
  ["full-signed-32", [0, 2147483648, 4294967295], -2147483648n, 2147483647n, 3, [-2147483648n, 0n, 2147483647n]],
  ["near-int64-max", [4294967295, 6], 9223372036854775798n, 9223372036854775807n, 2, [9223372036854775803n, 9223372036854775804n]],
  ["near-int64-min", [4294967295, 9], -9223372036854775808n, -9223372036854775799n, 2, [-9223372036854775803n, -9223372036854775799n]],
  ["wide-int64", [4294967295, 0], 9223372032559808512n, 9223372036854775807n, 2, [9223372036854775807n, 9223372032559808512n]],
];

const shuffleCases = [
  ["empty", [], [], []],
  ["one-item", [], ["a"], ["a"]],
  ["two-items-swap", [0], ["a", "b"], ["b", "a"]],
  ["two-items-keep", [1], ["a", "b"], ["a", "b"]],
  ["five-items", [7, 3, 4, 1], ["a", "b", "c", "d", "e"], ["a", "e", "b", "d", "c"]],
  ["reject-in-shuffle", [0, 2, 0], ["a", "b", "c"], ["b", "a", "c"]],
  ["duplicates", [1, 1], ["x", "x", "y"], ["x", "y", "x"]],
  ["non-ascii", [4294967295, 4294967294, 0], ["é", "日本", "🙂", "a"], ["日本", "é", "🙂", "a"]],
];

/** Returns a word source that gives words in order, and a check that all were used. */
function fakeWords(words) {
  let next = 0;
  const source = () => {
    assert.ok(next < words.length, "no more words");
    return words[next++];
  };
  return [source, () => next === words.length];
}

for (const [name, words, lo, hi, count, want] of rangeCases) {
  test(`intInRange ${name}`, () => {
    const [source, usedAll] = fakeWords(words);
    const got = Array.from({ length: count }, () => intInRange(source, lo, hi));
    assert.deepEqual(got, want);
    assert.ok(usedAll());
  });
}

for (const [name, words, items, want] of shuffleCases) {
  test(`shuffle ${name}`, () => {
    const [source, usedAll] = fakeWords(words);
    shuffle(source, items);
    assert.deepEqual(items, want);
    assert.ok(usedAll());
  });
}

test("a bad range throws", () => {
  assert.throws(() => intInRange(() => 0, 1n, 0n), RangeError);
  assert.throws(() => intInRange(() => 0, 0n, 1n << 32n), RangeError);
});

test("SplitMix64 gives the words of the reference code", () => {
  const source = seededWords(42n);
  const got = Array.from({ length: 5 }, source);
  assert.deepEqual(got, [3184996902, 686809907, 1196582743, 1478287871, 163338330]);
});

test("the same seed gives the same words", () => {
  const a = seededWords(7n);
  const b = seededWords(7n);
  const c = seededWords(8n);
  const first = Array.from({ length: 10 }, a);
  assert.deepEqual(Array.from({ length: 10 }, b), first);
  assert.notDeepEqual(Array.from({ length: 10 }, c), first);
});

test("secure words give values in range", () => {
  const source = secureWords();
  for (let i = 0; i < 100; i++) {
    const v = intInRange(source, 1n, 6n);
    assert.ok(v >= 1n && v <= 6n);
  }
});

for (const nbytes of [0, 1, 16, 32]) {
  test(`tokenHex ${nbytes}`, () => {
    assert.match(tokenHex(nbytes), new RegExp(`^[0-9a-f]{${2 * nbytes}}$`));
  });
}

test("tokens differ", () => {
  assert.notEqual(tokenHex(16), tokenHex(16));
});
randomNumbers.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

import { getRandomValues, randomBytes } from "node:crypto";

/** A function that returns a random integer from 0 to 2^32 - 1. */
export type WordSource = () => number;

const WORDS = 1n << 32n;
const MASK64 = (1n << 64n) - 1n;

/**
 * Returns an integer from lo to hi, each with equal probability. A word below
 * 2^32 % n is rejected, so that each remainder comes from the same number of
 * words.
 */
export function intInRange(nextWord: WordSource, lo: bigint, hi: bigint): bigint {
  const n = hi - lo + 1n;
  if (n < 1n || n > WORDS) {
    throw new RangeError("need lo <= hi and at most 2^32 values");
  }
  const least = WORDS % n;
  for (;;) {
    const word = BigInt(nextWord());
    if (word >= least) {
      return lo + (word % n);
    }
  }
}

/** Shuffles items in place with the Fisher-Yates method. */
export function shuffle<T>(nextWord: WordSource, items: T[]): void {
  for (let i = items.length - 1; i > 0; i--) {
    const j = Number(intInRange(nextWord, 0n, BigInt(i)));
    [items[i], items[j]] = [items[j] as T, items[i] as T];
  }
}

/**
 * Returns a word source that gives the same words for the same seed. Node.js
 * has no seeded generator, so this is SplitMix64 (Steele, Lea and Flood),
 * as in the reference code of Sebastiano Vigna, with the top 32 bits of each
 * output.
 */
export function seededWords(seed: bigint): WordSource {
  let state = BigInt.asUintN(64, seed);
  return () => {
    state = (state + 0x9e3779b97f4a7c15n) & MASK64;
    let z = state;
    z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK64;
    z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK64;
    z ^= z >> 31n;
    return Number(z >> 32n);
  };
}

/** Returns a word source from the secure generator. */
export function secureWords(): WordSource {
  return () => getRandomValues(new Uint32Array(1))[0] as number;
}

/** Returns nbytes secure random bytes as 2 * nbytes hexadecimal digits. */
export function tokenHex(nbytes: number): string {
  return randomBytes(nbytes).toString("hex");
}
randomNumbers.test.ts 101 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

import assert from "node:assert/strict";
import { test } from "node:test";
import type { WordSource } from "./randomNumbers.ts";
import { intInRange, secureWords, seededWords, shuffle, tokenHex } from "./randomNumbers.ts";

const rangeCases: [string, number[], bigint, bigint, number, bigint[]][] = [
  ["coin", [5, 2, 7], 0n, 1n, 3, [1n, 0n, 1n]],
  ["no-results", [], 1n, 6n, 0, []],
  ["die", [7, 12, 1000000, 4294967295], 1n, 6n, 4, [2n, 1n, 5n, 4n]],
  ["negative-range", [100, 2000000000, 4294967294], -10n, 10n, 3, [6n, -5n, -8n]],
  ["one-value", [0, 99], 5n, 5n, 2, [5n, 5n]],
  ["reject-low-words", [0, 3, 4], 1n, 6n, 1, [5n]],
  ["accept-least", [3, 4, 9], 0n, 5n, 2, [4n, 3n]],
  ["power-of-two", [0, 4294967295], 0n, 7n, 2, [0n, 7n]],
  ["worst-case", [2147483646, 2147483647], 0n, 2147483648n, 1, [2147483647n]],
  ["full-unsigned-32", [0, 4294967295, 123456789], 0n, 4294967295n, 3, [0n, 4294967295n, 123456789n]],
  ["full-signed-32", [0, 2147483648, 4294967295], -2147483648n, 2147483647n, 3, [-2147483648n, 0n, 2147483647n]],
  ["near-int64-max", [4294967295, 6], 9223372036854775798n, 9223372036854775807n, 2, [9223372036854775803n, 9223372036854775804n]],
  ["near-int64-min", [4294967295, 9], -9223372036854775808n, -9223372036854775799n, 2, [-9223372036854775803n, -9223372036854775799n]],
  ["wide-int64", [4294967295, 0], 9223372032559808512n, 9223372036854775807n, 2, [9223372036854775807n, 9223372032559808512n]],
];

const shuffleCases: [string, number[], string[], string[]][] = [
  ["empty", [], [], []],
  ["one-item", [], ["a"], ["a"]],
  ["two-items-swap", [0], ["a", "b"], ["b", "a"]],
  ["two-items-keep", [1], ["a", "b"], ["a", "b"]],
  ["five-items", [7, 3, 4, 1], ["a", "b", "c", "d", "e"], ["a", "e", "b", "d", "c"]],
  ["reject-in-shuffle", [0, 2, 0], ["a", "b", "c"], ["b", "a", "c"]],
  ["duplicates", [1, 1], ["x", "x", "y"], ["x", "y", "x"]],
  ["non-ascii", [4294967295, 4294967294, 0], ["é", "日本", "🙂", "a"], ["日本", "é", "🙂", "a"]],
];

/** Returns a word source that gives words in order, and a check that all were used. */
function fakeWords(words: number[]): [WordSource, () => boolean] {
  let next = 0;
  const source = () => {
    assert.ok(next < words.length, "no more words");
    return words[next++] as number;
  };
  return [source, () => next === words.length];
}

for (const [name, words, lo, hi, count, want] of rangeCases) {
  test(`intInRange ${name}`, () => {
    const [source, usedAll] = fakeWords(words);
    const got = Array.from({ length: count }, () => intInRange(source, lo, hi));
    assert.deepEqual(got, want);
    assert.ok(usedAll());
  });
}

for (const [name, words, items, want] of shuffleCases) {
  test(`shuffle ${name}`, () => {
    const [source, usedAll] = fakeWords(words);
    shuffle(source, items);
    assert.deepEqual(items, want);
    assert.ok(usedAll());
  });
}

test("a bad range throws", () => {
  assert.throws(() => intInRange(() => 0, 1n, 0n), RangeError);
  assert.throws(() => intInRange(() => 0, 0n, 1n << 32n), RangeError);
});

test("SplitMix64 gives the words of the reference code", () => {
  const source = seededWords(42n);
  const got = Array.from({ length: 5 }, source);
  assert.deepEqual(got, [3184996902, 686809907, 1196582743, 1478287871, 163338330]);
});

test("the same seed gives the same words", () => {
  const a = seededWords(7n);
  const b = seededWords(7n);
  const c = seededWords(8n);
  const first = Array.from({ length: 10 }, a);
  assert.deepEqual(Array.from({ length: 10 }, b), first);
  assert.notDeepEqual(Array.from({ length: 10 }, c), first);
});

test("secure words give values in range", () => {
  const source = secureWords();
  for (let i = 0; i < 100; i++) {
    const v = intInRange(source, 1n, 6n);
    assert.ok(v >= 1n && v <= 6n);
  }
});

for (const nbytes of [0, 1, 16, 32]) {
  test(`tokenHex ${nbytes}`, () => {
    assert.match(tokenHex(nbytes), new RegExp(`^[0-9a-f]{${2 * nbytes}}$`));
  });
}

test("tokens differ", () => {
  assert.notEqual(tokenHex(16), tokenHex(16));
});
random_numbers.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

// Package randomnumbers makes random integers in a range, shuffles a slice,
// and makes seeded word sources and secure tokens.
package randomnumbers

import (
	crand "crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"math/rand/v2"
)

// A WordSource returns a random integer from 0 to 2^32 - 1.
type WordSource func() uint32

const words = 1 << 32

// IntInRange returns an integer from lo to hi, each with equal probability.
// A word below 2^32 % n is rejected, so that each remainder comes from the
// same number of words. It panics if hi < lo or the range has more than
// 2^32 values.
func IntInRange(nextWord WordSource, lo, hi int64) int64 {
	// hi - lo can overflow an int64, but as a uint64 it is the true difference.
	span := uint64(hi) - uint64(lo)
	if hi < lo || span >= words {
		panic("randomnumbers: need lo <= hi and at most 2^32 values")
	}
	n := span + 1
	least := words % n
	for {
		word := uint64(nextWord())
		if word >= least {
			return lo + int64(word%n)
		}
	}
}

// Shuffle shuffles items in place with the Fisher-Yates method.
func Shuffle[T any](nextWord WordSource, items []T) {
	for i := len(items) - 1; i > 0; i-- {
		j := IntInRange(nextWord, 0, int64(i))
		items[i], items[j] = items[j], items[i]
	}
}

// SeededWords returns a word source that gives the same words for the same
// seed.
func SeededWords(seed uint64) WordSource {
	return rand.New(rand.NewPCG(seed, 0)).Uint32
}

// SecureWords returns a word source from crypto/rand.
func SecureWords() WordSource {
	return func() uint32 {
		var b [4]byte
		_, _ = crand.Read(b[:]) // Read never returns an error.
		return binary.LittleEndian.Uint32(b[:])
	}
}

// TokenHex returns nbytes secure random bytes as 2 * nbytes lowercase
// hexadecimal digits.
func TokenHex(nbytes int) string {
	b := make([]byte, nbytes)
	_, _ = crand.Read(b) // Read never returns an error.
	return hex.EncodeToString(b)
}
random_numbers_test.go 138 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

package randomnumbers

import (
	"math"
	"regexp"
	"slices"
	"strconv"
	"testing"
)

var rangeCases = []struct {
	name   string
	words  []uint32
	lo, hi int64
	count  int
	want   []int64
}{
	{"coin", []uint32{5, 2, 7}, 0, 1, 3, []int64{1, 0, 1}},
	{"no-results", []uint32{}, 1, 6, 0, []int64{}},
	{"die", []uint32{7, 12, 1000000, 4294967295}, 1, 6, 4, []int64{2, 1, 5, 4}},
	{"negative-range", []uint32{100, 2000000000, 4294967294}, -10, 10, 3, []int64{6, -5, -8}},
	{"one-value", []uint32{0, 99}, 5, 5, 2, []int64{5, 5}},
	{"reject-low-words", []uint32{0, 3, 4}, 1, 6, 1, []int64{5}},
	{"accept-least", []uint32{3, 4, 9}, 0, 5, 2, []int64{4, 3}},
	{"power-of-two", []uint32{0, 4294967295}, 0, 7, 2, []int64{0, 7}},
	{"worst-case", []uint32{2147483646, 2147483647}, 0, 2147483648, 1, []int64{2147483647}},
	{"full-unsigned-32", []uint32{0, 4294967295, 123456789}, 0, 4294967295, 3, []int64{0, 4294967295, 123456789}},
	{"full-signed-32", []uint32{0, 2147483648, 4294967295}, -2147483648, 2147483647, 3, []int64{-2147483648, 0, 2147483647}},
	{"near-int64-max", []uint32{4294967295, 6}, 9223372036854775798, 9223372036854775807, 2, []int64{9223372036854775803, 9223372036854775804}},
	{"near-int64-min", []uint32{4294967295, 9}, math.MinInt64, -9223372036854775799, 2, []int64{-9223372036854775803, -9223372036854775799}},
	{"wide-int64", []uint32{4294967295, 0}, 9223372032559808512, 9223372036854775807, 2, []int64{9223372036854775807, 9223372032559808512}},
}

var shuffleCases = []struct {
	name  string
	words []uint32
	items []string
	want  []string
}{
	{"empty", []uint32{}, []string{}, []string{}},
	{"one-item", []uint32{}, []string{"a"}, []string{"a"}},
	{"two-items-swap", []uint32{0}, []string{"a", "b"}, []string{"b", "a"}},
	{"two-items-keep", []uint32{1}, []string{"a", "b"}, []string{"a", "b"}},
	{"five-items", []uint32{7, 3, 4, 1}, []string{"a", "b", "c", "d", "e"}, []string{"a", "e", "b", "d", "c"}},
	{"reject-in-shuffle", []uint32{0, 2, 0}, []string{"a", "b", "c"}, []string{"b", "a", "c"}},
	{"duplicates", []uint32{1, 1}, []string{"x", "x", "y"}, []string{"x", "y", "x"}},
	{"non-ascii", []uint32{4294967295, 4294967294, 0}, []string{"é", "日本", "🙂", "a"}, []string{"日本", "é", "🙂", "a"}},
}

// fakeWords returns a word source that gives words in order, and a check
// that all were used.
func fakeWords(t *testing.T, words []uint32) (WordSource, func() bool) {
	next := 0
	source := func() uint32 {
		if next >= len(words) {
			t.Fatal("no more words")
		}
		next++
		return words[next-1]
	}
	return source, func() bool { return next == len(words) }
}

func TestIntInRange(t *testing.T) {
	for _, c := range rangeCases {
		t.Run(c.name, func(t *testing.T) {
			source, usedAll := fakeWords(t, c.words)
			got := make([]int64, 0, c.count)
			for range c.count {
				got = append(got, IntInRange(source, c.lo, c.hi))
			}
			if !slices.Equal(got, c.want) || !usedAll() {
				t.Errorf("got %v, want %v, used all words: %v", got, c.want, usedAll())
			}
		})
	}
}

func TestShuffle(t *testing.T) {
	for _, c := range shuffleCases {
		t.Run(c.name, func(t *testing.T) {
			source, usedAll := fakeWords(t, c.words)
			got := slices.Clone(c.items)
			Shuffle(source, got)
			if !slices.Equal(got, c.want) || !usedAll() {
				t.Errorf("got %q, want %q, used all words: %v", got, c.want, usedAll())
			}
		})
	}
}

func TestBadRangePanics(t *testing.T) {
	for _, r := range [][2]int64{{1, 0}, {0, 1 << 32}, {math.MinInt64, math.MaxInt64}} {
		func() {
			defer func() {
				if recover() == nil {
					t.Errorf("IntInRange(%d, %d) did not panic", r[0], r[1])
				}
			}()
			IntInRange(func() uint32 { return 0 }, r[0], r[1])
		}()
	}
}

func TestSameSeedSameWords(t *testing.T) {
	a, b, c := SeededWords(42), SeededWords(42), SeededWords(43)
	var wa, wb, wc []uint32
	for range 10 {
		wa, wb, wc = append(wa, a()), append(wb, b()), append(wc, c())
	}
	if !slices.Equal(wa, wb) || slices.Equal(wa, wc) {
		t.Errorf("seed 42: %v and %v, seed 43: %v", wa, wb, wc)
	}
}

func TestSecureWordsInRange(t *testing.T) {
	source := SecureWords()
	for range 100 {
		if v := IntInRange(source, 1, 6); v < 1 || v > 6 {
			t.Fatalf("got %d", v)
		}
	}
}

func TestTokenHex(t *testing.T) {
	for _, n := range []int{0, 1, 16, 32} {
		re := regexp.MustCompile("^[0-9a-f]{" + strconv.Itoa(2*n) + "}$")
		if got := TokenHex(n); !re.MatchString(got) {
			t.Errorf("TokenHex(%d) = %q", n, got)
		}
	}
	if TokenHex(16) == TokenHex(16) {
		t.Error("two tokens are equal")
	}
}
random_numbers.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

//! Random integers in a range, a shuffle, a seeded generator and tokens.
//!
//! The standard library has no random number generator, so this module has
//! `SplitMix64` for seeded words, and it reads `/dev/urandom` for secure bytes,
//! which works on Linux and macOS.

use std::fmt::Write as _;
use std::fs::File;
use std::io::{self, Read};

const WORDS: u64 = 1 << 32;

/// Returns an integer from `lo` to `hi`, each with equal probability.
///
/// `next_word` returns a random integer from 0 to 2^32 - 1. A word below
/// 2^32 % n is rejected, so that each remainder comes from the same number
/// of words.
///
/// # Panics
///
/// Panics if `hi < lo` or if the range has more than 2^32 values.
pub fn int_in_range(next_word: &mut impl FnMut() -> u32, lo: i64, hi: i64) -> i64 {
    let span = hi.abs_diff(lo);
    assert!(
        lo <= hi && span < WORDS,
        "need lo <= hi and at most 2^32 values"
    );
    let n = span + 1;
    let least = WORDS % n;
    loop {
        let word = u64::from(next_word());
        if word >= least {
            // word % n <= hi - lo, so the sum is at most hi.
            return lo.wrapping_add_unsigned(word % n);
        }
    }
}

/// Shuffles `items` in place with the Fisher-Yates method.
///
/// # Panics
///
/// Panics if `items` has more than 2^32 items.
pub fn shuffle<T>(next_word: &mut impl FnMut() -> u32, items: &mut [T]) {
    for i in (1..items.len()).rev() {
        let top = i64::try_from(i).expect("a slice index fits in i64");
        let j = usize::try_from(int_in_range(next_word, 0, top)).expect("0 <= j <= i");
        items.swap(i, j);
    }
}

/// Returns a word source that gives the same words for the same seed.
///
/// This is `SplitMix64` (Steele, Lea and Flood), as in the reference code of
/// Sebastiano Vigna, with the top 32 bits of each output.
pub fn seeded_words(seed: u64) -> impl FnMut() -> u32 {
    let mut state = seed;
    move || {
        state = state.wrapping_add(0x9e37_79b9_7f4a_7c15);
        let mut z = state;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^= z >> 31;
        (z >> 32) as u32
    }
}

/// Fills `buf` with secure random bytes from `/dev/urandom`.
///
/// # Errors
///
/// Returns the error of the open or the read.
pub fn secure_bytes(buf: &mut [u8]) -> io::Result<()> {
    File::open("/dev/urandom")?.read_exact(buf)
}

/// Returns a word source from `/dev/urandom`.
///
/// # Errors
///
/// Returns the error if the file does not open.
///
/// # Panics
///
/// The source panics if a read fails.
pub fn secure_words() -> io::Result<impl FnMut() -> u32> {
    let mut file = File::open("/dev/urandom")?;
    Ok(move || {
        let mut b = [0u8; 4];
        file.read_exact(&mut b).expect("read /dev/urandom");
        u32::from_le_bytes(b)
    })
}

/// Returns `nbytes` secure random bytes as 2 * `nbytes` lowercase
/// hexadecimal digits.
///
/// # Errors
///
/// Returns the error of [`secure_bytes`].
pub fn token_hex(nbytes: usize) -> io::Result<String> {
    let mut bytes = vec![0u8; nbytes];
    secure_bytes(&mut bytes)?;
    let mut out = String::with_capacity(2 * nbytes);
    for b in bytes {
        write!(out, "{b:02x}").expect("a write to a String does not fail");
    }
    Ok(out)
}
tests/random_numbers_test.rs 199 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/generate-random-numbers/.

use algo_generate_random_numbers::{int_in_range, secure_words, seeded_words, shuffle, token_hex};

type RangeCase = (
    &'static str,
    &'static [u32],
    i64,
    i64,
    usize,
    &'static [i64],
);
type ShuffleCase = (
    &'static str,
    &'static [u32],
    &'static [&'static str],
    &'static [&'static str],
);

const RANGE_CASES: &[RangeCase] = &[
    ("coin", &[5, 2, 7], 0, 1, 3, &[1, 0, 1]),
    ("no-results", &[], 1, 6, 0, &[]),
    ("die", &[7, 12, 1000000, 4294967295], 1, 6, 4, &[2, 1, 5, 4]),
    (
        "negative-range",
        &[100, 2000000000, 4294967294],
        -10,
        10,
        3,
        &[6, -5, -8],
    ),
    ("one-value", &[0, 99], 5, 5, 2, &[5, 5]),
    ("reject-low-words", &[0, 3, 4], 1, 6, 1, &[5]),
    ("accept-least", &[3, 4, 9], 0, 5, 2, &[4, 3]),
    ("power-of-two", &[0, 4294967295], 0, 7, 2, &[0, 7]),
    (
        "worst-case",
        &[2147483646, 2147483647],
        0,
        2147483648,
        1,
        &[2147483647],
    ),
    (
        "full-unsigned-32",
        &[0, 4294967295, 123456789],
        0,
        4294967295,
        3,
        &[0, 4294967295, 123456789],
    ),
    (
        "full-signed-32",
        &[0, 2147483648, 4294967295],
        -2147483648,
        2147483647,
        3,
        &[-2147483648, 0, 2147483647],
    ),
    (
        "near-int64-max",
        &[4294967295, 6],
        9223372036854775798,
        9223372036854775807,
        2,
        &[9223372036854775803, 9223372036854775804],
    ),
    (
        "near-int64-min",
        &[4294967295, 9],
        i64::MIN,
        -9223372036854775799,
        2,
        &[-9223372036854775803, -9223372036854775799],
    ),
    (
        "wide-int64",
        &[4294967295, 0],
        9223372032559808512,
        9223372036854775807,
        2,
        &[9223372036854775807, 9223372032559808512],
    ),
];

const SHUFFLE_CASES: &[ShuffleCase] = &[
    ("empty", &[], &[], &[]),
    ("one-item", &[], &["a"], &["a"]),
    ("two-items-swap", &[0], &["a", "b"], &["b", "a"]),
    ("two-items-keep", &[1], &["a", "b"], &["a", "b"]),
    (
        "five-items",
        &[7, 3, 4, 1],
        &["a", "b", "c", "d", "e"],
        &["a", "e", "b", "d", "c"],
    ),
    (
        "reject-in-shuffle",
        &[0, 2, 0],
        &["a", "b", "c"],
        &["b", "a", "c"],
    ),
    ("duplicates", &[1, 1], &["x", "x", "y"], &["x", "y", "x"]),
    (
        "non-ascii",
        &[4294967295, 4294967294, 0],
        &["é", "日本", "🙂", "a"],
        &["日本", "é", "🙂", "a"],
    ),
];

/// Returns a word source that gives `words` in order and counts the words it gave.
fn fake_words(
    words: &[u32],
) -> (
    impl FnMut() -> u32 + '_,
    std::rc::Rc<std::cell::Cell<usize>>,
) {
    let used = std::rc::Rc::new(std::cell::Cell::new(0));
    let counter = used.clone();
    let source = move || {
        let w = words[counter.get()];
        counter.set(counter.get() + 1);
        w
    };
    (source, used)
}

#[test]
fn int_in_range_cases() {
    for &(name, words, lo, hi, count, want) in RANGE_CASES {
        let (mut source, used) = fake_words(words);
        let got: Vec<i64> = (0..count)
            .map(|_| int_in_range(&mut source, lo, hi))
            .collect();
        assert_eq!(got, want, "{name}");
        assert_eq!(used.get(), words.len(), "{name}");
    }
}

#[test]
fn shuffle_cases() {
    for &(name, words, items, want) in SHUFFLE_CASES {
        let (mut source, used) = fake_words(words);
        let mut got = items.to_vec();
        shuffle(&mut source, &mut got);
        assert_eq!(got, want, "{name}");
        assert_eq!(used.get(), words.len(), "{name}");
    }
}

#[test]
fn bad_range_panics() {
    for (lo, hi) in [(1, 0), (0, 1 << 32), (i64::MIN, i64::MAX)] {
        let result = std::panic::catch_unwind(|| int_in_range(&mut || 0, lo, hi));
        assert!(result.is_err(), "{lo} {hi}");
    }
}

#[test]
fn splitmix64_matches_the_reference_code() {
    let mut source = seeded_words(42);
    let got: Vec<u32> = (0..5).map(|_| source()).collect();
    assert_eq!(
        got,
        [3184996902, 686809907, 1196582743, 1478287871, 163338330]
    );
}

#[test]
fn same_seed_same_words() {
    let (mut a, mut b, mut c) = (seeded_words(7), seeded_words(7), seeded_words(8));
    let first: Vec<u32> = (0..10).map(|_| a()).collect();
    assert_eq!(first, (0..10).map(|_| b()).collect::<Vec<_>>());
    assert_ne!(first, (0..10).map(|_| c()).collect::<Vec<_>>());
}

#[test]
fn secure_words_in_range() {
    let mut source = secure_words().expect("open /dev/urandom");
    for _ in 0..100 {
        assert!((1..=6).contains(&int_in_range(&mut source, 1, 6)));
    }
}

#[test]
fn token_hex_has_the_right_digits() {
    for n in [0, 1, 16, 32] {
        let token = token_hex(n).expect("read /dev/urandom");
        assert_eq!(token.len(), 2 * n);
        assert!(
            token
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        );
    }
    assert_ne!(token_hex(16).unwrap(), token_hex(16).unwrap());
}
random_numbers.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/generate-random-numbers/.
#
# Random integers in a range, a shuffle, a seeded generator and tokens.
# A word source is a function that sets REPLY to an integer from 0 to
# 2^32 - 1. It runs in the current shell, not in a subshell, so that it can
# keep its state in variables.

# int_in_range SOURCE LO HI: set REPLY to an integer from LO to HI, each with
# equal probability. A word below 2^32 % n is rejected, so that each remainder
# comes from the same number of words. Return 1 if HI < LO or the range has
# more than 2^32 values.
int_in_range() {
    local source=$1 lo=$2 hi=$3 n least
    # hi - lo can overflow, so compare hi with lo + 2^32 - 1 only where that
    # sum fits; above that point, no range can have more than 2^32 values.
    if ((hi < lo)) || { ((lo <= 9223372036854775807 - 4294967295)) && ((hi > lo + 4294967295)); }; then
        echo "int_in_range: need lo <= hi and at most 2^32 values" >&2
        return 1
    fi
    n=$((hi - lo + 1))
    least=$((4294967296 % n))
    while :; do
        "$source" || return 1
        if ((REPLY >= least)); then
            REPLY=$((lo + REPLY % n))
            return 0
        fi
    done
}

# shuffle_array SOURCE NAME: shuffle the indexed array NAME in place with the
# Fisher-Yates method. NAME must not be one of the local names of this
# function, because a name reference to a local of the same name is circular.
shuffle_array() {
    local source=$1 i j tmp
    local -n shuffle_array_items=$2
    for ((i = ${#shuffle_array_items[@]} - 1; i > 0; i--)); do
        int_in_range "$source" 0 "$i" || return 1
        j=$REPLY
        tmp=${shuffle_array_items[i]}
        shuffle_array_items[i]=${shuffle_array_items[j]}
        shuffle_array_items[j]=$tmp
    done
}

# seed_words SEED: seed RANDOM, so that seeded_word gives the same words for
# the same seed.
seed_words() {
    RANDOM=$1
}

# seeded_word: a word source. RANDOM gives 15 bits, so a word takes the bits
# of three values: 15 + 15 + 2.
seeded_word() {
    REPLY=$(((RANDOM << 17) | (RANDOM << 2) | (RANDOM & 3)))
}

# secure_word: a word source that reads 4 bytes from /dev/urandom.
secure_word() {
    local w
    w=$(od -An -N4 -tu4 /dev/urandom) || return 1
    REPLY=$((w))
}

# token_hex NBYTES: print NBYTES bytes from /dev/urandom as 2 * NBYTES
# lowercase hexadecimal digits.
token_hex() {
    local out
    if (($1 > 0)); then
        out=$(od -An -v -N"$1" -tx1 /dev/urandom) || return 1
    fi
    out=${out//[[:space:]]/}
    printf '%s\n' "$out"
}
test_random_numbers.bats 109 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/generate-random-numbers/.

setup() {
    source "$BATS_TEST_DIRNAME/random_numbers.sh"
}

# fake_word: a word source that gives the words in FAKE in order.
fake_word() {
    ((next < ${#FAKE[@]})) || return 1
    REPLY=${FAKE[next]}
    next=$((next + 1))
}

# ints_in_range "WORDS" LO HI COUNT: print COUNT results, and fail if a word is
# left.
ints_in_range() {
    local -a out=()
    local k
    read -ra FAKE <<<"$1"
    next=0
    for ((k = 0; k < $4; k++)); do
        int_in_range fake_word "$2" "$3" || return 1
        out+=("$REPLY")
    done
    ((next == ${#FAKE[@]})) || return 1
    echo "${out[*]}"
}

# shuffle_items "WORDS" ITEM...: print the shuffled items, one on each line.
shuffle_items() {
    read -ra FAKE <<<"$1"
    shift
    next=0
    local -a items=("$@")
    shuffle_array fake_word items || return 1
    ((next == ${#FAKE[@]})) || return 1
    if ((${#items[@]} > 0)); then
        printf '%s\n' "${items[@]}"
    fi
}

@test "coin" { run ints_in_range "5 2 7" 0 1 3; [ "$status" -eq 0 ]; [ "$output" = "1 0 1" ]; }
@test "no-results" { run ints_in_range "" 1 6 0; [ "$status" -eq 0 ]; [ "$output" = "" ]; }
@test "die" { run ints_in_range "7 12 1000000 4294967295" 1 6 4; [ "$status" -eq 0 ]; [ "$output" = "2 1 5 4" ]; }
@test "negative-range" { run ints_in_range "100 2000000000 4294967294" -10 10 3; [ "$status" -eq 0 ]; [ "$output" = "6 -5 -8" ]; }
@test "one-value" { run ints_in_range "0 99" 5 5 2; [ "$status" -eq 0 ]; [ "$output" = "5 5" ]; }
@test "reject-low-words" { run ints_in_range "0 3 4" 1 6 1; [ "$status" -eq 0 ]; [ "$output" = "5" ]; }
@test "accept-least" { run ints_in_range "3 4 9" 0 5 2; [ "$status" -eq 0 ]; [ "$output" = "4 3" ]; }
@test "power-of-two" { run ints_in_range "0 4294967295" 0 7 2; [ "$status" -eq 0 ]; [ "$output" = "0 7" ]; }
@test "worst-case" { run ints_in_range "2147483646 2147483647" 0 2147483648 1; [ "$status" -eq 0 ]; [ "$output" = "2147483647" ]; }
@test "full-unsigned-32" { run ints_in_range "0 4294967295 123456789" 0 4294967295 3; [ "$status" -eq 0 ]; [ "$output" = "0 4294967295 123456789" ]; }
@test "full-signed-32" { run ints_in_range "0 2147483648 4294967295" -2147483648 2147483647 3; [ "$status" -eq 0 ]; [ "$output" = "-2147483648 0 2147483647" ]; }
@test "near-int64-max" { run ints_in_range "4294967295 6" 9223372036854775798 9223372036854775807 2; [ "$status" -eq 0 ]; [ "$output" = "9223372036854775803 9223372036854775804" ]; }
@test "near-int64-min" { run ints_in_range "4294967295 9" -9223372036854775808 -9223372036854775799 2; [ "$status" -eq 0 ]; [ "$output" = "-9223372036854775803 -9223372036854775799" ]; }
@test "wide-int64" { run ints_in_range "4294967295 0" 9223372032559808512 9223372036854775807 2; [ "$status" -eq 0 ]; [ "$output" = "9223372036854775807 9223372032559808512" ]; }

@test "shuffle empty" { run shuffle_items ""; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n')" ]; }
@test "shuffle one-item" { run shuffle_items "" "a"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "a")" ]; }
@test "shuffle two-items-swap" { run shuffle_items "0" "a" "b"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "b" "a")" ]; }
@test "shuffle two-items-keep" { run shuffle_items "1" "a" "b"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "a" "b")" ]; }
@test "shuffle five-items" { run shuffle_items "7 3 4 1" "a" "b" "c" "d" "e"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "a" "e" "b" "d" "c")" ]; }
@test "shuffle reject-in-shuffle" { run shuffle_items "0 2 0" "a" "b" "c"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "b" "a" "c")" ]; }
@test "shuffle duplicates" { run shuffle_items "1 1" "x" "x" "y"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "x" "y" "x")" ]; }
@test "shuffle non-ascii" { run shuffle_items "4294967295 4294967294 0" "é" "日本" "🙂" "a"; [ "$status" -eq 0 ]; [ "$output" = "$(printf '%s\n' "日本" "é" "🙂" "a")" ]; }

@test "bad ranges" {
    run int_in_range secure_word 1 0
    [ "$status" -eq 1 ]
    run int_in_range secure_word 0 4294967296
    [ "$status" -eq 1 ]
    run int_in_range secure_word -9223372036854775808 9223372036854775807
    [ "$status" -eq 1 ]
}

@test "the same seed gives the same words" {
    local a b c k
    seed_words 42
    for ((k = 0; k < 10; k++)); do seeded_word; a+=" $REPLY"; done
    seed_words 42
    for ((k = 0; k < 10; k++)); do seeded_word; b+=" $REPLY"; done
    seed_words 43
    for ((k = 0; k < 10; k++)); do seeded_word; c+=" $REPLY"; done
    [ "$a" = "$b" ]
    [ "$a" != "$c" ]
    for w in $a; do ((w >= 0 && w <= 4294967295)); done
}

@test "secure words give values in range" {
    local k
    for ((k = 0; k < 20; k++)); do
        int_in_range secure_word 1 6
        ((REPLY >= 1 && REPLY <= 6))
    done
}

@test "token_hex gives 2n lowercase hexadecimal digits" {
    for n in 0 1 16 32; do
        run token_hex "$n"
        [ "$status" -eq 0 ]
        [[ "$output" =~ ^[0-9a-f]*$ ]]
        [ "${#output}" -eq $((2 * n)) ]
    done
}

@test "tokens differ" {
    [ "$(token_hex 16)" != "$(token_hex 16)" ]
}

References

  1. The Python Standard Library, random, the warning at the top; random.getrandbits, random.randint, random.shuffle; Notes on Reproducibility
  2. The Python Standard Library, secrets, secrets.randbits, secrets.token_hex
  3. MDN Web Docs, Math.random(), Description, the note on security
  4. Node.js documentation, Crypto, crypto.getRandomValues(typedArray); crypto.randomBytes(size[, callback]); crypto.randomInt([min, ]max[, callback])
  5. Java SE 25 API, java.util.Random, class description; nextInt(int bound)
  6. Java SE 25 API, java.security.SecureRandom, class description
  7. Java SE 25 API, java.util.HexFormat, of()
  8. Java SE 25 API, java.util.Collections, shuffle(List, Random)
  9. Java SE 25 API, java.lang.Math, abs(int)
  10. .NET API reference, Random, Notes to Callers
  11. .NET API reference, Random.Shuffle, Shuffle<T>(IList<T>)
  12. .NET API reference, RandomNumberGenerator.GetHexString, GetHexString(Int32, Boolean)
  13. Go standard library, math/rand/v2, Overview; func IntN; func Shuffle; func NewPCG
  14. Go standard library, crypto/rand, func Read; func Text
  15. The Rust Standard Library, std::random, the banner at the top of the module
  16. The Open Group Base Specifications Issue 8, getentropy, SYNOPSIS; DESCRIPTION; ERRORS
  17. cppreference.com, rand, the description; Notes
  18. cppreference.com, std::random_device, the description of the class
  19. cppreference.com, std::mersenne_twister_engine, Predefined specializations
  20. cppreference.com, std::random_shuffle, std::shuffle, the description of overload (3)
  21. GNU Bash Reference Manual, 5.2 Bash Variables: RANDOM, SRANDOM
  22. Linux manual page, random(4), DESCRIPTION
  23. OpenBSD libc, arc4random_uniform.c, the comment and the body of arc4random_uniform
  24. Sebastiano Vigna, splitmix64.c, the comment at the top; next()

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.