wordpress 網頁目錄下湖南專業(yè)seo公司
好的,以下是一個用JavaScript編寫的抽獎程序,它根據給定的概率來決定獎項。我們將使用隨機數生成器來模擬抽獎過程。
function drawPrize() {const prizes = [{ name: '特等獎', probability: 0.00000001 },{ name: '一等獎', probability: 0.00000003 },{ name: '二等獎', probability: 0.000004 },{ name: '三等獎', probability: 0.00001 },{ name: '大眾獎', probability: 0.0001 },{ name: '陽光普照獎', probability: 0.45 },{ name: '謝謝惠顧', probability: 0.3 },{ name: '再來一次', probability: 0.24999996 } // 確保所有概率之和為1];const random = Math.random();let cumulativeProbability = 0;for (const prize of prizes) {cumulativeProbability += prize.probability;if (random < cumulativeProbability) {return prize.name;}}
}// 測試抽獎程序
function testDrawPrize(times) {const results = {};for (let i = 0; i < times; i++) {const prize = drawPrize();if (results[prize]) {results[prize]++;} else {results[prize] = 1;}}return results;
}// 抽獎次數let num=20000000;
const results = testDrawPrize(num);
console.log(results);// 可視化結果(可選)
for (const prize in results) {console.log(`${prize}: ${(results[prize] / num* 100).toFixed(2)}%`);
}
說明:
- 獎項和概率:我們定義了一個數組
prizes
,其中每個對象包含一個獎項名稱和對應的概率。 - 隨機數生成:使用
Math.random()
生成一個介于 0 和 1 之間的隨機數。 - 累積概率:我們遍歷
prizes
數組,并計算累積概率。如果生成的隨機數小于或等于當前累積概率,則返回對應的獎項。 - 測試函數:
testDrawPrize
函數用于多次運行抽獎程序,并統(tǒng)計每個獎項的出現次數。 - 結果打印:我們運行
testDrawPrize
函數 1000000 次,并打印每個獎項的出現次數及其百分比。
注意,概率的總和必須為1,因此我在 再來一次
的概率中做了微調,以確??偤蜑?。由于浮點數的精度問題,這種微調是必要的。