monty9.c

/*
 * Monty Hall problem simulation
 *
 * Matt Bishop, ECS 36A
 * -- May 27, 2024	original version(s) done
 * -- May 28, 2024	finished in class
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/random.h>

/*
 * macros
 */
#define NUM_GAMES  1000000	/* default number of games */

/*
 * generate a number between 1 and 3 inclusive
 * we only need 1 random byte, hence the unsigned char
 * getrandom should either return the byte or fail
 */
int gen_door(void)
{
	unsigned char rn = 0;		/* space for random byte */

	/* generate a random byte */
	if (getrandom(&rn, sizeof(unsigned char), GRND_NONBLOCK) == -1){
		perror("getrandom");
		exit(1);
	}
	/* map it into 1, 2, or 3 and return it */
	return(rn % 3 + 1);
}




int main(int argc, char *argv[])
{
	int i;				/* counter in a for loop */
	char *ends;			/* points to 1 beyond end of argv[1] */
	int prize_door;			/* door behind which prize lies */
	int door_before_switch;		/* door contestant picks */
	int number_games;		/* how many games to play */
	int win_switch = 0;		/* how many games switching doors won */
	int win_noswitch = 0;		/* how many games not switching doors won */

	/*
	 * check there are either 0 or 1 arguments
	 * and process them
	 */
	if (argc > 2){
		fprintf(stderr, "Usage: %s [ number of games ]\n", argv[0]);
		return(1);
	}
	else if (argc == 2){
		number_games = strtol(argv[1], &ends, 10);
	        if (*ends != '\0' || number_games < 1){
			fprintf(stderr, "%s: need positive integer\n", argv[1]);
                	return(1);
		}
        }
	else{	/* argc == 1 */
		number_games = NUM_GAMES;
	}

	/*
	 * now play the games
	 */
	for(i = 0; i < number_games; i++){
		prize_door = gen_door();		/* generate the door for the prize */
		door_before_switch = gen_door();	/* generate door contestant chose */
		/* now see whether switching wins */
		if (door_before_switch == prize_door){
			/* for not switching */
			win_noswitch++;
		}
		else{
			/* for switching */
			win_switch++;
		}
	}

	/*
	 * announce results
	 */
	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 not switch\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