我有以下代码
option(2):-
write('Enter place of origin: '), read(Origin),
write('Enter place of destination: '), read(Destination),
path(Origin, Destination, Path, Length),nl,nl,
printPath(Path), write(' '),
writef(' TOTAL DISTANCE = %d', [Length]),nl,fail;true.
我想找到长度中最小的值。我得到类似于此
的输出bahirdar-->mota TOTAL DISTANCE = 100
bahirdar-->markos-->mota TOTAL DISTANCE = 70
答案 0 :(得分:1)
如果要查找数据库中任意两个位置之间的最小距离(根据谓词路径/ 4),使用CappelliC建议的aggregate库将起作用。如果要查找用户输入程序的最短路径,则需要存储该信息。一个简单的方法是asserta
用户的答案:
:- dynamic user_path/2.
option(2):-
write('Enter place of origin: '), read(Origin),
write('Enter place of destination: '), read(Destination),
path(Origin, Destination, Path, Length),
asserta(user_path(Origin, Destination)),
nl,nl,
printPath(Path), write(' '),
writef(' TOTAL DISTANCE = %d', [Length]),nl,fail
;
true.
然后你可以找到
的最小路径min_path(Path) :-
aggregate(
min(L,Path),
Origin^Destination^Path^(
user_path(Origin, Destination),
path(Origin, Destination, Path, L)
),
Length
).