Skip to content

Instantly share code, notes, and snippets.

@yiting007
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yiting007/ec572a47784baad99667 to your computer and use it in GitHub Desktop.
Save yiting007/ec572a47784baad99667 to your computer and use it in GitHub Desktop.
Get a random subset of the set
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