Skip to content

Instantly share code, notes, and snippets.

@psaitu
Created April 23, 2013 14:19
Show Gist options
  • Save psaitu/5443952 to your computer and use it in GitHub Desktop.
Save psaitu/5443952 to your computer and use it in GitHub Desktop.
A simple implementation of the water jug algorithm, works on the principle of repeatedly filling only one jug.
package defaultPackage;
public class Program {
public static void main(String args[]) {
WaterJug w = new WaterJug();
w.checkGoal();
}
}
package defaultPackage;
import java.util.*;
public class WaterJug {
int a_max = 2;
int b_max = 1;
int a = 0;
int b = 0;
int goal = 1;
void checkGoal() {
int fin = 0;
while(fin != 1) {
if((this.a == this.goal) || (this.b == this.goal)) { fin = 1; }
if(this.a==0) {
fillA();
} else if ((this.a > 0) && (this.b != this.b_max)) {
transferAtoB();
} else if ((this.a > 0) && (this.b == this.b_max)) {
emptyB();
}
}
}
void fillA() {
this.a = this.a_max;
System.out.println("{" + this.a + "," + this.b + "}");
}
void fillB() {
this.b = this.b_max;
System.out.println("{" + this.a + "," + this.b + "}");
}
void transferAtoB() {
int fin = 0;
while(fin != 1) {
this.b += 1;
this.a -= 1;
if((this.b == this.b_max) || (this.a == 0)) { fin = 1;}
}
System.out.println("{" + this.a + "," + this.b + "}");
}
void emptyA() {
this.a=0;
System.out.println("{" + this.a + "," + this.b + "}");
}
void emptyB() {
this.b=0;
System.out.println("{" + this.a + "," + this.b + "}");
}
}
@gouravpatidar13
Copy link

It is not working when we take a_max=10 , b_max=4 , goal=7. It goes into infinite loop .

@Jaykumarsanandiya
Copy link

because 10m +4b != 7 according to the extended Euclidian Algorithm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment