js实现随机摇号
随机摇号实现方法
基础随机数生成
使用Math.random()生成0到1之间的随机数,结合Math.floor()或Math.ceil()实现整数范围随机:

function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 示例:生成1-100的随机数
const randomNum = getRandomInt(1, 100);
数组元素随机抽取
使用Fisher-Yates洗牌算法实现公平随机抽取:

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
// 示例:从10人中随机抽取3人
const people = ['张三','李四','王五','赵六','钱七','孙八','周九','吴十','郑十一','王十二'];
const shuffled = shuffleArray([...people]).slice(0, 3);
权重随机算法
对于需要加权随机的情况(如不同概率中奖):
function weightedRandom(weights) {
const sum = weights.reduce((a, b) => a + b, 0);
let rand = Math.random() * sum;
for (let i = 0; i < weights.length; i++) {
if (rand < weights[i]) return i;
rand -= weights[i];
}
}
// 示例:三个奖项的中奖概率分别为50%,30%,20%
const prizeIndex = weightedRandom([50, 30, 20]);
时间种子增强随机性
为防止预测,可结合时间因素增强随机性:
function seededRandom(seed) {
const x = Math.sin(seed) * 10000;
return x - Math.floor(x);
}
// 使用当前时间戳作为种子
const randomValue = seededRandom(Date.now());
完整摇号系统示例
class LotterySystem {
constructor(participants) {
this.participants = participants;
this.winners = [];
}
drawWinners(count) {
const pool = [...this.participants];
while (this.winners.length < count && pool.length > 0) {
const index = Math.floor(Math.random() * pool.length);
this.winners.push(pool.splice(index, 1)[0]);
}
return this.winners;
}
reset() {
this.winners = [];
}
}
// 使用示例
const lottery = new LotterySystem(['A','B','C','D','E']);
console.log(lottery.drawWinners(2)); // 随机选出2名






