i am trying to write algorithm to solve random 8-puzzles with hill climbing. i have wrote it using first choice,best choice and random restart but they always caught in infinite loop.any way to prevent that? also when generating random puzzles i used an algorithm to make sure all of puzzles produced are solvable. so there is no problem on the matter of solvability. here is the function for random restart kind which should solve 8 puzzles on nearly 100% of puzzles:
public static bool HillClimbingRandomRestart(int[,] _state)
{
int[,] _current = _state;
int hMax = Problem.GetHeuristic(_state);
int Counter = 0;
int _h = hMax;
int[,] _best = _current;
int[,] _next = _current;
while (Counter < 100000)
{
Counter++;
if (isGoal(_current))
return true;
foreach (Move suit in Enum.GetValues(typeof(Move)))
{
_next = Problem.MoveEmptyTile(_current, suit);
if (_next == null)
continue;
_h = Problem.GetHeuristic(_next);
if (_h < hMax)
{
hMax = _h;
_best = _next;
}
}
if (_current == _best)
{
Random rnd = new Random();
int[,] _nextRandom = Problem.MoveEmptyTile(_current, (Move)rnd.Next(4));
while(_nextRandom==null)
_nextRandom = Problem.MoveEmptyTile(_current, (Move)rnd.Next(4));
_current = _nextRandom;
}
else
_current = _best;
hMax = Problem.GetHeuristic(_current);
}
return false;
}