Last active
March 2, 2021 15:06
-
-
Save jca02266/b3ef845fb0082cf8327db4fdc3752cb0 to your computer and use it in GitHub Desktop.
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
// 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)); | |
} |
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
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See: https://twitter.com/aoki_taichi/status/1366196445787815942?s=20