我如何获得此随机选择器游戏重复并计算结果



我在蒙蒂大厅问题上有这种变化,在这种变化中,它不是随机完成的,而不是选择和切换,而是随机完成。

我据说已经学会了足够的能力来创建它,以便随机选择器重复100次,并输出胜利计数和损失数,但是我一开始就卡住了。我所能证明的是,它成功地随机选择,但不知道该如何重复100倍并计算结果。我假设我需要使用一段时间循环和wincount ,但不知道该如何完成此工作。

感谢任何帮助!

//define prizes
//1 is a win
var prizes = [1,2,3];
var winCount = 0;
var loseCount = 0;
//copy prizes array so can be reused
var choices = prizes.slice();
//randomly select a prize
var pick1 = choices[Math.floor(Math.random() * choices.length)];
//find index of pick1
var pick1Index = choices.indexOf(pick1);
//remove an item that is not the win or pick1
function removePrize(choices,pick1){
    var prizeRemoved = Math.floor(Math.random()*choices.length);
    if(choices[prizeRemoved]==pick1){
        return removePrize(choices,pick1);
    }
    else if (choices[prizeRemoved]==1){
        return removePrize(choice,pick1);}
    else{
        return prizeRemoved;
    }
};
//randomly re-select from remaining prizes
var pick2 = choices[Math.floor(Math.random() * choices.length)];

//display pick2 to show selector works
alert(window["pick2"]);

我已经将代码移至带有解决方案的JSFiddle:https://jsfiddle.net/dwthz8v1/2/并已将控制台记录在输出中,按F12来看一下在控制台,我相信您要寻找的工作代码是:

//define prizes
//1 is a win
var prizes = [1,2,3];
var winCount = 0;
var loseCount = 0;
var totalGames = 100;
for(var i = 0; i < totalGames; i++) {
   //copy prizes array so can be reused
  var choices = prizes.slice();
   //randomly select a prize
  var pick1 = choices[Math.floor(Math.random() * choices.length)];
  var pick1Index = choices.indexOf(pick1);

    var removedPrize = removePrize(choices, pick1);
  var indexOfPrizeToRemove = choices.indexOf(removedPrize);
  //remove prize from choices
  choices.splice(indexOfPrizeToRemove);
  //remove pick1 from choices
  choices.splice(indexOfPrizeToRemove);
  var pick2 = choices[Math.floor(Math.random() * choices.length)];
  if(pick2 == 1) {
    console.log("Pick 2 won!");
    winCount++;
  }
  else {
    console.log("Pick 2 was wrong");
    loseCount++;
  }
}
console.log("Pick 2 won a total of " + winCount + " times");
console.log("Pick 2 lost a total of " + loseCount + " times");

//find index of pick1
var pick1Index = choices.indexOf(pick1);
//remove an item that is not the win or pick1
function removePrize(choices,pick1){
    var prizeRemoved = Math.floor(Math.random()*choices.length);
    if(choices[prizeRemoved]==pick1){
        return removePrize(choices,pick1);
    }
    else if (choices[prizeRemoved]==1){
        return removePrize(choices,pick1);}
    else{
        return prizeRemoved;
    }
};

它的工作方式是在循环中循环100次。每次迭代代表一个单独的游戏。

您设置了每个游戏的选择阵列。做出选择,然后删除选择,然后显示切换选择赢了多少次,以及切换丢失的时间

多少次

最新更新