Home  >  Article  >  Web Front-end  >  js implements code sharing for generating numbers 1, 2, 3, and 5 according to probability

js implements code sharing for generating numbers 1, 2, 3, and 5 according to probability

小云云
小云云Original
2018-02-12 09:37:171929browse

This article mainly introduces js to realize the generation of numbers 1, 2, 3, and 5 according to probability. Friends who need it can refer to it. I hope it can help everyone.

js is generated according to the configured probability. The probability rules are as follows:
1------------50%

2----- -------30%

3----------------15%

5------------5 %

Simple code


function myRandom() {
 var rand = Math.random();
 if (rand < .5) return 1;
 if (rand < .8) return 2;
 if (rand < .95) return 3;
 return 5;
}

Complex code


function prizeRand(oArr) {
 var sum = 0; // 总和
 var rand = 0; // 每次循环产生的随机数
 var result = 0; // 返回的对象的key

 console.log(oArr);

 // 计算总和
 for (var i in oArr) {
  sum += oArr[i][0];
 }

 // 思路就是如果设置的数落在随机数内,则返回,否则减去本次的数
 for (var i in oArr) {
  rand = Math.floor(Math.random()*sum + 1);
  if (oArr[i][0] >= rand) {
   result = oArr[i][0];
   break;
  } else {
   sum -= oArr[i][0];
  }
 }

 return result;

}

var oArr = {&#39;5&#39;:[5, &#39;Mac&#39;], &#39;3&#39;:[15, &#39;iPhone&#39;], &#39;2&#39;:[30, &#39;iPad&#39;], &#39;1&#39;:[50, &#39;iWatch&#39;]};

console.log(prizeRand(oArr));

Related recommendations:

php implements lottery probability algorithm code

PHP probability calculation function

php implements lottery program winning probability Example of algorithm

The above is the detailed content of js implements code sharing for generating numbers 1, 2, 3, and 5 according to 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