Last active
August 29, 2015 14:20
-
-
Save yiting007/ec572a47784baad99667 to your computer and use it in GitHub Desktop.
Get a random subset of the set
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
var pool = ["1", "2", "3", "4", "5"] | |
var getRandomSubsets = function (num) { // num: #of elements in the subset | |
if (num.length > pool) { | |
return null; | |
} | |
var subPool = {}; | |
for (var i = 0; i < num; i++) { | |
var max = pool.length - 1; | |
var min = 0; | |
var pick = Math.floor(Math.random() * (max - min + 1)) + min; | |
if (pick in subPool) { | |
i--; | |
continue; | |
} | |
subPool[pick] = pool[pick]; | |
} | |
return subPool; | |
} | |
getRandomSubsets(3); | |
//eg: return Object {1: "2", 2: "3", 3: "4"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment