sample_with_replacement.js

/**
 * 有放回抽样是一种允许从总体中多次抽取同一项目的抽样方法。
 *
 * @param {Array<*>} x 任意类型的数组
 * @param {number} n 需要抽取的元素数量
 * @param {Function} [randomSource=Math.random] 一个可选的熵源,返回介于0(包含)和1(不包含)之间的数字:[0, 1)
 * @return {Array} 从总体中抽取的n个样本
 * @example
 * var values = [1, 2, 3, 4];
 * sampleWithReplacement(values, 2); // 返回2个随机值,例如 [2, 4];
 */
function sampleWithReplacement(x, n, randomSource) {
    if (x.length === 0) {
        return [];
    }

    // 如果需要使用固定种子或其他随机数生成器(如[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;