生成微信红包金额
Sonder
2019-08-22
1778字
4分钟
浏览 (2.4k)
第一步:获取随机值
sum = 20+61+97+39+32+48+10+20+48+78 = 453
share1 = 20/453 = 0.04415011
...
share10 = 0.17218543
第二步:计算红包金额
a1 = share1 * 100 = 0.04415011 * 100 = 4.415011
...
a10 = share10 * 100 = 0.17218543 * 100 = 17.218543
代码
$('#submit').click(function(){
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function getNextItemKey(currentKey, count) {
if (currentKey > count) {
throw 'Error: currentKey > count';
}
if (currentKey != count) {
return currentKey + 1;
} else {
return 1;
}
}
var count = $('#count').val();
var amount = $('#amount').val();
if (!count) {
alert('红包个数必须填写');
return false;
}
if (!amount) {
alert('总金额必须填写');
return false;
}
if (amount / count < 0.01) {
alert('单个红包金额不可低于0.01元,请重新填写金额');
return false;
}
amount = amount * 100;
var items = [];
for (var i = 0; i < count; ++ i) {
items[i] = getRandomInt(1, 100);
}
var itemAmounts = [];
var sum = items.reduce(function(pv, cv) { return pv + cv; }, 0);
var currentAmount = 0;
for (var i = 0; i < count; ++ i) {
if (i !== count - 1) {
itemAmounts[i] = Math.floor(items[i] / sum * amount);
currentAmount += itemAmounts[i];
} else {
itemAmounts[i] = amount - currentAmount
}
}
for (var i = 0; i < count; ++ i ) {
if (itemAmounts[i] > 0) {
continue;
}
var nextKey = getNextItemKey(i, count);
var diff = 1 - itemAmounts[i];
itemAmounts[i] = 1;
itemAmounts[nextKey] -= diff;
}
for (var i = 0; i < count; ++ i ) {
itemAmounts[i] = itemAmounts[i] / 100;
}
alert(itemAmounts.join('元'));
});