fix: 优化随机选择算法以确保概率均匀
- 在选择随机元素时,使用 Math.floor() 替代 Math.round() - 此修改解决了随机元素概率不均的问题,提高了算法的公平性 - 主要应用于人员抽奖和随机球数据生成两个场景
This commit is contained in:
@@ -425,7 +425,8 @@ function startLottery() {
|
||||
luckyCount.value = leftover < luckyCount.value ? leftover : luckyCount.value
|
||||
for (let i = 0; i < luckyCount.value; i++) {
|
||||
if (personPool.value.length > 0) {
|
||||
const randomIndex = Math.round(Math.random() * (personPool.value.length - 1))
|
||||
// 解决随机元素概率过于不均等问题
|
||||
const randomIndex = Math.floor(Math.random() * (personPool.value.length - 1))
|
||||
luckyTargets.value.push(personPool.value[randomIndex])
|
||||
personPool.value.splice(randomIndex, 1)
|
||||
}
|
||||
@@ -587,8 +588,9 @@ function randomBallData(mod: 'default' | 'lucky' | 'sphere' = 'default') {
|
||||
const cardRandomIndexArr: number[] = []
|
||||
const personRandomIndexArr: number[] = []
|
||||
for (let i = 0; i < indexLength; i++) {
|
||||
const randomCardIndex = Math.round(Math.random() * (tableData.value.length - 1))
|
||||
const randomPersonIndex = Math.round(Math.random() * (allPersonList.value.length - 1))
|
||||
// 解决随机元素概率过于不均等问题
|
||||
const randomCardIndex = Math.floor(Math.random() * (tableData.value.length - 1))
|
||||
const randomPersonIndex = Math.floor(Math.random() * (allPersonList.value.length - 1))
|
||||
if (luckyCardList.value.includes(randomCardIndex)) {
|
||||
continue
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user