2015-02-12 77 views
0

我有一个简单的执行问题。 这里是我有的随机数函数,并且返回给定范围内的一个随机数。歪斜号码发生器

function randomNum(low, high){ 
    return Math.floor(Math.random() * (high - low + 1)) + low; 
    } 

不过,我想有越来越高数的50%的机会,并为一切25%..

例如:

randomNum(1, 3) 

'3' 将有有50%的几率得到命中,而'1'和'2'的命中率都将达到25%。 我不太确定我需要做些什么改变我的功能...提示将是伟大的,谢谢

+0

它一定是50%还是其他所有东西的两倍?例如randomNum(1,4)4的概率是50%,或者4的概率是40%? – jpriebe 2015-02-12 04:04:00

+0

@jpriebe是的,无论给出的范围如何,高数量的命中率都必须达到50%。 – user6623512 2015-02-12 04:06:06

+1

所以如果我做了'randomNum(1,6)',你希望有50%的几率得到6,而其他的都有10%的机会? – 2015-02-12 05:16:38

回答

0

如果其他条件 如果它是3它的好,否则,如果它不是3那么那么,再次在1和2之间做一个随机数; 因此,3将得到50%的机会,因为1,2将有25%的机会

+1

可能想检查你的逻辑/数学/统计数据。 – Fiddles 2015-02-12 04:24:14

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]; 
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; 
} 
3
function randomNum(low, high){ 
    return Math.random() > 0.5 ? 
    high : 
    Math.floor(Math.random() * (high - low)) + low; 
} 
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)); 
0

在这里你去。高会有50%的几率,其余的会平分其他50%

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 
    }