monty7.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/random.h>


int gen_door(void)
{
	unsigned int rn = 0;

	if (getrandom(&rn, sizeof(unsigned int), GRND_NONBLOCK) == 1){
		perror("getrandom");
		exit(1);
	}
	return(rn % 3 + 1);
}

int main(void)
{
	int prize_door;
	int door_before_switch;
	int number_games;
	int win_switch = 0;
	int win_noswitch = 0;

	for(number_games = 0; number_games < 10000; number_games++){
		prize_door = gen_door();
		door_before_switch = gen_door();
		if (door_before_switch == prize_door){
			/* for not switching */
			win_noswitch++;
		}
		else{
			/* for switching */
			win_switch++;
		}
	}
	printf("Won %d (%f%%)games where we switched\n",
		win_switch, (double) win_switch / (double) number_games);
	printf("Won %d (%f%%)games where we did notswitch\n",
		win_noswitch, (double) win_noswitch / (double) number_games);




	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh