Measure one litre using two vessels and infinite water supplys in C++

C++Server Side ProgrammingProgramming

Problem statement

There are two vessels of capacities ‘a’ and ‘b’ respectively. We have an infinite water supply. Give an efficient algorithm to make exactly 1 liter of water in one of the vessels. You can throw all the water from any vessel at any point in time. Assume that ‘a’ and ‘b’ are Coprimes.

Algorithm

Let V1 be the vessel of capacity ‘a’ and V2 be the vessel of capacity ‘b’ and ‘a’ is smaller than ‘b

1. Do following while the amount of water in V1 is not 1 −
   a. If V1 is empty, then completely fill V1
   b. Transfer water from V1 to V2. If V2 becomes full, then keep the remaining water in V1 and empty V2
2. V1 will have 1 litre after termination of loop in step 1

Example

 Live Demo

#include <iostream>
using namespace std;
int gcd(int a, int b){
   return b ? gcd(b, a % b) : a;
}
class Vessel{
   int capacity, current;
   public:
      Vessel(int capacity){
         this->capacity = capacity;
         current = 0;
      }
   void makeOneLitre(Vessel &V2);
   int transfer(int amount);
};
void Vessel:: makeOneLitre(Vessel &V2){
   if (gcd(capacity, V2.capacity) != 1) {
      return;
   }
   while (current != 1) {
      if (current == 0) {
         current = capacity;
      }
      cout << "Vessel 1: " << current << " Vessel 2: " << V2.current << endl;
      current = current - V2.transfer(current);
   }
   cout << "Vessel 1: " << current << " Vessel 2: " << V2.current << endl;
}
int Vessel::transfer(int amount){
   if (current + amount < capacity) {
      current += amount;
      return amount;
   }
   int transferred = capacity - current;
   current = 0;
   return transferred;
}
int main(){
   int a = 3, b = 7;
   Vessel V1(a), V2(b);
   V1.makeOneLitre(V2);
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Vessel 1: 3 Vessel 2: 0
Vessel 1: 3 Vessel 2: 3
Vessel 1: 3 Vessel 2: 6
Vessel 1: 2 Vessel 2: 0
Vessel 1: 3 Vessel 2: 2
Vessel 1: 3 Vessel 2: 5
Vessel 1: 1 Vessel 2: 0
raja
Published on 10-Feb-2020 10:13:03
Advertisements