The source array to sample from
The number of elements to sample
An array containing the randomly selected elements
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
RandomGenerator.sample(numbers, 3); // e.g. [2, 7, 9]
RandomGenerator.sample(numbers, 5); // e.g. [1, 4, 6, 8, 10]
RandomGenerator.sample(numbers, 15); // returns all 10 elements (capped at array length)
// Sample users for testing
const allUsers = await getUsersFromDatabase();
const testUsers = RandomGenerator.sample(allUsers, 10);
// Create random product selections
const featuredProducts = RandomGenerator.sample(allProducts, 5);
// Generate test data subsets
const validationSet = RandomGenerator.sample(trainingData, 100);
// Random A/B testing groups
const groupA = RandomGenerator.sample(allParticipants, 50);
const remaining = allParticipants.filter((p) => !groupA.includes(p));
const groupB = RandomGenerator.sample(remaining, 50);
contracts/common.md#principled-implementation A partial Fisher-Yates shuffle over a sparse map of moved positions draws each result element from the not-yet-chosen positions uniformly, so the sample is without replacement, approximately uniform under Math.random, and its cost grows with the sample size; the count is capped at the array length, a positive fractional count rounds upward through the loop condition, and a count that is zero, negative, or NaN yields an empty array.
contracts/common.md#clear-and-simple-design One loop with one map, and no rejection of repeated draws.
Randomly samples a specified number of positions from an array.
Selects input positions without replacement. Equal values at different positions remain separate candidates and can both appear in the result. The sample size is automatically capped at the array length to prevent errors. Uses a partial Fisher-Yates shuffle over a sparse index map, so every draw is final and the cost grows with the sample size, not with the array length. Ideal for creating test datasets or selecting random subsets for validation.
Processing cost: For K selected positions, sparse partial Fisher-Yates uses K map lookups/updates and K output entries: expected O(K) time and O(K) space, without copying the N-element input.