Skip to content

Instantly share code, notes, and snippets.

@jca02266
Last active March 2, 2021 15:06
Show Gist options
  • Save jca02266/b3ef845fb0082cf8327db4fdc3752cb0 to your computer and use it in GitHub Desktop.
Save jca02266/b3ef845fb0082cf8327db4fdc3752cb0 to your computer and use it in GitHub Desktop.
// return random intger value: [min, max)
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
// return (size m) array picked from 0..<n (n >= m)
// Modified Fisher-Yates Shuffle (derived from <https://qiita.com/hmito/items/9f4bdc8442b6f6b3c7bc>)
function randomPick(n, m) {
let max = n;
const map = []
const ret = []
for (let i = 0; i < m; i++) {
let val = getRandomInt(0, max);
let maxval;
if (map[max-1] !== undefined) {
maxval = map[max-1];
} else if (val !== max-1) {
maxval = max-1;
}
if (map[val] !== undefined) {
ret[i] = map[val];
} else {
ret[i] = val;
}
map[val] = maxval;
max--;
}
return ret;
}
// sample
for (let i = 0; i < 10; i++) {
console.log(randomPick(5, 4));
}
const randomPick = (n: number, m: number): number[] => {
const arr: number[] = [];
for (let i = 0; i < m; i++) {
const max = n - 1 - i;
const picked = Math.floor(Math.random() * (max + 1));
[arr[picked], arr[max]] = [arr[max] ?? max + 1, arr[picked] ?? picked + 1];
}
return arr.slice(n - m, n);
}
for (let i = 0; i < 10; i++) {
console.log(randomPick(100000,5));
}
@jca02266
Copy link
Author

jca02266 commented Mar 2, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment