Array.fill & array padding
Array.fill & array padding
arr.fill(value[, start[, end]])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
const log = console.log;
const arr = [...new Uint8Array(4)];
//const arr = [1, 2, 3, 4];
log(arr);
// [0, 0, 0, 0]
// fill with 0.01 from position 0 until position 4
log(arr.fill(0.01, 0, 4));
// [0.01, 0.01, 0.01, 0.01]
https://github.com/mljs/pad-array
String.padStart & String.padEnd()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
最简单的方法实现微信红包的随机算法🧧
微信红包的随机算法是怎样实现的?
https://www.zhihu.com/question/22625187/answer/1478941580
/**
算法需要满足条件:
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) => {
const result = [...new Uint8Array(num)].fill(0.01, 0, num);
// 正态分布 ❓ TODO...
// 就地交换, shuffle
return shuffle(result);
}
const shuffle = (arr = []) => {
let len = arr.length;
while (len > 1){
// Math.floor
const index = Math.floor(Math.random() * len--);
// ES6 swap
[
arr[len],
arr[index],
] = [
arr[index],
arr[len],
];
}
return arr;
}
// 测试
const test = autoRandomRedPackage(100, 10);
log(`test =`, test)
https://www.zhihu.com/question/22625187
/**
算法需要满足条件:
1. 每个人都可以分到至少 0.01 元;
2. 所有人的分到的红包之和与发出的金额相等,不多不少,刚好分完;
3. 每个人分到金额的概率相等;
*/
/**
假设,发出一个 100元红包,给 10个人分!
算法实现
*/
const autoRandomRedPackage = (money, num, limit = 0.01) => {
const result = [...new Uint8Array(num)].fill(0.01, 0, num);
// const result = [...new Uint8Array(num)].padding(0.01);
}
// 测试
const test = autoRandomRedPackage(100, 10);
log(`test =`, test)
//
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13688278.html
未经授权禁止转载,违者必究!