Skip to content

Instantly share code, notes, and snippets.

@therajanmaurya
Created August 31, 2015 09:23
Show Gist options
  • Save therajanmaurya/e5d5a2ae8162217fe617 to your computer and use it in GitHub Desktop.
Save therajanmaurya/e5d5a2ae8162217fe617 to your computer and use it in GitHub Desktop.
Water Jug Problem
import java.util.Scanner;
public class waterjug {
Scanner scan=new Scanner(System.in);
int maxA,maxB,desA,desB,a,b;
public static void main(String args[])
{
System.out.println("*** Water Jug ***\n\n");
waterjug jug=new waterjug();
jug.input();
jug.mix();
}
void input()
{
System.out.println("Enter the capacity of the bigger jug.");
maxA=scan.nextInt();
System.out.println("Enter the capacity of the smaller jug.");
maxB=scan.nextInt();
desA=maxA+1;
desB=maxB+1;
while(desA>maxA || desB>maxB)
{
System.out.println("Enter the desired water in the bigger jug.");
desA=scan.nextInt();
// Setting value desB =0;
desB = 0;
}
}
void mix()
{
a=0;
b=0;
while(a!=desA || b!=desB)
{
if(b==0)
{
fillB();
}
else if(a<maxA && b>0)
{
B2A();
}
else if(a==maxA)
{
emptyA();
}
System.out.println(a+","+b);
}
}
void fillB()
{
b=maxB;
}
void B2A()
{
while(a!=maxA && b!=0)
{
a++;
b--;
}
}
void emptyA()
{
a=0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment