Professional Documents
Culture Documents
ASSIGNMENT
2.
(a) For a fixed N, there are (n-1) successor states
(b) Heuristic cost function (h) = the number of adjacent swaps needed to reach the goal
state
(c) It has no local minima since all local minima must also be global
(d)
(e)
Population Selection Crossover Mutation
53972 59 | 327 59 972 59932
59327 53 | 972 53 327 59327
53972 593 | 27 593 72 59372
59732 539 | 72 539 27 53227
3. Manhattan Distance: The sum of the vertical and horizontal distances from each tile to
their goal position.
pq.offer(root);
while(!pq.isEmpty()) {
State current = pq.poll();
if(current.cost == 0) {
System.out.println("SOLUTION FOUND!");
printPath(current);
System.out.println("Total Moves: "+current.step);
System.out.println("PATH: ");
return;
}//reach the goal state
for(int[] dir : DIR) {
int newX = current.x+dir[0];
int newY = current.y+dir[1];
if(isSafe(newX, newY)) {
State child = new State(current.matrix, current.x,current.y, newX, newY, curren-
t.step+1, current);
if(current.parent == null || !
getString(current.parent.matrix).equals(getString(child.matrix))) {
child.cost = calculateHammingCost(child.matrix, finalState);
pq.offer(child);
}
}
}
}
}
public boolean isSafe(int x, int y){
return (x >= 0 && x < len && y >= 0 && y < len);
}
public int calculateHammingCost(int[][] currentState, int[][] finalState) {
int cost = 0;
for(int i=0; i < len;i++) {
for(int j = 0; j < len;j++) {
if(currentState[i][j]!= 0 && currentState[i][j] != finalState[i][j]) {
cost++;
}
}
}
return cost;
}//calculate the cost using Hamming distance
System.out.println();
}
public void printMax(int[][] matrix) {
for(int i=0; i < len;i++) {
for(int j= 0; j < len; j++) {
System.out.print(matrix[i][j]);
}
System.out.println();
}
}
}
@Override
public int compareTo(State that) {
return (this.cost + this.step) - (that.cost+that.step);
}
}
OUTPUT
236 203 123
236 084 186 864
045 175 754 705
817
236 023 123
236 184 186 804
845 075 754 765
017
236 123 SOLUTION FOUND!
236 184 086 PATH: DRRULLDR-
845 705 754 RUULLDRDDLU
107
Total Moves: 19
236 123
236 184 806
845 750 754
170
236 123
236 180 860
840 754 754
175
230 123
236 186 864
804 754 750
175