Created
November 5, 2013 16:31
-
-
Save geckotang/7321751 to your computer and use it in GitHub Desktop.
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
| //@param items {Array} ランダムに抽出する対象の配列 | |
| //@param pickoutNum {Number} 抽出する個数 | |
| //@see http://d.hatena.ne.jp/miya2000/20080607/p0 | |
| function random(items, pickoutNum) { | |
| var tmp = {}; | |
| var result = []; | |
| var itemNum = items.length; | |
| pickoutNum = (pickoutNum < itemNum) ? pickoutNum : itemNum; | |
| while (pickoutNum-- > 0) { | |
| var i = Math.random() * itemNum | 0; | |
| result[pickoutNum] = tmp[i] || items[i]; | |
| --itemNum; | |
| tmp[i] = tmp[itemNum] || items[itemNum]; | |
| } | |
| return result; | |
| } | |
| console.log(random([0,1,2,3,4,5],2)); // 0~5 | |
| console.log(random([0],2)); // 0 | |
| console.log(random([0,5],2)); // 0,5 | |
| console.log(random([0,1,2,3],2)); // 0~3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment