JS calculates the probability of winning based on the prize weight

JS calculates the probability of winning based on the prize weight

1. Example scenario

1.1. Set the prize name for the lucky draw

Award names: ["First Prize", "Second Prize", "Third Prize", "No Prize"]. Assume that the sweepstakes event sets up these four prizes, of course the developer can expand it to more.

var prizes = ["First Prize","Second Prize","Third Prize","No Prize"]; //Award name array

1.2. Set the weight of each award

Award weights: [1, 5, 20, 74]. Prize weights are mainly used to represent the probability of winning each prize. Here, the sum of the prize weight array is 100 (=1+5+20+74), where 1 means the probability of winning the first prize is 1%; 5 means the probability of winning the first prize is 5%; 20 means the probability of winning the third prize is 20%; and the remaining 74 means the probability of not winning is 74%.

var prizeWeight = [1, 5, 20, 74]; // Prize weight array, representing the percentage of the chance of winning each prize in the total. For example, the winning rate of the first prize is 1%, and the winning rate of the second prize is 5%.

If there are more prizes set for the lottery, the developer can also expand the sum of the weight array accordingly, for example, the sum of the weights is 500, 1000, etc., and set the array elements accordingly to represent how many times and what level of prizes can be won in every 500 draws.

In addition, developers can also declare the award name and award weight array together in one object:

//Set the award name, weight, etc. array var prizes = [
    {"name": "First Prize", "weight": 1}, 
    {"name": "Second Prize", "weight": 5}, 
    {"name": "Third Prize", "weight": 20}, 
    {"name": "Not Winning", "weight": 74}
];

1.3. Lucky Draw Rules

  • 0 < the random number of this lottery <= 1, indicating that the first prize is won;
  • 1 < the random number of this lottery <= 5, which means you win the second prize;
  • 5 < the random number of this lottery <= 20, which means you win the third prize;
  • The random number for this draw > 20, which means no winner.

2. Implementation Principle

Because this article is a simple implementation, the principle of this lottery program is also designed to be relatively simple:

  • According to the sum of the weight array (weightSum), a weight random number (weightRandom) is generated at each draw. This weight random number (weightRandom) is between 0-weightSum (weight sum value). The weight array sum value set in this example is 100, which means that the generated weight random number is between 0-100;
  • Then let this weighted random number (weightRandom) be compared with all the element values ​​in the weight array to calculate which two prizes this weighted random number (weightRandom) is between, which winning rule it meets, and which prize name it corresponds to.

For example, the weighted random number (weightRandom) generated in a certain lottery is 15.15. According to the activity rules in 1.3, because 5 <15.15<= 20, it means that the weighted random number (weightRandom) generated this time can win the third prize.

Let’s implement them separately:

2.1. Calculate weights and values

//Array cumulative sum function: Array.reduce(function(prev ,cuurentValue), initialValue)
var weightSum = prizeWeight.reduce(function(prev, currVal){ //Calculate the sum of weights: 1+5+20+74=100
    return prev + currVal; //prev is the value after the previous accumulation, currVal is the value to be added this time}, 0);

2.2. Write a lottery function

Generate a random weight value between 0 and weightSum based on the weight and value weightSum

//Lottery function var lottery = function(weightSum) {
    var res = "Not Winning"; //The default setting for the lottery result is "Not Winning"
    console.log("Award weight and value of this program:", weightSum);
    
    //Generate a random weight number between 0-weightSumvar random = Math.random()*weightSum; //Generate a random weight number (between 0 and weightSum)
    console.log("The random weight of this draw:", random);
    
    //Reorganize and sort the weight array var concatWeightArr = prizeWeight.concat(random); //Add random numbers to the weight array var sortedWeightArr = concatWeightArr.sort(function(a, b){return ab;}); //Sort the new weight array containing random numbers from small to large (ascending order) console.log("The new weight array containing random numbers is sorted in ascending order:", sortedWeightArr);
    
    //Array index of the weighted random number var randomIndex = sortedWeightArr.indexOf(random); //The position of the indexed random number in the new weight array randomIndex = Math.min(randomIndex, prizes.length -1); //The index of the weighted random number must not exceed the length of the prize array - 1, recalculate the index position of the random number in the prize array console.log("Array index corresponding to this weighted random number:", randomIndex);
    
    //Get the corresponding prize res = prizes[randomIndex]; //Get the result of this lottery from the prize array console.log("The result of this lottery:", res);
    
    return {"weightSum": weightSum , "weightRandom": random, prizeIndex: randomIndex, "data": res}; //Return the result of this lottery};

It should be noted that:

(1) In the lottery function, first generate a random weight number (random), then merge this random weight number (random) with the original weight array (using the Array.concat() function, the return value is a new array, the original weight array remains unchanged), generate a new weight array, and sort the new weight array from small to large (ascending order) (using the Array.sort() function); in this way, the random weight number (random) will fall between two prize weight values ​​in order of size. Finally, by indexing the random weight number (random) in the new weight array, you can retrieve the corresponding element in the award name array.

(2) For example, the random weight number generated by a lottery function is 15.15. When it is merged with the original weight array [1, 5, 20, 74] and sorted, a new weight array [1, 5, 15.15, 20, 74] is obtained. The random weight number (15.15) falls between 5 and 20. The subscript of the random weight number (15.15) in the new weight array is 2. The corresponding element of the prize name array with subscript 2 is taken out: prizes[2] = "third prize". From this, it can be judged that the third prize can be won in this lottery.

(3) In the lottery function, in order to determine which prize the size of the weighted random number (random) corresponds to, that is, to compare the size of the weighted random number with the value of each element in the weight array, the editor did not use the traditional for loop to traverse and compare the size of the weighted random number (random) and each element in the prizeWeight array. Instead, the editor merged and generated a new weight array and sorted it, and then used the Array.indexOf() function to index the subscript of the weighted random number (random), and the prize name corresponding to this subscript was retrieved.

3. Complete project code

The core code of this sample project js is as follows:

//layui modular reference layui.use(['jquery', 'util'], function(){
    var $ = layui.$, util = layui.util;
    
    //Set arrays for prize name, weight, number of wins, etc. var prizes = ["First Prize", "Second Prize", "Third Prize", "No Winner"]; //Award name array var prizeWeight = [1, 5, 20, 74]; //Prize weight array, representing the percentage of the chance of winning each prize in the total. For example, the winning rate of the first prize is 1%, and the winning rate of the second prize is 5%.            
    
    // Developers can also declare award names, weights, and other arrays in one object // var prizes = [
    // {"name": "First Prize", "weight": 1}, 
    // {"name": "Second Prize", "weight": 5}, 
    // {"name": "Third Prize", "weight": 20}, 
    // {"name": "Not winning", "weight": 74}
    //];                
    
    //Array cumulative sum function: Array.reduce(function(prev ,cuurentValue), initialValue)
    var weightSum = prizeWeight.reduce(function(prev, currVal){ //Calculate the sum of weights: 1+5+20+74=100
        return prev + currVal; //prev is the value after the previous accumulation, currVal is the value to be added this time}, 0);
    document.getElementById("weightSum").innerhtml = weightSum; //Set weight and value //Lottery function var lottery = function(weightSum) {
        var res = "Not Winning"; //The default setting for the lottery result is "Not Winning"
        console.log("Award weight and value of this program:", weightSum);
        
        //Generate a random weight number between 0-weightSumvar random = Math.random()*weightSum; //Generate a random weight number (between 0 and weightSum)
        console.log("The random weight of this draw:", random);
        
        //Reorganize and sort the weight array var concatWeightArr = prizeWeight.concat(random); //Add random numbers to the weight array var sortedWeightArr = concatWeightArr.sort(function(a, b){return ab;}); //Sort the new weight array containing random numbers from small to large (ascending order) console.log("The new weight array containing random numbers is sorted in ascending order:", sortedWeightArr);
        
        //Array index of the weighted random number var randomIndex = sortedWeightArr.indexOf(random); //The position of the indexed random number in the new weight array randomIndex = Math.min(randomIndex, prizes.length -1); //The index of the weighted random number must not exceed the length of the prize array - 1, recalculate the index position of the random number in the prize array console.log("Array index corresponding to this weighted random number:", randomIndex);
        
        //Get the corresponding prize res = prizes[randomIndex]; //Get the result of this lottery from the prize array console.log("The result of this lottery:", res);
        
        return {"weightSum": weightSum , "weightRandom": random, prizeIndex: randomIndex, "data": res}; //Return the result of this lottery};

    //Register button event $('.layui-btn[data-type="save"]').on('click', function () {
        var res = lottery(weightSum);
        document.getElementById("dateNow").innerhtml = util.toDateString(new Date()); //Output the time of this lottery document.getElementById("weightRandom").innerHTML = res.weightRandom; //Output the weighted random number of this lottery document.getElementById("printData").innerHTML = res.data; //Output the result of this lottery //Reset the font color of the winning rules text $('.rule-body>p').css("color", "inherit");
        $('.rule-body>p:eq(' + res.prizeIndex + ')').css("color", "red");
    });
});

The above is the details of how JS calculates the probability of winning based on the prize weight. For more information about JS calculating the probability of winning, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • jquery.rotate.js implements the lottery code of the turntable with optional lottery number and winning content
  • js control random number generation probability code example
  • js realizes the generation of 1,2,3,5 numbers according to probability
  • js array to achieve weight probability distribution
  • js probability calculation (simple version)
  • Detailed explanation of JavaScript randomly generating events by probability
  • JavaScript to achieve random lottery function
  • js to realize the lottery function
  • Native JS realizes the nine-square lottery
  • js to achieve simple lottery function

<<:  Zabbix's psk encryption combined with zabbix_get value

>>:  How to install MySQL 5.7 from source code in CentOS 7 environment

Recommend

How to implement real-time polygon refraction with threejs

Table of contents Preface Step 1: Setup and front...

Solution to no Chinese input method in Ubuntu

There is no solution for Chinese input method und...

Basic principles for compiling a website homepage

1. The organizational structure of the hypertext d...

Basic knowledge of MySQL database

Table of contents 1. Understanding Databases 1.1 ...

MySql login password forgotten and password forgotten solution

Method 1: MySQL provides a command line parameter...

Teach you how to write maintainable JS code

Table of contents What is maintainable code? Code...

MySQL5.7 single instance self-starting service configuration process

1.MySQL version [root@clq system]# mysql -v Welco...

How to use mqtt in uniapp project

Table of contents 1. Reference plugins in the uni...

How to use the Clipboard API in JS

Table of contents 1. Document.execCommand() metho...

Summary of solutions for MySQL not supporting group by

I downloaded and installed the latest version of ...

Detailed tutorial on installing Docker on CentOS 7.5

Introduction to Docker Docker is an open source c...

Summary of commonly used multi-table modification statements in Mysql and Oracle

I saw this question in the SQL training question ...

Summary of MySQL InnoDB locks

Table of contents 1. Shared and Exclusive Locks 2...