How can I get my maze program to create and print two route-lists to the console?

戏子无情 提交于 2021-01-28 11:27:19

问题


link(entry, a).
link(a, b).
link(b, c).
link(c, d).
link(d, e).

link(b, e).
link(e, f).
link(f, c).

link(f, exit).

route(1, 2) :-
member(1, [entry,a,b,c,d,e,f,exit]),
member(2, [entry,a,b,e,f,exit]).

route(X, Z, [entry,a,b,c,d,e,f,exit]) :- route(X, Z,[R],[entry,a,b,c,d,e,f,exit]).
route(X, Z, [exit,f,e,d,c,b,a,entry], [entry,a,b,c,d,e,f,exit]) :-
reverse(X, Y, [exit,f,e,d,c,b,a,entry], [entry,a,b,c,d,e,f,exit]),
route(Y, Z),

write(X).

Despite hours of reading, I am struggling to understand how I can make my program generate and display the listed paths in the console window. Is there anyone who can provide advice? I have basically no programming experience, prolog is probably the bulk of my knowledge, and that's insufficient.


回答1:


route(X, Y, [X, Y]) :- link(X,Y).
route(X, Y, [X | TY]) :- 
    link(X, T),
    route(T, Y, TY).

With route as above, the following code searches for the path in increasing order of length.

?- length(X, _), route(entry,exit, X).
X = [entry, a, b, e, f, exit] ;
X = [entry, a, b, c, d, e, f, exit] ;
X = [entry, a, b, e, f, c, d, e, f, exit] ;
X = [entry, a, b, c, d, e, f, c, d, e, f, exit] ;
X = [entry, a, b, e, f, c, d, e, f, c, d, e, f, exit]

Since we did not constrain route predicate to disallow repeated nodes, we have loops at higher lengths of the path.

EDIT: The following works SWI-Prolog check if your system has dif/2. Using maplist here allows us to do increasing path length search.

route(X, Y, [X, Y]) :- link(X,Y).
route(X, Y, [X|TY]) :-
    link(X, T),
    maplist(dif(X), TY), % X is different from all nodes in TY
    route(T, Y, TY).

If you do not have dif use \+ member(X, TY) after the route(T, Y, TY).
This gives


?- route(entry, exit, X).
X = [entry, a, b, e, f, exit] ;
X = [entry, a, b, c, d, e, f, exit] ;

After the couple of solutions it will loop endlessly. If you want that to stop that happening you can constrain the length of path to number of existing nodes

?- between(2, 8, N), length(X, N), route(entry, exit, X).
N = 6,
X = [entry, a, b, e, f, exit] ;
N = 8,
X = [entry, a, b, c, d, e, f, exit] ;
false.


来源:https://stackoverflow.com/questions/65545714/how-can-i-get-my-maze-program-to-create-and-print-two-route-lists-to-the-console

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!