Rewrite the Jars problem to use a Jar class and a vector of
Jar objects
The Jar class has 2 private members - volume, capacity, a
default constructor, a 1 parameter constructor, 2 accessors but
only 1 mutator, two boolean methods isEmpty and IsFull, a 1 Jar
reference parameter method, pour, that pours the contents of its
parameter into the method's Jar.
/*
A man goes to a bathtub with two jars, of which one holds
exactly 3 pints and the other 5 pints.
How can be bring back exactly 4 pints of water. The solution
presents no difficulty.
Empty(source, destination)
Fill(source, destination)
Pour(source, destination)
while source is not empty and destination is not full
aubtract 1 from volume(source)
add 1 to volume(destination)
end while
End Pour
tub(capacity) = 8
jar1(capacity) = 5
jar2(capacity) = 3
tub(volume) = 8
jar1(volume) = 0
jar2(volume) = 0
display(count, tub, jar1, jar2)
count = 0
repeat
read source, destination
pour source, destination
count = count + 1
display(count, tub, jar1, jar2)
until jar1(volume) = 4
*/
#include <iostream>
#include <string>
using namespace std;
const int TUB = 0;
const int JAR1 = 1;
const int JAR2 = 2;
const int capacity[] = {8, 5 , 3};
const string names[] = {"Tub", "Jar 1", "Jar 2"};
int volume[] = {8, 0, 0};
void display(int count);
void read(int& source, int& destination);
void pour(int source, int destination);
bool isEmpty(int container);
bool isFull(int container);
int main()
{
int count = 0;
display(count);
do
{
int source, destination;
read(source, destination);
pour(source, destination);
count++;
display(count);
}
while(volume[JAR1] != 4);
system("pause");
return 0;
}
void pour(int source, int destination)
{
while(!isEmpty(source) && !isFull(destination))
{
volume[source]--;
volume[destination]++;
}
}
bool isEmpty(int container)
{
return volume[container] == 0;
}
bool isFull(int container)
{
return volume[container] == capacity[container];
}
void read(int& source, int& destination)
{
cout << "source? ";
cin >> source;
cout << names[source] << " is the source" <<
endl;
cout << "destination? ";
cin >> destination;
cout << names[destination] << " is the
destination" << endl;
}
void display(int count)
{
cout << count << ": ";
for(int index = TUB; index <= JAR2; index++)
cout << volume[index] << ' ';
cout << endl;
}