Javascript随机网址重定向,赔率不同

时间:2019-06-24 09:51:00

标签: javascript

我有以下代码,这些代码会在页面加载时根据随机数(从提供的链接数中)重定向到不同的url。很好。

我想做的是控制每个链接被加载的几率。

更准确地说,我只希望第一个链接的“获胜”机会最小。

var links = [
  "flip1.html",
  "flip2.html",
  "flip3.html",
  "flip4.html",
  "flip5.html"
]
var openSite = function() {
  // get a random number between 0 and the number of links
  var randIdx = Math.random() * links.length;
  // round it, so it can be used as array index
  randIdx = parseInt(randIdx, 10);
  // construct the link to be opened
  var link = 'http://' + links[randIdx];

  var win = window.open(link, '_self');
  win.focus();

};
<body onload="javascript:openSite();" style="height: 100%; margin: 0px; padding:0px; ">

2 个答案:

答案 0 :(得分:1)

您可以为每个可能的选项分配权重。

然后,您可以根据权重的总和生成随机数,并查看随机命中的位置:

var links = [
  { url: "flip1.html", weight: 1 }, // 5%
  { url: "flip2.html", weight: 2 }, // 10%
  { url: "flip3.html", weight: 3 }, // 15%
  { url: "flip4.html", weight: 4 }, // 20%
  { url: "flip5.html", weight: 10 } // 50%
];

function weightedRandom(arr)
{
  var weightSum = arr.map(l => l.weight).reduce((a, b) => a + b, 0);
  var rand = Math.random() * weightSum;
  
  var accumulated = 0;
  for (var i = 0; i < arr.length; i++)
  {
    if (rand < accumulated + arr[i].weight)
    {
      return arr[i];
    }
    
    accumulated += arr[i].weight;
  }
}

function openSite() {
  var link = weightedRandom(links);
  
  // uncomment this and call openSite function:
  //var win = window.open(link.url, '_self');
  //win.focus();
}

function experiment()
{
  var testsCount = 10000;
  var counts = {};
  
  for (var i = 0; i < links.length; i++)
  {
    counts[links[i].url] = 0;
  }
  
  for (var i = 0; i < testsCount; i++)
  {
    var link = weightedRandom(links);
    counts[link.url]++;
  }
  
  console.log(counts);
}

experiment();

答案 1 :(得分:0)

您可以多次将相同链接添加到数组

例如: link1具有10%的机会,link2具有50%的机会,link3具有40%的机会

需要此机会的阵列:

var links = [
   'link1', // single link1
   'link2', // five times link2
   'link2',
   'link2',
   'link2',
   'link2',
   'link3', // four times link3
   'link3',
   'link3',
   'link3',
]

然后您可以随机排列数组并从中随机获取值

链接1的机会约为10%