Created
January 19, 2016 02:23
-
-
Save dongnanyanhai/b4169c89b958b75ea3be 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
/*obj 概率对象数组; | |
luck 概率数组,即obj数组元素意义对应; | |
对于给定的概率对象,该函数可简化如下: | |
var a = ['一等奖:宝马X6', '二等奖:苹果三件套', '三等奖:威戈背包', '继续努力!']; | |
var b = [1, 10, 100, 500]; | |
function goodluck(a, b) { | |
var random = (1 + 10 + 100 + 500) * Math.random(); | |
if(random <= 500) return a[3]; | |
else if(random <= 600) return a[2]; | |
else if(random <= 610) return a[1]; | |
else return a[0]; | |
}; | |
console.log(goodluck(a, b)); | |
*/ | |
function goodluck(obj, luck) { | |
var sum = 0, | |
factor = 0, | |
random = Math.random(); | |
for(var i = luck.length - 1; i >= 0; i--) { | |
sum += luck[i]; // 统计概率总和 | |
}; | |
random *= sum; // 生成概率随机数 | |
for(var i = luck.length - 1; i >= 0; i--) { | |
factor += luck[i]; | |
if(random <= factor) return obj[i]; | |
}; | |
return null; | |
}; | |
/* test | |
var a = ['一等奖:宝马X6', '二等奖:苹果三件套', '三等奖:威戈背包', '继续努力!']; | |
var b = [100, 100, 100, 100]; | |
console.log(goodluck(a, b)); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment