16

Waterjug Algorithm

A C++ algorithm that solves a waterjug puzzle.

A C++ algorithm that solves a puzzle consisting of 3 jugs with set capacities of water in the least amount of moves.

Usage

./waterjug [Capacity A] [Capacity B] [Capacity C] [Goal A] [Goal B] [Goal C]

Explanation

The initial state of water has bucket A and B as empty, and bucket C is filled to capacity. The algorithm will find the combination of pours to reach the goal capacities in each bucket.

Example

./waterjug 1 3 4 0 2 2

Initial state: Jug A: 0 gallons, Jug B: 0 gallons, Jug C: 4 galllons
Capacities: Jug A can hold 1 gallon. Jug B can hold 3 gallons. Jug C can hold 4 gallons.
Goal: Jug A: 0 gallons, Jug B: 2 gallons, Jug C: 2 galllons

Steps to achieve the goal:

  • Pour from Jug C to Jug B

Jug A: 0 gallons, Jug B: 3 gallons, Jug C: 1 galllons

  • Pour from Jug B to Jug A

Jug A: 1 gallons, Jug B: 2 gallons, Jug C: 1 galllons

  • Pour from jug A to Jug C

Jug A: 0 gallons, Jug B: 2 gallons, Jug C: 2 galllons

Languages

C++