ai-22 / src / am / aua / npuzzle / MisplacedTilesHeuristic.java
MisplacedTilesHeuristic.java
Raw
package am.aua.npuzzle;

import am.aua.search.GoalTest;
import am.aua.search.Node;
import am.aua.search.NodeFunction;

import static am.aua.utils.ArrayUtils.getCol;
import static am.aua.utils.ArrayUtils.getRow;

/**
 * Heuristic 1.
 */
public class MisplacedTilesHeuristic implements NodeFunction {
    private GoalTest goalTest;

    public MisplacedTilesHeuristic(GoalTest goalTest) {
        this.goalTest = goalTest;
    }

    @Override
    public int eval(Node n) {
        Tiles tiles = (Tiles) n.state;
        TilesGoalTest tilesGoalTest = (TilesGoalTest) goalTest;
        int misplaced = 0;
        for (int i = 0; i < tiles.width * tiles.width; i++) {
            int cell = tilesGoalTest.GOAL[i];
            int col = i % tiles.width;
            int row = i / tiles.width;
            if (cell != Tiles.EMPTY_TILE
                && !(col == getCol(cell, tiles.tiles, tiles.width) && row == getRow(cell, tiles.tiles, tiles.width))) {
                misplaced += 1;
            }
        }
        return misplaced;
    }
}