本帖最后由 TS__likewise 于 2014-5-22 10:00 编辑
import java.util.ArrayList;
import java.util.Random;
class TNT {
public static void main(String[] args) {
doTransport();
}
public static void doTransport() {
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
arr1.add("鱼");
arr1.add("猫");
arr1.add("狗");
System.out.println("农夫,猫,鱼,狗都在此岸,开始过河.\n");
String[] boat ={"-","-"};
while (arr1.size() > 0) {
move(arr1, arr2, boat);
}
System.out.println("\n农夫,猫,鱼,狗都到达彼岸.");
}
public static void move(ArrayList<String> arr1, ArrayList<String> arr2,String[] boat) {
if (boat[0].equals("-")) {
int one=0;
do{
one = new Random().nextInt(arr1.size());
}while(arr1.get(one).equals(boat[1]));
boat[1]=boat[0];
boat[0] = arr1.get(one);
arr1.remove(one);
}
if (ifNice(arr1)) {
arr2.add(boat[0]);
System.out.println("--->农夫带" + boat[0] + "去彼岸 ");
if(arr2.size()==3){
return;
}
if (ifNice(arr2)) {
boat[1]=boat[0];
boat[0] ="-";
System.out.println(" 农夫单独回此岸<---");
} else {
boat[0]=arr2.get(0);
System.out.println(" 农夫带" +boat[0]+ "回此岸<---");
arr2.remove(0);
arr1.add(boat[0]);
boat[1]=boat[0];
boat[0]="-";
}
} else {
arr1.add(boat[0]);
boat[1]=boat[0];
boat[0]="-";
}
}
public static boolean ifNice(ArrayList<String> arr) {
if ((arr.contains("猫") && arr.contains("狗"))
|| (arr.contains("鱼") && arr.contains("猫"))) {
return false;
} else {
return true;
}
}
} |