Search code examples
prologswi-prolog

[Prolog]: Keep only the minimum length list from the predicates result


I solved a maze problem in prolog but I want to keep only the smallest path that the program returns. Is there a way to find the minimum length for the Path List Variable and return only that? I've googled it but there is no answer I understand, maybe because of my level of experience.

 solve_maze(Path) :- solve_maze_helper(Path).

As of right now, the answers are:

   [3/2, 4/2, 4/3, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 2/6]

   [3/2, 4/2, 4/3, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 1/7, 2/7, 2/6]

   [3/2, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 2/6]

   [3/2, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 1/7, 2/7, 2/6]

   [3/2, 3/1, 4/1, 4/2, 4/3, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 2/6]

   [3/2, 3/1, 4/1, 4/2, 4/3, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 1/7, 2/7, 2/6]

and I only for instance want the number 3.

Thanks in advance!


Solution

  • Try querying ?- length(Items, _). and see how it generates an empty list, then when you retry it makes length one, retry again and it makes length two, and keeps making the list longer. Use this idea to constrain the Path to find short solutions first:

    solve_maze(Path) :-
        length(Path, _),
        solve_maze_helper(Path).
    

    Path must first be length 0, and then the solution must fit in it. No solutions. Path must be length 1, no solutions. Path must be length 2, no solutions. When it gets to Path length 8, hopefully it will find [3/2, 3/3, 2/3, 1/3, 1/4, 1/5, 1/6, 2/6] your shortest path.

    (This technique is what The Power of Prolog calls "Iterative Deepening", looking for shallow solutions, and gradually digging deeper into the search space over and over).