gpt4 book ai didi

java - 数组仅填充最后一个元素

转载 作者:行者123 更新时间:2023-11-30 06:46:14 25 4
gpt4 key购买 nike

我正在尝试解决 8-puzzle ,我正在尝试为空白图 block 的移动生成可能的棋盘配置。我将在拼图数组中返回这些配置,并将板配置作为数据。当我运行下面的代码时,它仅在空白图 block 有多个移动的情况下存储空白图 block 的最后一个移动。我不知道如何阻止它覆盖以前的数组数据。

public Puzzle[] getNextPuzzle(Puzzle current) {

//returns list of indicies representing moves as integers
int[] ms = current.possibleMoves();
//trims the previous move so we don't move backwards
int[] moves = current.removeLastCase(ms);
//return all possible configurations of puzzles based on moves
Puzzle[] ret = new Puzzle[moves.length];
for(int i = 0; i < ret.length; i++) {
ret[i] = new Puzzle();
//set array puzzle configuration to current configuration
ret[i].setPuzzle(current.getPuzzle());
//***System.out.Print(current.getPuzzle());
//returns array index where blank tile is
int num = ret[i].indexOf(0);
//swaps the indices passed in: numbered instruction index and blank tile
ret[i].swap(moves[i], num);
}
return ret;
}

Public class Puzzle {
int[] puzzle = new int[9];
public void swap(int locA, int locB) {
int temp = this.puzzle[locB];
this.puzzle[locB] = this.puzzle[locA];
this.puzzle[locA] = temp;
}
public int indexOf(int n) {
//will be out of bounds
int ret = 10;
for (int i = 0; i < this.puzzle.length; i++) {
if (this.puzzle[i] == n) {
ret = i;
}
}
return ret;
}
}

示例输出:

//current configuration
1 4 2
3 0 5
6 7 8
//is solvable
true
//indices of possible moves of blank tile
toRemove[0] 1
toRemove[1] 3
toRemove[2] 5
toRemove[3] 7
//indices with previous state removed for disallow of backwards
ret[0] 3
ret[1] 5
ret[2] 7
//this is being printed out where the *** is
142305678
142035678
142530678
//what is returned in the array at the very end, expected is 3 different configurations
1 4 2
5 3 7
6 0 8

1 4 2
5 3 7
6 0 8

1 4 2
5 3 7
6 0 8

最佳答案

问题在于您正在创建当前谜题的浅拷贝,因此您在每个循环中更改当前谜题。相反,您应该创建当前谜题的深拷贝,并保持当前谜题完好无损。我不知道您的 Puzzle 类的完整实现,但您可能想检查您的构造函数和 setter 方法。

为 Puzzle 创建一个新的构造函数:

public Puzzle (int[] puzzle) { 
//this creates a deep copy
this.puzzle = new int[puzzle.length];
for (int i = 0; i < puzzle.length; ++i) {
this.puzzle[i] = puzzle[i];
}
}

然后替换以下行:

ret[i] = new Puzzle();
//set array puzzle configuration to current configuration
ret[i].setPuzzle(current.getPuzzle());

与:

ret[i] = new Puzzle(current.getPuzzle());

为了更好地解释深拷贝和浅拷贝,我推荐 this post .

关于java - 数组仅填充最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43650731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com