Loading

三门问题 js解法

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>三门问题</title>
</head>

<body>

  <script>
    
    function getRes(doors, reSelect) {
      const len = doors.length
      const x = Math.ceil(Math.random() * len) // 汽车所在的第x扇门
      const car = doors[x - 1] // 汽车所在的门 - 对应的门牌号
      
      const y = Math.ceil(Math.random() * len) // 玩家选择第y扇门
      let player = doors[y - 1] // 玩家选择的门 - 对应的门牌号
      
      const left_doors = [...doors] // 玩家选择后剩下的门
      left_doors.splice(y - 1, 1)
      
      const z = Math.ceil(Math.random() * (len - 1)) // 主持人选择第z扇门,不能等于礼物所在的门
      const presenter = left_doors[z - 1] // 主持人选择的门 - 对应的门牌号
      
      const resDoors = [...left_doors] // 剩下的门
      resDoors.splice(z - 1, 1)
      const resDoor = resDoors[0] // 剩下的一扇门对应的门牌号
      
      if (reSelect) { // 换门
        return resDoor === car // 玩家当前选择不等于车所在门,换门后一定中奖
      } else {
        return player === car // 玩家不换门,只有当等于车所在门才中奖
      }
    }
    
    /**
     * 选数字游戏执行函数
     * @param {Array} doors 门的数组
     * @param {Number} times 玩游戏的次数
     * @param {boolean} reSelect 是否重新选择
     */
    function playGame(doors, times, reSelect) {
      if (typeof times !== 'number' || parseInt(times) !== times) {
        console.warn("请输入整数局的对局次数");
        return false;
      }
      
      let count = 0
      
      for (let i = 0; i < times; i++) {
        if (getRes(doors, reSelect)) {
          count ++
        }
      }
      
      return count / times
    }
    
    const doors = ['A', 'B', 'C']
    const times = 10000
    document.write('玩家不变更选择,中奖概率是:', playGame(doors, times, false), '<br/>玩家变更选择,中奖概率是:', playGame(doors, times, true))
    console.log('玩家不变更选择,中奖概率是:', playGame(doors, times, false), '\n玩家变更选择,中奖概率是:', playGame(doors, times, true))
  </script>
</body>

</html>

经过多次测试,结果无限接近2/3,所以换门胜率更大!

posted @ 2019-06-19 23:13  Frank-Link  阅读(283)  评论(0编辑  收藏  举报