-
Notifications
You must be signed in to change notification settings - Fork 45
/
Water_Jug.cpp
124 lines (103 loc) · 1.92 KB
/
Water_Jug.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
using namespace std;
class Jug{
int capacity;
int value;
public:
Jug(int n)
{
capacity = n;
value = 0;
}
void Fill()
{
value = capacity;
}
void Empty()
{
value = 0;
}
bool isFull()
{
return value >= capacity;
}
bool isEmpty()
{
return value == 0;
}
//A[B] -> Transfer contents of B to A until A is full
void operator[](Jug &B)
{
int old_value = value;
value = value + B.value;
value = value > capacity?capacity:value;
B.value = B.value - (value - old_value);
}
int getValue()
{
return value;
}
};
int gcd(int n,int m)
{
if(m<=n && n%m == 0)
return m;
if(n < m)
return gcd(m,n);
else
return gcd(m,n%m);
}
bool check(int a,int b,int c){
//boundary cases
if(c>a){
cout<<"A can't hold more water than it's capacity!\n";
return false;
}
//if c is multiple of HCF of a and b, then possible
if(c % gcd(a,b) == 0){
return true;
}
//if c is not multiple of HCF of a and b, then not possible
cout<<"Can't reach this state with the given jugs\n";
return false;
}
void solve(Jug A, Jug B, int result)
{
while(A.getValue() != result)
{
if(!A.isFull() && B.isEmpty()){
cout<<"Fill B\n";
B.Fill();
cout << "(A, B) = (" << A.getValue() << ", " << B.getValue() << ")\n";
}
if(A.isFull()){
cout<<"Empty A\n";
A.Empty();
cout << "(A, B) = (" << A.getValue() << ", " << B.getValue() << ")\n";
}
cout<<"Pour from B into A\n";
A[B];
cout << "(A, B) = (" << A.getValue() << ", " << B.getValue() << ")\n";
}
}
int main()
{
int a, b, result;
cout<<"Enter capacity of A\n";
cin >> a;
cout<<"Enter capacity of B\n";
cin >> b;
do{
cout<<"Enter required water in A:\n";
cin >> result;
}
while(!check(a,b,result));
Jug A(a), B(b);
cout << "\n(A, B) = (" << A.getValue() << ", " << B.getValue() << ")\n";
solve(A, B, result);
cout<<"Done!"<<endl;
#ifdef _WIN32
system("pause");
#endif
return 0;
}