mardi 5 septembre 2017

Monty Hall implementation

I recently watched a video regarding the Monty Hall problem and found it interesting, so I thought of implementing it to see if the probability is truly 66.6% as predicted.

Here is what I have,

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int repeat = 5000000, i;
    int win = 0, lose = 0;

    for (i = 1; i <= repeat; i++) {
        int winDoor = rand();
        winDoor = winDoor % 4;

        int firstPick = rand();
        firstPick = firstPick % 4;

        if (winDoor == firstPick) {
            lose++;
        } else {
            win++;
        }
    }

    printf("%.2f percent win rate\n", ((float)win/(float)repeat)*100.00);
}

However, I seem to be getting a 75% win rate (by switching doors) with the above code. Is there something wrong with my codes? Or is the 66.6% (2/3) a lie?

P.S. The logic I implemented is, if winning door is first picked, by switching, we lose. If losing door is first picked, by switching, we win. That's how I understand the Monty Hall problem.

EDIT: Oh shit, that's dumb of me. I actually put %4 because I read that %4 will represent 0-3. I forgot I need 1-3, not 0-3. Question resolved.




Aucun commentaire:

Enregistrer un commentaire