- fixed heuristic for puzzle8
- fixed test
This commit is contained in:
2024-01-11 10:26:20 +01:00
parent 569f902126
commit 732d9eed20
2 changed files with 3 additions and 5 deletions

View File

@@ -26,8 +26,9 @@ public class Puzzle8 implements Iterable<Integer> {
for(var i = 0; i < n; i++) index[p1.puzzle[i]] = i;
for(var i = 0; i < n; i++) {
var curr = p2.puzzle[i];
var i2 = index[curr];
if(curr == 0) continue;
var i2 = index[curr];
sum += Math.abs((i / LENGTH) - (i2 / LENGTH)) + Math.abs((i % LENGTH) - (i2 % LENGTH));
}
return sum;
@@ -265,7 +266,7 @@ public class Puzzle8 implements Iterable<Integer> {
public List<Move> solve(Puzzle8 goal) {
if(!this.isSolvable(goal)) return null;
var aStar = new AStar<Puzzle8, Move>(Puzzle8::availableMoves, (p, m) -> new Puzzle8(p, m));
var aStar = new AStar<Puzzle8, Move>(Puzzle8::availableMoves, Puzzle8::new);
aStar.setHeuristic(HEURISTIC_MANHATTAN);
return aStar.solve(this, Objects.requireNonNull(goal));

View File

@@ -126,11 +126,8 @@ public class TestPuzzle {
public void testSolve() {
var puzzle = new Puzzle8(3,5,6,1,2,4,0,7,8);
var puzzleGoal = new Puzzle8(1,2,3,4,5,6,7,8,0);
var solution = new Puzzle8.Move[] {RIGHT, UP, RIGHT, UP, LEFT, LEFT, DOWN, RIGHT, DOWN, RIGHT, UP, UP, LEFT, DOWN, RIGHT, DOWN};
var actual = puzzle.solve(puzzleGoal).toArray(new Puzzle8.Move[0]);
assertArrayEquals(solution, actual);
for(var move : actual) puzzle.move(move);
assertEquals(puzzleGoal, puzzle);
}