蒙蒂霍尔模拟器

时间:2015-10-27 16:27:21

标签: c++ random

此代码编译并运行,但我没有获得Monty Hall问题的正确百分比。切换答案应该接近66%。我找不到问题所在。保持同一门的百分比是正确的,但切换,包括switchChoice和revealDoor功能,给出了一致但不正确的结果。

int winner(){
    return  (rand() / ( RAND_MAX / 3 ) + 1);
}
int userChoice(){
    return (rand() / ( RAND_MAX / 3 ) + 1);
}
int revealedDoor(int winnerX){  
    if (winnerX == 1){
            return  (2 + rand() % 2);
        }
        else if (winnerX == 2){
            if( ( 3 + rand() % 2) == 4){
                return  1;
            }else{
                return  3;
            }
        }
        else if (winnerX == 3){
            return  (1 + rand() % 2);
        }
    else return winnerX;
}
int switchChoice(int uChoice, int revealedD){
    int newChoice;
    do{
        newChoice =  1 + rand() % 3;
    }while ( uChoice == newChoice || newChoice == revealedD);

    return newChoice;
}

1 个答案:

答案 0 :(得分:0)

您的revealedDoor()方法可以返回用户的选择!你需要更多的东西(警告 - 快速入侵!):

int revealedDoor(int winnerX, int uChoice) {
    int ret = uChoice;
    while (ret == uChoice) {
        if (winnerX == 1){
                ret =  (2 + rand() % 2);
            }
            else if (winnerX == 2){
                if( ( 3 + rand() % 2) == 4){
                    ret =  1;
                }else{
                    ret =  3;
                }
            }
            else if (winnerX == 3){
                ret =  (1 + rand() % 2);
            }
        else ret = winnerX;
    }
    return ret;
}

然后将simulation ()更改为仅计算用户选择一次,并按上述方式传递:

vector<int> simulation (){
    long n, winnerX, uChoice = 0;
    vector<int> choiceCtr;
    choiceCtr.push_back(0);
    choiceCtr.push_back(0);

    cout << "How many times would you like to run the simulation? ";
    cin >> n;
    choiceCtr.push_back(n);

    for(int i = 0; i < n; i++){
        winnerX = winner();
        uChoice = userChoice();
        if(decision(switchChoice(uChoice, revealedDoor(winnerX, uChoice)), winnerX)){
            choiceCtr[0]++;
        }
    }
    for(int i = 0; i < n; i++){
    if(decision(uChoice, winner())){
        choiceCtr[1]++;
    }
    }
    return choiceCtr;
}

这给出了结果:

How many times would you like to run the simulation? 100000
66276
33439
Switching:
-----------------
You won 66276 out of 100000 Which is 66.28 percent.

Staying:
-----------------
You won 33439 out of 100000 Which is 33.44 percent.

我确信你可以提出更好的解决办法,但这个快速破解显然可以解决问题