1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| let testArr = [ { text: "普通", ran: 0.8 }, { text: "稀有", ran: 0.1 }, { text: "传奇", ran: 0.05 }, { text: "传说", ran: 0.025 }, { text: "金色传说", ran: 0.01 }, ]
function ranText(arr) { let totalNum = 0, numMap = [], lastNum = 0, fixNum = getFixNum(arr); arr.forEach(el => { totalNum += el.ran * fixNum; numMap.push({ text: el.text, ran: [lastNum, totalNum] }); lastNum = totalNum + 1; }) let ranNum = Math.floor(Math.random() * totalNum), text = ""; numMap.forEach(el => { if (ranNum >= el.ran[0] && el.ran[1] >= ranNum) { text = el.text; } }) return text; }
function getFixNum(arr) { let num = 1, ret = "1"; arr.forEach(el => { if (el.ran.toString().split(".").length === 2) { let thisNum = el.ran.toString().split(".")[1].length if (thisNum > num) { num = thisNum; } } }); for (var i = 0; i < num; i++) { ret += "0"; } return ret * 1; }
function testFun(arr, num) { let oArr = [], hit = false; for (var i = 0; i < num; i++) { let tag = ranText(arr), findEl = oArr.find((el) => el.text === tag); if (findEl) { findEl.nums++; } else { oArr.push({ text: tag, nums: 1 }); } } console.log("目标比例"); console.log(arr); console.log("实际比例"); console.log(oArr); }
testFun(testArr, 10000);
|