带比率的随机数

Random numbers with ratio

本文关键字:随机数 比率      更新时间:2023-09-26

我想用自定义宽度随机化我的列表。为此,我编写了简单的JavaScript片段,在1 and 2之间生成数字。

功能如下:

randomizePortfolio: function() {
    $('ul.works').children('li').each(function() {
        var Random = Math.floor(Math.random() * 2) + 1,
            words = 'normal';
        if(Random == '2') {
            words = 'wide';
        }
        $(this).addClass('col-md-'+3*Random+' col-sm-'+3*Random+' '+words);
    });
    $('ul.works').masonry({
        itemSelector: 'li'
    });
}

问题是,我想为1提供更大的比率。现在它 - 不知不觉 - 随机,所以有时我得到所有的2,其他时间 - 所有1的。我怎样才能为此添加比率(假设 3:1)?

要获得 3:1 分布,您可以使用所需的数字创建一个数组,并添加三个 1 和一个 2,然后随机化索引:

var rvalues = [1,1,1,2];
var Random = rvalues[Math.floor(Math.random() * rvalues.length)];

这是另一种等效的方法,该方法基于随机值小于 3/4 的时间 3/4 的事实:

var Random:
if (Math.random() < .75) Random = 1;
else Random = 2;

正在使用的另一种方式,可以为您服务:

// here's the value we wanna get by ratio (where v is value and r is ratio)
// r is an array with min and max value, this example is based on a 100% ratio
const ratioValues = [
  {v: 1, r: [0,75]}, // 75% chance to get 1
  {v: 2, r: [76,100]} // 25% chance to get 2
];
//actual function to get our value
function getRandByRatio(ratioValues) {
  // idx is a random integer between 0 and 100
  let idx = Math.floor(Math.random() * (100 + 1));
  for (let item of ratioValues) {
    // test if idx is within the r range
    if (idx >= item.r[0] && idx <= item.r[1]) {
      //if it is return our value
      return item.v;
    }
  }
};
// let's make a testing function
function makeTest(nb) {
  const ul = document.getElementById("rand-value");
  for (let i = 0; i < nb; i++) {
    ul.innerHTML += "<li>" + getRandByRatio(ratioValues) + "</li>";
  }
};
makeTest(10);
<ul id="rand-value"></ul>

虽然只有 2 个值可能有很多代码,但我发现它更具可读性且更易于维护。(当你有更多的价值时,这很棒!!)

希望这对某人有用!! :)