如何用 js 实现一个类似微信红包的随机算法
如何用 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 实现一个类似微信红包的随机算法的更多相关文章
- 如何用 js 实现一个 class 类函数
如何用 js 实现一个 class 类函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refere ...
- 如何用 js 实现一个 apply 函数
如何用 js 实现一个 apply 函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referen ...
- 如何用 js 实现一个 call 函数
如何用 js 实现一个 call 函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referenc ...
- 如何用 js 实现一个 sleep 函数
如何用 js 实现一个 sleep 函数 原理 实现方式 总结 refs js sleep xgqfrms 2012-2020 www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
- 如何用 js 实现一个 new 函数
如何用 js 实现一个 new 函数 原理 new 关键字实现经过了如下过程 创建一个空对象 obj = {} 链接到原型 obj.proto = constructor.prototype 绑定 t ...
- 如何用 js 实现一个 bind 函数
如何用 js 实现一个 bind 函数 原理 实现方式 总结 refs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Referenc ...
- 说说如何用js实现一个模板引擎
本文同步更新在: https://github.com/whxaxes/blog/issues/4 ,在 github 看文章显示效果会更好一些. 前言 不知不觉就很长时间没造过什么轮子了,以前一直想 ...
- Qt 做一个类似微信滑动聊天界面的demo
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://www.cnblogs.com/lihuidashen/p/115889 ...
- 使用React.js写一个类似单选框与复选框的功能
单选框 <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <tit ...
随机推荐
- centralized collectors 中心化 采集器
Fluent Bit https://fluentbit.io/ FluentBit is an open source specialized data collector. It provides ...
- https://www.cnblogs.com/AloneSword/p/3209653.html
proc/sys/net/ipv4/下各项的意义 - 孤剑 - 博客园 https://www.cnblogs.com/AloneSword/p/3209653.html
- “batteries included” philosophy
https://docs.djangoproject.com/en/2.2/ref/contrib/ contrib packages Django aims to follow Python's & ...
- 分布式缓存 — Docker
Docker 是一个开源项目,它基于 Google 公司推出的 Go 语言实现. 项目后来加入了 Linux 基金会,遵从了 Apache 2.0 协议,项目代码在 GitHub 上进行维护. Doc ...
- Jsp数字格式化
日期格式(2008年5月5日22点00分23秒) <fmt:formatDate value="<%=new Date() %>" pattern="y ...
- 小程序UnionID浅谈
UnionID机制说明 如果开发者拥有多个移动应用.网站应用.和公众帐号(包括小程序),可通过 UnionID 来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用.网站应用和公众帐号(包 ...
- 最全面的图卷积网络GCN的理解和详细推导,都在这里了!
目录 目录 1. 为什么会出现图卷积神经网络? 2. 图卷积网络的两种理解方式 2.1 vertex domain(spatial domain):顶点域(空间域) 2.2 spectral doma ...
- 网络编程(socket简介)
socket简介 Python 提供了两个基本的 socket 模块. 第一个是 Socket,它提供了标准的 BSD Sockets API. 第二个是 SocketServer, 它提供了服务器中 ...
- php开发扩展环境的搭建(Windows)
php开发扩展环境的搭建(Windows) 前期准备: (1) 下载php-5.3.10源码包(php-5.3.10.tar.bz2)并解压到C:\php-5.3.10:下载二进制包php-5.3.1 ...
- PHP-mysql存储照片的两种方式
PHP-mysql存储照片的两种方式 方式一:把图片数据存储在数据库中(二进制) 数据库代码: CREATE TABLE `photo` ( `id` int(10) unsigned NOT ...