Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active January 17, 2024 07:28
Show Gist options
  • Save Phryxia/bff4ccecde26d303e48e9cf55339c676 to your computer and use it in GitHub Desktop.
Save Phryxia/bff4ccecde26d303e48e9cf55339c676 to your computer and use it in GitHub Desktop.
Extract samples without replacement using TypeScript.
/**
* 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
}
@Phryxia
Copy link
Author

Phryxia commented Jul 15, 2023

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