我有一个简单的实现问题。 这是我的随机数函数,并返回给定范围内的随机数。
function randomNum(low, high){
return Math.floor(Math.random() * (high - low + 1)) + low;
}
但是,我希望有50%的机会获得高数字,25%获得其他所有数据。
例如:
randomNum(1, 3)
' 3'将有50%的机会获得一个打击,而' 1'和' 2'两者的命中率都是25%。 我不太确定我需要对我的功能进行哪些更改...提示会很棒,谢谢
答案 0 :(得分:3)
function randomNum(low, high){
return Math.random() > 0.5 ?
high :
Math.floor(Math.random() * (high - low)) + low;
}
答案 1 :(得分:1)
以一般方式;我想你是在加权随机数生成器之后:
function weightedRandomNumber(weights) {
var sum = 0;
for (var w in weights) {
w = weights[w];
sum += w.weight;
}
var rand = Math.random() * sum;
for (var w in weights) {
w = weights[w];
if (rand < w.weight) {
return w.value;
}
rand -= w.weight;
}
return weights[weights.length - 1].value;
}
测试:
var config = [
{ weight: 25, value: 1 },
{ weight: 25, value: 2 },
{ weight: 50, value: 3 }
];
var test = { 1: 0, 2: 0, 3: 0 }, max = 10000;
for (var i = 1; i < max; i += 1) {
test[weightedRandomNumber(config).toString()] += 1;
}
alert('From ' + max + ' rounds; results: ' + JSON.stringify(test));
答案 2 :(得分:0)
制造if else条件 如果它是3则可以,否则如果它不是3则再次在1和2之间产生一个随机数; 因此,3将获得50%的机会,因为1,2将获得25%的机会
答案 3 :(得分:0)
您可以使用两种方法。 (1)你可以得到值的数组和随机的值索引。如果你想让某些数字有更高的机会,那么就把它放得更多。例如:
var arr = [1, 2, 3, 3];
return arr[Math.floor(Math.random() * arr.length)];
(2)第二种方法是array shuffling。
var arr[1, 2, 3, 3];
shuffle(arr);
return arr[0];
答案 4 :(得分:0)
这应该有效:
function randomNum(low, high){
var mid = (low + high)/2;
var randomn = Math.floor(Math.random() * (high - low + 1)) + low;
if(randomn > mid)
return randomn ;
else
return Math.floor(Math.random() * (high - low + 1)) + low;
}
答案 5 :(得分:0)
function randomNum(low, high)
{
var myarry = []
for(var i=0;i<(high-low);i++) { myarry.push(low+i) } ; //var myarry=[low, low+1, ....,high-1] excludes high
console.log(myarry)
var magic=Math.random();
var index=Math.round(magic*(high-low)); // Gaurantee the chance is split between the elements of the array
return Math.round(magic)==1?high:myarry[index] // Guaranteed 50% chance for high either 0 or 1, the rest will split the chance
}