Explain how JavaScript generates events randomly based on probability, and explain the javascript Probability
Recently, a JavaScript event is generated randomly based on probability, So I sorted out my ideas and wrote a small demo:
/** This algorithm is often used in lottery activity. Different awards have different probability of acquisition. The corresponding prize should be randomly generated based on probability. **/function random (arr1, arr2) {var sum = 0, factor = 0, random = Math. random (); for (var I = arr2.length-1; I> = 0; I --) {sum + = arr2 [I]; // sum of statistical probabilities }; random * = sum; // generate a probability random number for (var I = arr2.length-1; I> = 0; I --) {factor + = arr2 [I]; if (random <= factor) return arr1 [I] ;}; return null ;}; // testvar a = ['mac', 'iphone ', 'vivo ', 'oppo ']; var B = [0.1, 0.2, 0.3, 0.4]; console. log (random (a, B ));
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.