다음은 교체 여부에 관계없이 배열을 쉽게 샘플링 할 수있는 함수입니다.
const randomSample = (arr, k, withReplacement = false) => {
let sample;
if (withReplacement === true) {
sample = Array.from({length: k}, () => arr[Math.floor(Math.random() * arr.length)]);
} else {
if (k > arr.length) {
throw new RangeError('Sample size must be less than or equal to array length when sampling without replacement.')
}
sample = arr.map(a => [a, Math.random()]).sort((a, b) => {
return a[1] < b[1] ? -1 : 1;}).slice(0, k).map(a => a[0]);
};
return sample;
};
사용은 간단합니다.
대체하지 않음 (기본 동작)
randomSample([1, 2, 3], 2) 돌아올 수있다 [2, 1]
교체 포함
randomSample([1, 2, 3, 4, 5, 6], 4) 돌아올 수있다 [2, 3, 3, 2]