In the movie "Die Hard with a Vengeance" (starring Bruce Willis and Samuel Jackson), the heros are faced with the prospect of a bomb exploding unless they can determine how to measure exactly 4 gallons of water using two jugs that hold exactly 5 gallons and 3 gallons respectively. Fortunately, this problem is very simple and easily solved in the 30 seconds or so given in the movie, but what will happen in "Die Hard with a Terrible Vengeance", when the jugs may be much bigger and the problem much harder? Obviously the police need an automated solution to the "jug" problem.
Unlike the scene in the movie, in which any solution was sufficient, we want our automated system to produce the best solution, ie. the one that requires the least heavy lifting of water jugs. Furthermore, we'd like to know the best solution for any given initial configuration of water in the two jugs. (In the movie both jugs were empty initially.)
The general problem to be solved is this: given an (essentially) infinite supply of water and two jugs holding exactly B and S gallons (where B > S), show how to get exactly P gallons (P <= B) in one of the jugs using the following six operations:
We can model this problem using a graph. Each node in the graph is a pair (b,s) where
There is a directed arc between two nodes (x,y) and (u,v) if, given x gallons in the jug that holds at most B gallons, and y gallons in the jug that holds at most S gallons, we can perform any one of the six operations listed above (i.e., empty either jug, fill either jug, pour from one jug to another) and end up with u gallons in the big jug and v gallons in the small jug.
Each operation has an associated weight, which is proportional to the effort required to lift the water used in that operation. So, in the graph, each arc has a weight corresponding to the number of gallons lifted. The weights are defined as follows:
In this graph representation, any node of the form (P,k) or (j,P) represents a solution to the problem of P gallons, since one of the jugs holds exactly P gallons.
So, given two jugs that hold B and S gallons, and an initial configuration (b,s), where the large jug has b gallons and the small jug has s gallons, you are to find the sequence of operations requiring the least effort (as determined by the weights of the operations) that produces P gallons in one of the jugs.
That is, you are to write a program with five inputs B, S, b, s, and P, which builds the graph of B x S nodes, and finds the shortest path between (b,s) and (j,k), for some j and k, where j=P or k=P.
Extra Fun for Extra Credit:
This assignment is due at the start of class on Tuesday, Feb 16.