js implements the algorithm for specifying the order and amount of red envelopes

js implements the algorithm for specifying the order and amount of red envelopes

This article shares the specific code of js to implement the specified red envelope order and amount for your reference. The specific content is as follows

Preface

  • Written at the request of a friend
  • The minimum amount for a single package is 0.01
  • If all other values ​​except the specified amount are 0.01 , the probability of the last package being 0 is
  • This algorithm has passed 1,000,000 tests with an error rate of 3 per million

Effect display

Empty package problem

Red Envelope Algorithm

/*
    param: float, int, int, float
    param1: total amount of red envelopes param2: number of red envelopes param3: specify special red envelopes param4: specify special red envelope amount*/
let getPrize = function(total, number, index, volume){
    let allowance = total - volume;

    let arr = [];
    let i = 0;
    while(i < number - 2){
        //Specify [0.01, allowance-(i*0.01))
        let temp = (Math.random()*(allowance - (number - 1 - i) * 0.01) + 0.01).toFixed(2);
        // if (temp < 0) console.log(`temp:${temp}`);
        temp = temp <= 0 ? 0.01 : temp;        
        arr.push(parseFloat(temp));
        allowance = parseFloat((allowance - temp).toFixed(2));        
        i++;
        // console.log(`arr:${arr}, i:${i}`);
        // If the distribution is less than 0, exploit the strong and divide it equally if(allowance <= 0){
            // console.log(`alowance:${allowance}`);
            
            
            let w = arr.filter((val,index)=>{
                // console.log(`val:${val}`);
                if(val > 0.01){
                    
                    arr[index] = parseFloat((arr[index] - 0.01).toFixed(2));
                    return val;
                }
            });

            if(w.length == 0){
                allowance = 0;
            }else{
                allowance = 0.01;
            }
            
        }
    }
    // The last one is put in arr.push(parseFloat(allowance.toFixed(2)));
    let result = arr;

    return result.slice(0, index).concat(parseFloat(volume), result.slice(index));
}

Test Examples

// Test sample
for(let m = 0; m < 10000; m++){
    let total = (Math.random()*100 + 0.01).toFixed(2);

    let number = Math.floor(Math.random()*20 +2);
    while(total / number < 0.01){
        number = Math.floor(Math.random()*20 +2);
    }

    let index = Math.floor(Math.random()*(number - 1));

    let volume = (Math.random()*(total - 0.01*(number-1))+0.01).toFixed(2);
    while(volume >= total || volume + 0.01*(number-1) > total){
        // console.log(`xx:${volume}`);
        volume = (Math.random()*(total - 0.01*(number-1))+0.01).toFixed(2);
        volume = volume <= 0 ? 0.01 : volume;
    }
    
    
    let test = getPrize(total, number, index, volume);
    // console.log(test);
    let sum = test.reduce((total,val)=>total+=parseFloat(val));
    sum = sum.toFixed(2);
    if(sum !== total) {
        console.log(`volume:${volume}, total: ${total}, number: ${number}`);
        console.log(`sum:${sum}`);
        console.log(test);
    }
    test.map((val,index)=>{
        if(val <= 0 && index !== test.length - 1){
            console.log(`volume:${volume}, total: ${total}, number: ${number}`);
            console.log(`sum:${sum}`);
            console.log(test);
        }
    });

}

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Using JS to implement binary tree traversal algorithm example code
  • How to use JavaScript to implement sorting algorithms
  • JavaScript programming through Matlab centroid algorithm positioning learning
  • Binary Search Tree Algorithm Tutorial for JavaScript Beginners
  • Summary of seven sorting algorithms implemented in JavaScript (recommended!)
  • A brief discussion on an efficient algorithm for constructing tree structures in JavaScript
  • How to Learn Algorithmic Complexity with JavaScript
  • How to use javascript to do simple algorithms

<<:  A brief discussion on the efficiency of MySQL subquery union and in

>>:  Example of using supervisor to manage nginx+tomcat containers

Recommend

A brief discussion on how to customize the host file in Docker

Table of contents 1. Command 2. docker-compose.ym...

The latest 36 high-quality free English fonts shared

01. Infinity Font Download 02. Banda Font Download...

Summary of the differences between Vue's watch, computed, and methods

Table of contents 1 Introduction 2 Basic usage 2....

MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

CentOS8 - bash: garbled characters and solutions

This situation usually occurs because the Chinese...

Docker starts in Exited state

After docker run, the status is always Exited Sol...

JS implements click drop effect

js realizes the special effect of clicking and dr...

MySQL trigger definition and usage simple example

This article describes the definition and usage o...

Are the value ranges of int(3) and int(10) the same in mysql

Table of contents Question: answer: Reality: Know...

How to implement parent-child component communication with Vue

Table of contents 1. Relationship between parent ...

Some pitfalls of JavaScript deep copy

Preface When I went to an interview at a company ...

mysql solves the problem of finding records where two or more fields are NULL

Core code /*-------------------------------- Find...

Detailed explanation of CSS3 elastic expansion box

use Flexible boxes play a vital role in front-end...

A brief understanding of MySQL storage field type query efficiency

The search performance from fastest to slowest is...