#include<iostream>
#include<cstdlib>
using namespace std;
// Pre-conditions: takes in array of characters
// and number of elements to use
// Post-conditions: Place 'C' in one of first
// SIZE number of elements and
// 'G' in all other elements
void assignDoors(char doors[],int size);
int main()
{
// Initialize variables
int num_doors, door_choice, goat_door;
char switch_decision;
char doors[4];
// Initialize randomizer
srand(time(0));
// Get number of doors to play with
cout << "How many doors? ";
cin >> num_doors;
// Assign car to one door, goat to others
assignDoors(doors,num_doors);
// Get guess of car location
cout << "What door do you think the car is behind? ";
cin >> door_choice;
// Pick door to show where there is a got
do {
goat_door=rand()%num_doors+1; // randomly pick a door
/* while condition rejects that door if
there is a car behind it or if the
user has picked that door
(this is the strategy Justin
recommended!) */
} while(goat_door==door_choice || doors[goat_door-1]=='C');
cout << "The car is not behind door "
<< goat_door << endl;
// Ask user if s/he wants to change doors
cout << "Do you want to switch?";
cin >> switch_decision;
// switch doors
if(switch_decision=='Y')
{
if(num_doors==4) { // Give user choice
// of new door in 4-door
// condition
cout << "What door do you want? ";
cin >> door_choice;
} else { // In 3 door condition, there
// is an interesting math trick
// to determine which numbered door
// is left: the number is
// 6-(door that was shown)-(door previously chosen)
door_choice=6-goat_door-door_choice;
}
}
// Announce if user has won the car or not
if(doors[door_choice-1]=='C')
cout << "You won the car!\n";
else
cout << "Sorry, you got a goat!\n";
// At the end, I announce the contents of each
// door -- this is good for debugging, but not
// part of the final-product
for(int i=0;i<num_doors;i++)
{ cout << doors[i]; }
cout << endl;
return 0;
}
// Randomly assign car ('C') to one of first SIZE doors
// and goats ('G') to the rest
void assignDoors(char doors[], int size)
{
// Initialize all doors to 'G' for goat
for(int i=0;i<size;i++)
doors[i]='G';
// Randomly place goat in one of first
// SIZE doors
doors[rand()%size]='C';
}