WATER JUG PROBLEM C++ CODE
#include<iostream>
using namespace std;
#include<conio.h>
int in1[20], in2[20];
void main()
{
float J1, J2, j1 = 0, j2 = 0, j1_max, j2_max, J1_goal;
int i, j, choice, pos = 0;
in1[0] = 4;
in2[0] = 3;
pos++;
in1[pos] = 0;
in2[pos] = 0;
pos++;
cout << "Enter max volume of JUG1: ";
cin >> j1_max;
cout << "Enter max volume of JUG2: ";
cin >> j2_max;
cout << "Enter Goal state for JUG1: ";
cin >> J1_goal;
cout << "\nInitial State: 0 0";
cout << "\nFinal State: " << J1_goal << "\t n";;
cout << "\nJUG1 JUG2 ";
choice = 1;
cout << "\n " << j1 << " " << j2;
while (1)
{
J1 = j1;
J2 = j2;
switch (choice)
{
case 1:
{
if (j1 < j1_max)
{ j1 = j1_max; }
choice++;
}
break;
case 2:
{
if (j2 < j2_max)
{ j2 = j2_max; }
choice++;
}
break;
case 3:
{
if (j1>0)
{j1 = 0; }
choice++;
}
break;
case 4:
{
if (j2 > 0)
{ j2 = 0;}
choice++;
}
break;
case 5:
{
if ((j1 + j2 >= j1_max) && (j2 > 0))
{
j2 = j2 - (j1_max - j1);
j1 = j1_max;
}
choice++;
}
break;
case 6:
{
if ((j1 + j2 >= j2_max) && (j1 > 0))
{
j1 = j1 - (j2_max - j2);
j2 = j2_max;
}
choice++;
}
break;
case 7:
{
if ((j1 + j2 <= j1_max) && (j2 > 0))
{
j1 = j1 + j2;
j2 = 0;
}
choice++;
}
break;
case 8:
{
if ((j1 + j2 <= j2_max) && (j1 > 0))
{
j2 = j1 + j2;
j1 = 0;
}
choice++;
}
case 9:
{
if ((j2 == J1_goal) && (j1 == 0))
{
j2 = j1;
j1 = J1_goal;
}
choice++;
}
default:
{
choice = 1;
}
}
for (i = 0; i < pos; i++)
{
if ((in1[i] == j1) && (in2[i] == j2))
{
j1 = J1;
j2 = J2;
break;;
}
}
if (i == pos)
{
in1[pos] = j1;
in2[pos] = j2;
pos++;
cout << "\n " << j1 << " " << j2;
}
if (j1 == J1_goal)
{
cout << "\nDONE";
exit(1);
}
}
getch();
}
OUTPUT
Enter max volume of JUG1:
4
Enter max volume of JUG2:
3
Enter Goal state for
JUG1: 2
Initial State: 0 0
Final State: 2 n
JUG1 JUG2
0
0
4
0
1
3
0
3
3
0
3
3
4
2
0
2
2
0
DONEPress any key to
continue . . .
No comments:
Post a Comment