Добавление ArrayList не увеличивает список
Я пытаюсь решить проблему с 8 головоломками, используя эвристический поиск. Я использую матрицу 3*3, чтобы представить возможность. Код не завершен, но когда я пытаюсь добавить исследуемый элемент в исследуемый набор (который является ArrayList), он только обновляет текущий элемент в исследуемом наборе вместо добавления еще одного элемента в конец. Когда я пытаюсь распечатать все элементы в исследуемом наборе, всегда есть только один элемент (обновляется на каждой итерации). Мне интересно, что не так с моим кодом. Спасибо!!
public static void printexplored(ArrayList<int[][]> explored){
//System.out.println("the size of the explored set is " + explored.size());
System.out.println("the explored set is...");
while(explored.isEmpty() == false){
int[][] temp = explored.remove(0);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
}
}
public static boolean heuristicSearch(int initialState[][]){
Queue<int[][]> frontier = new LinkedList<int[][]>();
frontier.add(initialState);
ArrayList<int[][]> explored = new ArrayList<int[][]>();
int f_score = 0;
//int count = 0;
while(frontier.isEmpty() == false){
int[][] temporaryState = new int[3][3];
temporaryState = frontier.remove();
int indexX = blankIndexX(temporaryState);
int indexY = blankIndexY(temporaryState);
explored.add(temporaryState);
printexplored(explored);
2 ответа
В вашем методе печати вы удаляете элемент из списка.
Чтобы исправить, замените следующие строки в printexplored()
метод:
while(explored.isEmpty() == false){
int[][] temp = explored.remove(0);
для этого:
for (int i = 0; i < explored.size(); i++) {
int[][] temp = explored.get( i );
Ваш код неполон, но сразу бросается в глаза то, что вы одновременно добавляете и удаляете элемент в исследуемый список. Смотрите комментарии ниже:
public static void printexplored(ArrayList<int[][]> explored){
//System.out.println("the size of the explored set is " + explored.size());
System.out.println("the explored set is...");
while(explored.isEmpty() == false){
//---->YOU REMOVED THE ELEMENT WHICH WAS ADDED EARLIER HERE:
int[][] temp = explored.remove(0);
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(temp[i][j]);
}
System.out.println();
}
System.out.println();
}
}
public static boolean heuristicSearch(int initialState[][]){
Queue<int[][]> frontier = new LinkedList<int[][]>();
frontier.add(initialState);
ArrayList<int[][]> explored = new ArrayList<int[][]>();
int f_score = 0;
//int count = 0;
while(frontier.isEmpty() == false){
int[][] temporaryState = new int[3][3];
temporaryState = frontier.remove();
int indexX = blankIndexX(temporaryState);
int indexY = blankIndexY(temporaryState);
//---->YOU ARE ADDING AN ELEMENT HERE BUT REMOVING IT LATER IN THE THE
//printexplored METHOD:
explored.add(temporaryState);
printexplored(explored);