//A simple MasterMind Program
#include <iostream>
#include <vector>
#include <cstdlib>

using namespace std;

//Generate a random number between 0 and N
int random(int N) {return rand()%N;}

//Generate an n-digit random number
//This is a slightly more general version that the one that I used in the
//class on Friday
int generate_random_number(int n)
{
 //Generate the first digit, which cannot be zero
 int random_number = 1 + random(9);

 //Loop over the remaining digits
 for(unsigned int i=1;i<n;i++)
  {
   //Shift every digit to the left
   random_number *= 10;
   //Add another digit at the end
   random_number += random(10);
  }

 //Return the final random number
 return random_number;
}

//A neat little recursive function to determine how many digits guess and
//answer have in common
int compare_digits_of_two_numbers(int guess, int answer)
{
 //The number of digits in common
 int number_in_common=0;
 //If we have recursed all the way to zero in the guess
 if(guess==0)
  {
   //Check that we have recursed all the way to zero in the answer
   //If so, return the number of digits in common
   if(answer==0) {return number_in_common;}
   //If not, the guess has fewer digits than the answer, return an error
   else {return -1;}
  }
 else 
  {
   //Find the number of digits in common for all but the last digit
   number_in_common = 
    compare_digits_of_two_numbers((guess - guess%10)/10,
                                  (answer - answer%10)/10);

   //Now if the last digits are the same add one to the number_in_common
   if(guess%10 == answer%10) {number_in_common +=1;}

   //Return the number of digits in common
   return number_in_common;
  }
}
 
//Main program loop
int main()
  {
   //Set seed value for random number generation
   srand(time(0));
   
   //Ask the user how many digits there are to be in the number
   cout << "How many digits do you want?" << endl;
   int ndigits;
   cin >> ndigits;

   //Generate the random number
   int answer = generate_random_number(ndigits);

   //OK, now start looping
   do
    {
     //Read in the guess
     int guess;
     cout << "Enter guess " << endl;
     cin >> guess;

     //Find out how many digits are correct
     int ncorrect = compare_digits_of_two_numbers(guess,answer) ;

     //If there is an error report it
     if(ncorrect == -1) 
      {
       cout << "Need a " << ndigits << " digit number" << endl;
       continue;
      }
     //Otherwise say how many digits are correct
     else
      {
       cout << ncorrect << " digits correct" << endl;
      }
     //If all correct then exit
     if(ncorrect == ndigits) {break;}
    }
   while(true);

   //Congratulate the player!
   cout << "Well done" << endl;
  }
