Last active
January 17, 2024 07:28
-
-
Save Phryxia/bff4ccecde26d303e48e9cf55339c676 to your computer and use it in GitHub Desktop.
Extract samples without replacement using TypeScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extract n samples from list without replacement in O(|list|) | |
* @param {Object[]} list - array containing elements | |
* @param {number} n - size of the extraction | |
* @returns {Object[]} new array contains extracted elements | |
*/ | |
function getSamplesWithoutReplacement<T>(list: T[], n: number): T[] { | |
if (n <= 0) return [] | |
list = [...list] | |
if (n >= list.length) return list | |
for (let k = 0; k < n; ++k) { | |
const target = Math.floor(Math.random() * (list.length - k)) + k; | |
[list[k], list[target]] = [list[target], list[k]] | |
} | |
list.length = n | |
return list | |
} |
Also you can use this function for permutating list. It's special case of n = list.length
.
function permutateList<T>(list: T[]): T[] {
list = [...list];
for (let k = 0; k < list.length; ++k) {
const target = Math.floor(Math.random() * (list.length - k)) + k;
[list[k], list[target]] = [list[target], list[k]];
}
return list;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The method of sample extraction without replacement is not trivial. One may implement like below, but it may run redundant retrial depend on what is selected. Theoretically, there is a chance of inifinite loop (although that probability is almost 0).
My implementation guarantees a single loop.
Note that possibilities of every elements being selected are same, regardless of order of selections.
Proof