Created
October 29, 2011 10:27
-
-
Save Takazudo/1324317 to your computer and use it in GitHub Desktop.
randomPick/randomNum
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
/* need underscore.js */ | |
/** | |
* randomNum | |
* randomNum(3,6); => 4 | |
*/ | |
var randomNum = function(from, to) { | |
return from + Math.floor( Math.random() * (to - from + 1) ); | |
}; | |
/** | |
* randomPick | |
* randomPick([1,2,3,4,5], 3); => [3,5,2] | |
*/ | |
var randomPick = function(array, length) { | |
if(array.length === 0){ | |
return []; | |
} | |
var temp = _.clone(array); | |
var ret = []; | |
var item; | |
for(var i=0, l=length; i<l; i++){ | |
item = temp[randomNum(0, temp.length-1)]; | |
ret.push(item); | |
temp = _.without(temp, item); | |
if(temp.length === 0){ | |
break; | |
} | |
} | |
return ret; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment