-
Notifications
You must be signed in to change notification settings - Fork 224
/
sample_with_replacement.js
36 lines (30 loc) · 1.14 KB
/
sample_with_replacement.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* Sampling with replacement is a type of sampling that allows the same
* item to be picked out of a population more than once.
*
* @param {Array<*>} x an array of any kind of value
* @param {number} n count of how many elements to take
* @param {Function} [randomSource=Math.random] an optional entropy source that
* returns numbers between 0 inclusive and 1 exclusive: the range [0, 1)
* @return {Array} n sampled items from the population
* @example
* var values = [1, 2, 3, 4];
* sampleWithReplacement(values, 2); // returns 2 random values, like [2, 4];
*/
function sampleWithReplacement(x, n, randomSource) {
if (x.length === 0) {
return [];
}
// a custom random number source can be provided if you want to use
// a fixed seed or another random number generator, like
// [random-js](https://www.npmjs.org/package/random-js)
randomSource = randomSource || Math.random;
const length = x.length;
const sample = [];
for (let i = 0; i < n; i++) {
const index = Math.floor(randomSource() * length);
sample.push(x[index]);
}
return sample;
}
export default sampleWithReplacement;