js實現(xiàn)指定紅包順序和金額算法
更新時間:2021年04月19日 11:49:45 作者:莫兮是我
這篇文章主要為大家詳細介紹了js實現(xiàn)指定紅包順序和金額算法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js實現(xiàn)指定紅包順序和金額的具體代碼,供大家參考,具體內(nèi)容如下
前言
- 朋友拜托而寫
- 單個包最小金額為0.01
- 如果除指定金額外,其余都為0.01,最后尾包存在為0的幾率
- 本算法通過了1000000次測試,出錯率為百萬分之3
效果展示
空包問題
紅包算法
/* param: float, int, int, float param1:紅包金額總額 param2:紅包數(shù)目 param3:指定特殊紅包 param4:指定特殊紅包金額 */ let getPrize = function(total, number, index, volume){ let allowance = total - volume; let arr = []; let i = 0; while(i < number - 2){ // 指定[0.01,allowance-(i*0.01)) let temp = (Math.random()*(allowance - (number - 1 - i) * 0.01) + 0.01).toFixed(2); // if(temp < 0) console.log(`temp:${temp}`); temp = temp <= 0 ? 0.01 : temp; arr.push(parseFloat(temp)); allowance = parseFloat((allowance - temp).toFixed(2)); i++; // console.log(`arr:${arr}, i:${i}`); // 如果出現(xiàn)小于0的分配情況,剝削強者均分 if(allowance <= 0){ // console.log(`alowance:${allowance}`); let w = arr.filter((val,index)=>{ // console.log(`val:${val}`); if(val > 0.01){ arr[index] = parseFloat((arr[index] - 0.01).toFixed(2)); return val; } }); if(w.length == 0){ allowance = 0; }else{ allowance = 0.01; } } } // 最后一個放入 arr.push(parseFloat(allowance.toFixed(2))); let result = arr; return result.slice(0, index).concat(parseFloat(volume), result.slice(index)); }
測試樣例
// Test sample for(let m = 0; m < 10000; m++){ let total = (Math.random()*100 + 0.01).toFixed(2); let number = Math.floor(Math.random()*20 +2); while(total / number < 0.01){ number = Math.floor(Math.random()*20 +2); } let index = Math.floor(Math.random()*(number - 1)); let volume = (Math.random()*(total - 0.01*(number-1))+0.01).toFixed(2); while(volume >= total || volume + 0.01*(number-1) > total){ // console.log(`xx:${volume}`); volume = (Math.random()*(total - 0.01*(number-1))+0.01).toFixed(2); volume = volume <= 0 ? 0.01 : volume; } let test = getPrize(total, number, index, volume); // console.log(test); let sum = test.reduce((total,val)=>total+=parseFloat(val)); sum = sum.toFixed(2); if(sum !== total) { console.log(`volume:${volume}, total: ${total}, number: ${number}`); console.log(`sum:${sum}`); console.log(test); } test.map((val,index)=>{ if(val <= 0 && index !== test.length - 1){ console.log(`volume:${volume}, total: ${total}, number: ${number}`); console.log(`sum:${sum}`); console.log(test); } }); }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于前后端json數(shù)據(jù)的發(fā)送與接收詳解
這篇文章主要給大家介紹了關(guān)于前后端json數(shù)據(jù)發(fā)送與接收的相關(guān)資料,文中通過示例代碼詳細介紹了關(guān)于flask中的json數(shù)據(jù)接收和前端發(fā)送json數(shù)據(jù)等內(nèi)容,需要的朋友可以參考借鑒,下面來一起看看吧。2017-07-07Javascript執(zhí)行流程細節(jié)原理解析
這篇文章主要介紹了Javascript執(zhí)行流程細節(jié)解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05