1

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;
}
  • Why does your code gets stuck in an infinite loop when you have limited it to `100000`? – Eric B. Dec 22 '15 at 09:49
  • it's heuristic has always gets caught between two values. the point is it never solves puzzle and gets caught between few states –  Dec 22 '15 at 09:51
  • Then you should try to remember your state. You could create a list of all the possible states already used, and when determining the next state, check whether it was already used or not. – Eric B. Dec 22 '15 at 09:54
  • 2
    I would recommend to determine the correctness of your code, you minimize your code and use it for a 4-Puzzle, and see if it returns correct output for that. – Eric B. Dec 22 '15 at 09:55
  • if i prevent from going to previous state (by having a list of previous states) it most of the times get caught in corner. because sometimes it has to get back to previous state and select another choice. –  Dec 24 '15 at 19:00

0 Answers0