我在为我的AI课编写一段代码,旨在列出给定三个水壶的水壶问题的所有可能状态(你可以填充任何一个水壶,或者将一个水壶中的水尽可能多地倒入另一个水壶中,或者清空任何一个水壶,可以随意进行多次操作且顺序不限),初始状态是所有水壶都是空的。
不知为何,在记录了88个看似不同的状态后,第89个状态与第一个相同,导致程序因为循环而耗尽空间。
我认为问题可能出在检查状态是否不同的方式上,但无法找出具体原因。任何帮助都将不胜感激。
import java.util.ArrayList; import java.util.List;public class AI { private static final int[] start=new int[]{0,0,0}; private static int[] jugs; public static void main(String[] args){ jugs=new int[]{Integer.parseInt(args[0]), Integer.parseInt(args[1]),Integer.parseInt(args[2])}; String out=""; out=out.concat("{"); for (int[] state:addStates(start,new ArrayList<>())) { out=out.concat("{"+state[0]+","+state[1]+","+state[2]+"}"); } out=out.substring(0,out.length()-2).concat("}"); System.out.println(out);}private static List<int[]> addStates(int[] start, List<int[]> states) { states.add(start); int[][] newStates={ fillA(start), fillB(start), fillC(start), emptyA(start), emptyB(start), emptyC(start), pour(start,0,1), pour(start,0,2), pour(start,1,0), pour(start,1,2), pour(start,2,0), pour(start,2,1) }; for (int[] child:newStates) { if (!has(states,child)) { states.addAll(addStates(child,states)); } } System.out.println("close"); return states;}private static boolean has(List<int[]> list, int[] e) { //finds out if list contains something with the same values as e for (int[] el:list) { boolean is=true; for(int i=0;i<e.length;i++){ if (el[i]!=e[i]){ is=false; } } if(is){ return true; } } return false;}private static int[] fillA(int[] state) { return new int[]{jugs[0],state[1],state[2]};} //fills Aprivate static int[] fillB(int[] state) { return new int[]{state[0],jugs[1],state[2]};} //fills Bprivate static int[] fillC(int[] state) { return new int[]{state[0],state[1],jugs[2]};} //fills Cprivate static int[] emptyA(int[] state) { return new int[]{0,state[1],state[2]};} //empties Aprivate static int[] emptyB(int[] state) { return new int[]{state[0],0,state[2]};} //empties Bprivate static int[] emptyC(int[] state) { return new int[]{state[0],state[1],0};} //empties Cprivate static int[] pour(int[] state, int from, int into) { int currentInto=state[into]; int currentfrom=state[from]; if (currentInto+currentfrom>jugs[into]){ currentfrom-=(jugs[into]-currentInto); currentInto=jugs[into]; } else { currentInto+=currentfrom; currentfrom=0; } int[] newState= new int[3]; newState[from]=currentfrom; newState[into]=currentInto; newState[3-from-into]=state[3-from-into]; return newState;} //moves as much water from "from" into "into"
}
回答:
问题在于我同时使用了states.add(start)
和states.addAll(addStates(child,states))
,这意味着我重复添加了大量元素。修复这个问题后,代码运行得非常好。