Search algorithms for the 8-puzzle solution
Heuristic.hpp
Go to the documentation of this file.
1 /**
2  * @author Douglas De Rizzo Meneghetti (douglasrizzom@gmail.com)
3  * @date 2017-6-22
4  * @brief Abtract class for heuristic functions.
5  */
6 
7 #ifndef SEARCH_HEURISTIC_HPP
8 #define SEARCH_HEURISTIC_HPP
9 
10 #include "Game.hpp"
11 
12 //!Abtract class for heuristic functions.
13 class Heuristic {
14  public:
15 
16  //! Calculates the heuristic value for a state.
17  //! \param currentState the state to be evaluated
18  //! \return heuristic value for currentState
19  virtual int calc(GameState &currentState) = 0;
20 };
21 
22 //! Implementation of the Manhattan distance for the 8-puzzle
23 class Manhattan : public Heuristic {
24  public:
25 
26  int calc(GameState &currentState) {
27  int distance = 0, dimension = currentState.getDimension();
28 
29  for (int i = 0; i < pow(dimension, 2); i ++) {
30  int *pos = currentState.find(i);
31  int x = pos[0], y = pos[1];
32  delete[] pos;
33  int x_opt = i != 0 ? (i - 1) / dimension : 2,
34  y_opt = i != 0 ? (i - 1) % dimension : 2;
35 
36  distance += abs(x - x_opt) + abs(y - y_opt);
37  }
38  return distance;
39  }
40 };
41 
42 //! Implementation of the tile difference heuristic for the 8-puzzle
43 class TileDifference : public Heuristic {
44  public:
45 
46  int calc(GameState &currentState) {
47  int distance = 0, dimension = currentState.getDimension();
48 
49  // adds 1 for every tile that is not in its goal position
50  for (int i = 0; i < pow(dimension, 2); i ++) {
51  int *pos = currentState.find(i);
52  int x = pos[0], y = pos[1];
53  delete[] pos;
54  int x_opt = i != 0 ? (i - 1) / dimension : 2,
55  y_opt = i != 0 ? (i - 1) % dimension : 2;
56 
57  distance += x != x_opt || y != y_opt;
58  }
59  return distance;
60  }
61 };
62 
63 #endif // SEARCH_HEURISTIC_HPP
Implementation of the tile difference heuristic for the 8-puzzle.
Definition: Heuristic.hpp:43
int getDimension() const
Definition: GameState.hpp:284
Implementation of the Manhattan distance for the 8-puzzle.
Definition: Heuristic.hpp:23
virtual int calc(GameState &currentState)=0
Calculates the heuristic value for a state.
int calc(GameState &currentState)
Calculates the heuristic value for a state.
Definition: Heuristic.hpp:46
int calc(GameState &currentState)
Calculates the heuristic value for a state.
Definition: Heuristic.hpp:26
Describes a single state in the 8-puzzle.
Definition: GameState.hpp:18
Abtract class for heuristic functions.
Definition: Heuristic.hpp:13