当前位置:首页 > JavaScript

js实现随机摇号

2026-01-31 03:14:57JavaScript

随机摇号实现方法

基础随机数生成

使用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]);

时间种子增强随机性

为防止预测,可结合时间因素增强随机性:

js实现随机摇号

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名

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获取 jQ…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现视口

js实现视口

js实现视口检测的方法 使用JavaScript检测元素是否进入视口(viewport)可以通过Intersection Observer API或手动计算元素位置实现。以下是两种常见方法: Int…

js实现代码雨

js实现代码雨

实现代码雨效果 使用HTML5 Canvas和JavaScript可以轻松实现经典的代码雨效果。以下是完整的实现代码和说明: HTML结构 <!DOCTYPE html> <…