#include<iostream>
#include<string>
using namespace std;
/* Declare Functions*/
bool checkSolution();
void findSolutions();
bool keepGoing();
/* Declare global variables */
const int RABBIT_FEET = 4;
const int CHICKEN_FEET = 2;
int totalFeet = 0;
int main()
{
cout << "Please enter the total number of feet: ";
cin >> totalFeet; // take in user input
// loop until the user enters correct init. integer value
while (cin.fail())
{
cout << "Invalid input!\n\n";
cin.clear(); // if the input is invalid, clear cin
cin.ignore(10, '\n'); // and ignore the last 10 characters or newline
cout << "Please enter the total number of feet: ";
cin >> totalFeet;
}
findSolutions(); // if totalFeet is valid, run at least once
while (keepGoing())
{ // while boolkeepGoing() yields true, keep running.
findSolutions();
}
}// end main()
bool keepGoing ()
{
char answer;
while (true)
{
cout << "Try another number?: [y/n]";
cin >> answer;
switch (answer) {
case 'y':
case 'Y':
cout << "Please enter an integer:";
cin >> totalFeet;
while (cin.fail())
{
cin.clear();
cin.ignore(10, '\n');
cout << "\n\nInvalid input!\n";
cout << "Please enter an integer:";
cin >> totalFeet;
}
return (true);
break;
case 'n':
case 'N':
return (false);
break;
default:
cout << "Invalid input!\n\n";
cin.clear();
cin.ignore(10, '\n');
break;
}
}
}
void findSolutions()
{
int solutions = 0;
int numRabbits = 0;
int numChicken = 0;
if (totalFeet > 0 && totalFeet%2 == 0)
{
for (int i = 0; i <= (totalFeet/RABBIT_FEET); i++)
{
numRabbits = i;
cout << "rabbit#: " << numRabbits;
solutions++;
for (int j = 0; j <= (totalFeet-(numRabbits*RABBIT_FEET)); j++)
{
numChicken = ((totalFeet-(numRabbits*RABBIT_FEET))/CHICKEN_FEET);
}
cout << " && chicken#: " << numChicken << "\n";
}
}
else if checkSolution(numRabbits, numChicken, totalFeet) != false)
{
cout << "\n\n--------------------------------------\n";
cout << "Total number of solutions found: " << solutions << endl;
}
else {
cout << "Error!";
}
}
/*
checkSolution will determine whether the given number of rabbits and chickens can result in a valid solution, based on the total number of feet. If the given number of rabbits and chickens is a valid solution, checkSolution will return true and you should output the solution to the screen. If checkSolution returns false, indicating that the given number of rabbits and chickens does not result in a valid solution, you should not output anything to the screen but you should move on to consider the next possible solution.
*/
bool checkSolution (int numRabbits, int numChicken, int totalFeet)
{
int temp;
temp = ((numRabbits*RABBIT_FEET) + (numChicken*CHICKEN_FEET));
return temp <= totalFeet;
}