sampleWithReplacement
Returns a new array with a specified number of random elements, allowing duplicates (sampling with replacement).
1/**
2 * Returns a new array with a specified number of random elements,
3 * allowing duplicates (sampling with replacement).
4 *
5 * @param arr - The input array to sample from.
6 * @param count - The number of elements to sample.
7 * @returns A new array with randomly selected elements (duplicates allowed).
8 */
9export function sampleWithReplacement<T>(arr: T[], count: number): T[] {
10 const result: T[] = [];
11
12 for (let i = 0; i < count; i++) {
13 const index = Math.floor(Math.random() * arr.length);
14 result.push(arr[index]);
15 }
16
17 return result;
18}Supports duplicate values
Unlike standard sampling, this allows the same element to be selected multiple times
Simple and efficient
Uses direct indexing and a single loop, making it fast even for large arrays or high
countvalues.Non-mutating behavior
Leaves the original array unchanged, which ensures functional purity and avoids side effects.
Guaranteed result length
Always returns exactly
countelements, even if the original array is smaller.
Tests | Examples
1test('sampleWithReplacement returns correct count', () => {
2 const result = sampleWithReplacement([1, 2, 3], 5);
3 expect(result.length).toBe(5);
4});
5
6test('sampleWithReplacement allows duplicates', () => {
7 const input = ['a'];
8 const result = sampleWithReplacement(input, 3);
9 expect(result).toEqual(['a', 'a', 'a']);
10});
11
12test('sampleWithReplacement does not include elements outside the input', () => {
13 const input = [10, 20, 30];
14 const result = sampleWithReplacement(input, 100);
15 result.forEach(val => expect(input).toContain(val));
16});Common Use Cases
Statistical simulations
Sampling with replacement is foundational in Monte Carlo methods, bootstrapping, and other probabilistic algorithms.
Game logic / randomized outcomes
Useful for loot tables, randomized encounters, or drawing from a pool where repetition is allowed (e.g. pulling cards with reshuffle).
UI demo / load testing
When mocking UI states or repeating randomized selections for tests.
Educational / probabilistic modeling
Helps demonstrate probability concepts where the same outcome may occur more than once (e.g. rolling dice, spinning a wheel).