public class Test10 {
public static void main(String[] args) {
List<String> left = new ArrayList<String>();
List<String> right = new ArrayList<String>();
left.add( "猫" );
left.add( "狗" );
left.add( "鱼" );
int useBoat = 0;
String animal = null;
while( !left.isEmpty() ){
useBoat++;
animal = null;
if( 1 == useBoat % 2 ){
for( int i = 0; i < left.size(); i++ ){
animal = left.remove( i );
if( lossAnimal(left) ){
left.add( animal );
continue;
}else{
break;
}
}
System.out.println( "第" + useBoat + "次, 老农用船将" + animal + "运到河右岸" );
right.add( animal );
}else {
while( lossAnimal(right) ){
for( int i = 0; i < right.size(); i++ ){
animal = right.remove( i );
if( lossAnimal(right) ){
right.add( animal );
continue;
}else{
break;
}
}
}
if( animal == null ){
System.out.println( "第" + useBoat + "次, 老农用船回到河左岸" );
}else{
System.out.println( "第" + useBoat + "次, 老农用船将" + animal + "运回河左岸" );
left.add( animal );
}
}
}
}
public static boolean lossAnimal( List<String> list ){
if( list.contains("猫") && list.contains("狗") ){
return true;
}else if( list.contains("猫") && list.contains("鱼") ){
return true;
}else{
return false;
}
}
}
|