模拟,摸珠子小游戏

	// 乱序
    function shuffle(a) {
      for(let i = a.length; i; i--) {
        let j = Math.floor(Math.random() * i)
        [a[i - 1], a[j]] = [a[j], a[i - 1]]
      }
      return a
    }
    // 排序
    function bubbleSort(array) {
      const len = array.length
      if (len < 2) return array
      for (let i = 0; i < len; i++) {
        for (let j = 0; j < i; j++) {
          if (array[j] > array[i]) {
            const temp = array[j]
            array[j] = array[i]
            array[i] = temp
          }
        }
      }
      return array
    }
    const prize = () => {
      const a = new Array(8).fill('a')
      const b = new Array(8).fill('b')
      const c = new Array(8).fill('c')
      // const box = shuffle(a.concat(b).concat(c))
      const box = a.concat(b).concat(c)
      const result = []
      for (let i = 0; i < 12; i++) {
        const r = Math.floor(Math.random() * 24)
        result.push(box[r])
      }
      const aNum = result.filter(item => item === 'a').length
      const bNum = result.filter(item => item === 'b').length
      const cNum = result.filter(item => item === 'c').length
      return [aNum, bNum, cNum]
    }
    const count = 10000
    const resultArr = [
      [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6],
      [1, 1], [1, 2], [1, 3], [1, 4], [1, 5],
      [2, 2], [2, 3], [2, 4], [2, 5],
      [3, 3], [3, 4],
      [4, 4]
    ]
    const result = resultArr.map(item => {
      return {
        number: `${item.toString()},${12 - item[0] - item[1]}`,
        count: 0
      }
    })
    for (let i = 0; i < count; i++) {
      const r = prize()
      for (const item of result) {
        if (item.number === bubbleSort(r).toString()) {
          item.count++
        }
      }
    }
    for (const item of result) {
      console.log(item.number, Math.floor((item.count / count) * 10000) / 100 + '%')
    }

和李老师计算的概率不一致

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值