如何用 js 实现一个类似微信红包的随机算法

js, 微信红包, 随机算法

"use strict";

/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-09-16
* @modified
*
* @description 如何用 js 实现一个类似微信红包的随机算法, 最简单的方法实现微信红包的随机算法
* @difficulty Hard
* @complexity O(n)
* @augments
* @example
* @link https://www.cnblogs.com/xgqfrms/p/13689802.html
* @link https://www.cnblogs.com/xgqfrms/tag/%E7%BA%A2%E5%8C%85/
* @link https://www.zhihu.com/question/22625187/answer/1478941580
* @solutions
*
*/ const log = console.log; const shuffle = (arr = []) => {
let len = arr.length;
while (len > 1){
const index = Math.floor(Math.random() * len--);
[
arr[len],
arr[index],
] = [
arr[index],
arr[len],
];
}
return arr;
} /** 算法需要满足条件:
1. 每个人都可以分到至少 0.01 元;
2. 所有人的分到的红包之和与发出的金额相等,不多不少,刚好分完;
3. 每个人分到金额的概率相等;
*/ /** 假设,发出一个 100元红包,给 10个人分! 算法实现:
1. 按照人数,生成一个等长的数组,且每一个元素的初始化值为 0.01;
2. 将剩余的金额(100 - 10 * 0.01), 按照微信设计的规则(假如是正态分布)进行分配出 10 份;
3. 将分配好的红包,依次加入到生成的数组中;
4. 最后使用 shuffle 算法打乱数组,并返回;
5. 将计算好的数组,按照抢红包的顺序作为索引值依次取出红包即可. */ // 精度损失解决方案, 扩大后,再还原
const autoRandomRedPackage = (money, num, limit = 0.01) => {
if((money / num) < limit) {
// alert
log(` 请重新输入红包数量! 减少红包数量,或增加红包金额!`);
log(` 你输入的红包数量太多了,每个人至少要能分到 0.01 元!`);
return false;
} else {
const originMoney = money;
const originLimit = limit;
let multi = 100 * (100 / money);
money *= multi;
limit *= multi;
// log(`multi =`, multi);
const result = [...new Uint8Array(num)].fill(limit, 0, num);
// 1. 将剩余的红包,均分,如果有余数,随机的添加到数组的一个元素上
const restLimit = (money - limit * num) / limit;
const reminderLimit = (restLimit % num);
const reminderMoney = reminderLimit * limit;
const averageLimit = (restLimit - reminderLimit) / num;
for (let i = 0; i < num; i++) {
const index = parseInt(Math.random() * averageLimit);
const randomMoney = index * limit;
const leftMoney = (averageLimit - index) * limit;
// 2. 在平均后的范围内,计算出一个随机数,将分配好的红包,依次加入到生成的数组中;
result[i] += randomMoney;
// 3. 分配后剩余的红包,随机加入到生成的数组中;
const j = parseInt(Math.random() * num);
result[j] += leftMoney;
}
// 4. 将平均后的余数红包,随机加入到生成的数组中;
if(reminderMoney > 0) {
const index = parseInt(Math.random() * num);
result[index] += reminderMoney;
}
const temp = shuffle(result).map(i => i / multi);
// log(`temp =`, temp);
const total = temp.reduce((acc, i) => acc += i*multi, 0) / multi;
// log(`total !== originMoney`, total !== originMoney, total, originMoney);
if(total !== originMoney) {
return autoRandomRedPackage(originMoney, num, originLimit);
}
const [min, ...rest1] = temp.sort((a, b) => a - b > 0 ? 1 : -1);
const [max, ...rest2] = temp.sort((a, b) => a - b > 0 ? -1 : 1);
return {
total: total,
result: temp,
desc: `

如何用 js 实现一个类似微信红包的随机算法的更多相关文章

  1. 如何用 js 实现一个 class 类函数

    如何用 js 实现一个 class 类函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refere ...

  2. 如何用 js 实现一个 apply 函数

    如何用 js 实现一个 apply 函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referen ...

  3. 如何用 js 实现一个 call 函数

    如何用 js 实现一个 call 函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referenc ...

  4. 如何用 js 实现一个 sleep 函数

    如何用 js 实现一个 sleep 函数 原理 实现方式 总结 refs js sleep xgqfrms 2012-2020 www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!

  5. 如何用 js 实现一个 new 函数

    如何用 js 实现一个 new 函数 原理 new 关键字实现经过了如下过程 创建一个空对象 obj = {} 链接到原型 obj.proto = constructor.prototype 绑定 t ...

  6. 如何用 js 实现一个 bind 函数

    如何用 js 实现一个 bind 函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referenc ...

  7. 说说如何用js实现一个模板引擎

    本文同步更新在: https://github.com/whxaxes/blog/issues/4 ,在 github 看文章显示效果会更好一些. 前言 不知不觉就很长时间没造过什么轮子了,以前一直想 ...

  8. Qt 做一个类似微信滑动聊天界面的demo

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://www.cnblogs.com/lihuidashen/p/115889 ...

  9. 使用React.js写一个类似单选框与复选框的功能

    单选框 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <tit ...

随机推荐

  1. 【Azure Developer】在Azure Resource Graph Explorer中查看当前订阅下的所有资源信息列表并导出(如VM的名称,IP地址内网/公网,OS,区域等)

    问题描述 通过Azure的Resource Graph Explorer(https://portal.azure.cn/#blade/HubsExtension/ArgQueryBlade),可以查 ...

  2. Oracle19c的多租户笔记

    Oracle19c的多租户笔记 1.多租户的概念 PDB(PLUGGABLE DATABASE)可以理解为我们Oracle11gR2的数据库,只不过是一个实例上面可以放置多个数据库了.名称为插件式数据 ...

  3. JAVA中关于基本数据和引用数据参数传递过程

    基本数据和引用数据参数传递过程 案例1:判断程序的输出结果 class Demo{ public static void main(String[] atgs){ int x =4; show(x); ...

  4. Connection reset by peer的常见原因及解决办法 RST 大文件上传

    Connection reset by peer的常见原因及解决办法 Connection reset by peer的常见原因 - 简书 https://www.jianshu.com/p/263e ...

  5. the code has to work especially hard to keep things in the same thread

    django/asgiref: ASGI specification and utilities https://github.com/django/asgiref/

  6. lodash的debounce函数的使用

    最新,在react新项目的开发中使用到了lodash类库的debounce方法,就随手梳理了一下此方法的方便之处 未使用debounce之前 如果不考虑使用debounce,那么在用户连续点击的情况之 ...

  7. JD价格监控【docker版】

    快过年了,准备买些年货,于是频繁刷购物网站对比价格,搞得还是挺头大的.我想能不能做个应用抓取实时价格并在低于预期价格后进行提醒,于是就有了本篇文章.本文主要分享怎么将本地项目打包成镜像并推送到dock ...

  8. P1908 逆序对——树状数组&离散化&快读快写の学习

    题目简述: 对于给定的一段正整数序列,逆序对就是序列中 a_i>a_jai​>aj​ 且 i<ji<j 的有序对. 输出序列中逆序对的数目. 知识补充: 树状数组: 这东西就是 ...

  9. Codeforces Round #651 (Div. 2) D. Odd-Even Subsequence(二分)

    题目链接:https://codeforces.com/contest/1370/problem/D 题意 给出一个含有 $n$ 个数的数组 $a$,从中选出 $k$ 个数组成子序列 $s$,使得 $ ...

  10. 【poj 2752】Seek the Name, Seek the Fame(字符串--KMP)

    题意:给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀.从小到大依次输出这些子串的长度. 解法:利用KMP中next[ ]数组的性质,依次找到前缀.后缀匹 ...