Reputation: 11
I keep getting false for path_to_phone(1, 16, Path). and cannot figure out where the error is in the code.
door(1,2).
door(1,7).
door(2,1).
door(2,8).
door(3,8).
door(4,8).
door(4,9).
door(5,9).
door(5,6).
door(6,9).
door(7,1).
door(7,8).
door(7,9).
door(7,10).
door(7,11).
door(7,12).
door(7,13).
door(7,14).
door(8,2).
door(8,3).
door(8,4).
door(8,7).
door(9,4).
door(9,5).
door(9,6).
door(9,7).
door(10,7).
door(11,7).
door(12,7).
door(13,7).
door(14,7).
door(14,15).
door(15,16).
door(16,15).
phone(5).
phone(9).
phone(16).
rooms_connected(X, Y) :- door(X, Y), door(Y, X).
path_to_phone(Start, End, Path) :-
move(Start, End,[Start], Room),
reverse(Room,Path).
move(Start, End, Path, [End|Path]) :-
rooms_connected(Start, End),
phone(End).
move(Start, Middle, Visit, Path) :-
rooms_connected(Start, End),
End \== Middle,
\+member(End, Visit),
move(End, Middle, [End|Visit], Path).
Upvotes: 1
Views: 156
Reputation: 60024
I think should be simpler, no need to pass around the confusing Middle:
path_to_phone(Start, End, Path) :-
move(Start, [Start], [End|RPath]),
reverse([End|RPath], Path).
move(From, Visit, [Phone|Visit]) :-
door(From, Phone),
phone(Phone).
move(From, Visit, Path) :-
door(From, Next),
\+memberchk(Next, Visit),
move(Next, [Next|Visit], Path).
Upvotes: 0
Reputation: 285
From an aesthetical point of view, it would look better like this:
move(Start, End, Visit, Path) :- rooms_connected(Start, Middle),
End \== Middle,
\+member(Middle, Visit),
move(Middle, End, [Middle|Visit], Path).
The problem is your definition of rooms_connected because it forces to have the connection both ways. If thats what you intended you have to put in the file doors(15,14) and others, because as it is now, it cannot find a path. If not you can change it to:
rooms_connected(X, Y) :- door(X, Y); door(Y, X).
This means either door(X,Y) or door(Y,X).
Upvotes: 1