monty4.c

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


int ask_user(void)
{
	unsigned int rn;

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

int ask_user_yn()
{
	int ch, i;

	while(printf("> "), (ch = getchar()) != EOF){
		while((i = getchar()) != '\n' && i != EOF)
			;
		if (ch == 'y' || ch == 'Y')
			return('y');
		else if (ch == 'n' || ch == 'N')
			return('n');
		printf("y or n please! ");
	}
	exit(1);
}

void set_prize_door(int *door)
{
	printf("Select door where prize is ");
	if ((*door = ask_user()) == 0)
		exit(1);
}

void contestant_picks_door(int *door)
{
	printf("Select door for contestant ");
	if ((*door = ask_user()) == 0)
		exit(1);
}


void switch_or_not(int start_door, int prize_door)
{
	printf("Does contestant switch doors? ");
	if (ask_user_yn() =='y'){
		if (start_door != prize_door)
			printf("You picked door %d, and the prize is behind door %d -- you win!\n", start_door, prize_door);
		else
			printf("You picked door %d, but the prize is behind door %d -- you lose!\n", start_door, prize_door);
	}
	else{
		if (start_door == prize_door)
			printf("You picked door %d, and the prize is behind door %d -- you win!\n", start_door, prize_door);
		else
			printf("You picked door %d, but the prize is behind door %d -- you lose!\n", start_door, prize_door);
	}
}

int main(void)
{
	int prize_door;
	int door_before_switch;

	set_prize_door(&prize_door);
	contestant_picks_door(&door_before_switch);
	printf("prize door %d, door before switch %d\n", prize_door, door_before_switch);
	switch_or_not(door_before_switch, prize_door);

	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: [email protected]
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