An explanation of randomly generated events in JavaScript

巴扎黑
Release: 2017-08-06 14:30:09
Original
1398 people have browsed it

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 = ['mac', 'iphone', 'vivo', 'OPPO']; var b = [0.1, 0.2, 0.3, 0.4]; console.log(random(a, b));
Copy after login

The above is the detailed content of An explanation of randomly generated events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!