Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...