Created
April 23, 2013 14:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package defaultPackage; | |
public class Program { | |
public static void main(String args[]) { | |
WaterJug w = new WaterJug(); | |
w.checkGoal(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + "}"); | |
} | |
} |
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
It is not working when we take a_max=10 , b_max=4 , goal=7. It goes into infinite loop .