是个倒油问题
有一位厨师要从12斤油(A桶)倒出6斤油但现在手里只有8斤和5斤的桶,怎么取出6斤
编译以后不显示输出 是不是哪里写错了求高手指点。。。。。。郁闷中
这是写的Set类
public class MySet{
//用来存放所有添加进来的对象, 初始长度为0表示开始是空的
private Object [] objs = new Object [0];
public boolean contains(Object obj){
for(Object tm : objs){
if(tm.equals(obj)){
return true;
}
}
return true;
}
public boolean add(Object obj){
//判断是否重复
if(contains(obj)){
return false;
}
//1: 创建一个新的数组,长度为原来数组长度加1
Object [] tempObjs = new Object [objs.length + 1];
//2:复制原来的数组对象到新的数组对象
System.arraycopy(objs,0,tempObjs,0,objs.length);
//3:把对象添加到新的数组的最后一个
tempObjs[objs.length] = obj;
//4:把新的数组赋值给原来的数组对象
objs = tempObjs;
return true;
}
public Object [] getAll(){
return objs;
}
public int getLen(){
return objs.length;
}
}
public class DaoYou{
public static void main(String[]args){
DaoYou t = new DaoYou();
t.t1();
}
//2:有一位厨师要从盛12斤的油(A桶)的桶中倒出6斤油来,可是手边只有盛8斤的
//油(B桶)和盛5斤油的(C桶)的两个桶,问如何操作才能将6斤取出来呢?
private void t1(){
Tong t1 =new Tong();
t1.max =12;
t1.now =12;
Tong t2 =new Tong();
t2.max = 8;
t2.now = 0;
Tong t3 =new Tong();
t3.max = 5;
t3.now = 0;
Tong []ts = new Tong[3];
ts[0] = t1;
ts[1] = t2;
ts[2] = t3;
MySet set = new MySet();
set.add(ts);
stepDaoYou(set);
}
private void stepDaoYou(MySet setKeNeng){
for(Object objs : setKeNeng.getAll()){
Tong ts[] = (Tong[])objs;
//1:判断是否已经完成
if(ts[0].now==6 || ts[1].now==6 || ts[2].now==6){
System.out.println("倒油完成----"+ts[0]+","+ts[1]+","+ts[2]);
}
//2:递归
stepDaoYou(keNengDaoYou(ts));
}
}
MySet yiDao = new MySet();
private MySet keNengDaoYou(Tong[]ts){
MySet setKeNeng = new MySet();
System.out.println("a"+ts[0].now+"b"+ts[1].now+"c"+ts[2].now);
for(int i=0;i<ts.length;i++){
for(int j=0;j<ts.length;j++){
//1:不能自己给自己倒
if(i==j){
continue;
}
//2:算出能倒多少
int canDaoYou = ts[i].canOut();
if(ts[i].canOut()>ts[j].canIn()){
canDaoYou = ts[j].canIn();
}
//3:模拟倒
ts[i].out(canDaoYou);
ts[j].in(canDaoYou);
//4:判断这个倒油的步骤是否已经出现过了
if(yiDao.contains("A="+ts[0].now+"B="+ts[1].now+"C="+ts[2].now)){
//已经出现了,不能这么倒,否则死循环了。
//还回去
ts[i].in(canDaoYou);
ts[j].out(canDaoYou);
//
continue;
}
//5:说明可以这么倒油
//5.1:先在已倒里面加入新的可能的倒油情况
yiDao.add("A="+ts[0].now+"B="+ts[1].now+"C="+ts[2].now);
//5.2添加可能性
Tong newTs[] = new Tong[3];
Tong t1 = new Tong();
t1.max = ts[0].max;
t1.now = ts[0].now;
Tong t2 = new Tong();
t2.max = ts[1].max;
t2.now = ts[1].now;
Tong t3 = new Tong();
t3.max = ts[2].max;
t3.now = ts[2].now;
newTs[0] = t1;
newTs[1] = t2;
newTs[2] = t3;
setKeNeng.add(newTs);
//6:把油还回去
ts[i].in(canDaoYou);
ts[j].out(canDaoYou);
}
}
return setKeNeng;
}
}
class Tong{
//最大值
public int max = 0;
//当前值
public int now = 0;
public void in(int a ){
now +=a;
}
public void out(int a ){
now -=a;
}
public int canIn(){
return(max - now );
}
public int canOut(){
return now;
}
}