如何用 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. jQuery 真伪数组的转换

    //真数组转换伪数组 var arr = [1,3,5,7,9]; var obj = {}; [].push.apply(obj,arr); console.log(obj) //伪数组转真数组 v ...

  2. 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/

  3. How does Circus stack compare to a classical stack?

    Frequently Asked Questions - Circus 0.15.0 documentation https://circus.readthedocs.io/en/latest/faq ...

  4. vue组件中data为什么必须是一个函数?

    因为JavaScript的特性所导致,在component中,data必须以函数的形式存在,不可以是对象. 组建中的data写成一个函数,数据以函数返回值的形式定义,这样每次复用组件的时候,都会返回一 ...

  5. JavaWeb——JSP内置对象application,JSP属性范围

    application application语法 application对象 JSP属性范围 范围的分类 page request session application pagecontext延伸 ...

  6. snmp协议 及snmpwalk

    推荐阅读: snmp及工具:https://www.jianshu.com/p/dc2dc0222940 snmp协议详解:https://blog.csdn.net/shanzhizi/articl ...

  7. Codeforces Round #652 (Div. 2) E. DeadLee(贪心)

    题目链接:https://codeforces.com/contest/1369/problem/E 题意 Lee 有 $n$ 种不同种类的食物和 $m$ 个朋友,每种食物有 $w_i$ 个,每个朋友 ...

  8. Codeforces Round #665 (Div. 2) D - Maximum Distributed Tree dfs贡献记录

    题意: t组输入,每组数据中n个节点构成一棵树,然后给你n-1条边.给你一个m,然后给你m个k的素数因子,你需要给这n-1条边都赋一个权值,这n-1条边的权值之积应该等于k.如果k的素数因子数量小于n ...

  9. Codeforces Round #660 (Div. 2) Captain Flint and Treasure 拓扑排序(按照出度、入读两边拓扑排序)

    题目链接:Captain Flint and Treasure 题意: 一种操作为 选一个下标 使得ans+=a[i] 且 把a[b[i]]+a[i]   要求每个下标都进行一种这样的操作,问怎么样的 ...

  10. Codeforces Round #648 (Div. 2) E. Maximum Subsequence Value 贪心

    题意:E.Maximum Subsequence Value 题意: 给你n 个元素,你挑选k个元素,那么这个 k 集合的值为 ∑2i,其中,若集合内至少有 max(1,k−2)个数二进制下第 i 位 ...