Last active
August 29, 2015 14:19
-
-
Save Alex1990/f181d458e473ddf6d135 to your computer and use it in GitHub Desktop.
Pick N elements from an array randomly.
This file contains hidden or 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
| /** | |
| * Pick N elements from an array randomly. | |
| */ | |
| function randPick(arr, n) { | |
| var len = arr.length; | |
| var randIdx; | |
| var tmp; | |
| while (n--) { | |
| randIdx = Math.floor(Math.random() * len); | |
| tmp = arr[len - 1]; | |
| arr[len - 1] = arr[randIdx]; | |
| arr[randIdx] = tmp; | |
| len--; | |
| } | |
| return arr.slice(len - arr.length); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment