Home  >  Article  >  Web Front-end  >  An explanation of JavaScript's implementation of randomly generating events based on probability

An explanation of JavaScript's implementation of randomly generating events based on probability

巴扎黑
巴扎黑Original
2017-08-13 14:45:421309browse

This article mainly introduces a detailed explanation of JavaScript's random generation of events based on probability, which has certain reference value. Interested friends can refer to it

Recently made a JavaScript random generation of events based on probability, so I sorted out my thoughts and wrote a small demo:


/*
*在抽奖的活动中经常会用到这个算法,不同奖项的获取概率不同,要按概率去随机生成对应的奖品
*
*/
function random(arr1, arr2) {
  var sum = 0,
    factor = 0,
    random = Math.random();

  for(var i = arr2.length - 1; i >= 0; i--) {
    sum += arr2[i]; // 统计概率总和
  };
  random *= sum; // 生成概率随机数
  for(var i = arr2.length - 1; i >= 0; i--) {
    factor += arr2[i];
    if(random <= factor) 
     return arr1[i];
  };
  return null;
};

// test
var a = [&#39;mac&#39;, &#39;iphone&#39;, &#39;vivo&#39;, &#39;OPPO&#39;];
var b = [0.1, 0.2, 0.3, 0.4];
console.log(random(a, b));

The above is the detailed content of An explanation of JavaScript's implementation of randomly generating events based on probability. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn