- Related Questions & Answers
- Measure execution time with high precision in C/C++
- How to measure time taken by a function in C?
- Java Program to check if a Float is Infinite or Not a Number(NAN)
- How to generate Infinite Stream of Integers in Java using IntStream.iterate()
- Generate Infinite Stream of Integers in Java using IntStream.generate()
- How to generate Infinite Stream of Double in Java using DoubleStream.generate()
- Generate Infinite Stream of Integers in Java using Random.ints()
- Generate Infinite Stream of Double in Java using DoubleStream.iterate()
- Why a living person sinks and a dead person floats in water?
- What is the measure for ozone layer?
- How does the water inside a clay pot get cold?
- What measures can we take to conserve water?
- How to use the water high in fluoride content for all purposes?
- Can the new Edible water bottle replace plastic bottles in the future?
- How to purify water at home without a water purifying machine?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

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

#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; }

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

Advertisements