Calculate the optimal solution of the water pouring problem of the logic question of the interview:
/** * Algorithms and principles * * / public int [] rsa ( int [] data) { / ** * Logic question: There are two water cups, one is aL and the other is bL, water can be used casually, how to get cL * That is to use the principle of full in and out, either aL is full back to bL, or bL is full back to aL cycle to get * that is satisfied: ax-by=c/bx-ay=c * Regarding the number of times each cup is full, x/y is set to no more than 100 by default * */ int a=data[0]; int b=data[1]; int c=data[2]; int sum=0; for(int x=0;x<100;x++) { for(int y=0;y<100;y++) { if(a*x-b*y==c) { sum=x+y; //返回a,b,x,y,sum int [] datas= {a,b,x,y,sum}; return datas; } } } return data; } /** * call the method, * Because there are two possibilities, that is, calling twice, the second time the ab order is exchanged and assigned * */ public void use( int [] data) { int a=data[0 ]; int b=data[1 ]; int c=data[2 ]; // call int [] data1= {a, b,c}; int [] data2= {b,a,c}; // Get the returned array int [] s1 = rsa(data1); int [] s2= rsa(data2); // Judge the total number of steps and find the optimal solution if (s1[4]<s2[4 ]) { String message=s1[0]+"升倒"+s1[1]+"升:x="+s1[2]+",y="+s1[3]; System.out.println(message); }else { String message=s2[0]+"升倒"+s2[1]+"升:x="+s2[2]+",y="+s2[3]; System.out.println(message); } } }
Test example:
public static void main(String[] args) { dsUtils test = new dsUtils(); // Pass the capacity of the two cups and the capacity to be taken int [] data= {11,7,2 }; test.use(data); }
Test Results:
If you don't need to find the optimal solution of the two methods, you don't need to be so troublesome:
public class dsUtil { /** * Algorithms and principles * */ public void rsa(int a,int b,int c) { /** * Logic question: There are two water cups, one is aL and the other is bL, water can be used casually, how to get cL * That is to use the principle of full in and out, either aL is full back to bL, or bL is full back to aL cycle to get * that is satisfied: ax-by=c/bx-ay=c * Regarding the number of times each cup is full, x/y is set to no more than 100 by default * */ for(int x=0;x<100;x++) { for(int y=0;y<100;y++) { if(a*x-b*y==c) { String message=a+"升倒"+b+"升:x="+x+",y="+y; System.out.println(message); return; } } } } /** * call the method, * Because there are two possibilities, that is, calling twice, the second time the ab order is exchanged and assigned * */ public void use(int a,int b,int c) { rsa(a,b,c); rsa(b,a,c); } }
Test Results:
Reference: https://www.cnblogs.com/j-star/p/7127190.html