Monday, May 19, 2008

solving bucket measurement generically

public class Main {

private static final int RESULT = 4;
private static Bucket a = new Bucket("A", 0, 8);
private static Bucket b = new Bucket("B", 5, 5);
private static Bucket c = new Bucket("C", 3, 3);

public static void recurse(Bucket a, Bucket b, Bucket c) {
moveWaterFromXtoY(c,b);

if (b.current == RESULT){
print();
System.exit(0);
}

if (b.capacity == b.current){
moveWaterFromXtoY(b,a);
}else{
moveWaterFromXtoY(a,c);
}

recurse (a,b,c);

}

public static boolean moveWaterFromXtoY(Bucket X, Bucket Y) {
print();

// y is full.
if (Y.current == Y.capacity) {
return false;
}

if (X.current == 0) {
return false;
}

int totalWaterCanBeMoved= (Y.capacity-Y.current);

if (totalWaterCanBeMoved > X.current){
totalWaterCanBeMoved = X.current;
}

Y.current += totalWaterCanBeMoved;
X.current -=totalWaterCanBeMoved;

return true;
}

public static void main(String[] args) {

moveWaterFromXtoY(b,a);
moveWaterFromXtoY(c,a);

recurse(a, b, c);
}

public static void print(){
System.out.format("%2d %2d %2d\n", a.current, b.current , c.current);
}
}

class Bucket {
public int capacity;
public int current;
public String name;

public Bucket(String name, int current, int capacity) {
this.name = name;
this.current = current;
this.capacity = capacity;
}

public void print(){
System.out.println ("Bucket "+name + " has = " + current + " of " + capacity);
}
}