2016-02-04 32 views
0

最小值我有以下代碼如何找到在序言

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

最小路徑,見庫([集合](HTTP://www.swi-prolog .ORG/pldoc /人?部=集合體))。那麼你可以聚合(min(L,Path),Origin^Destination^Path^path(Origin,Destination,Path,L),Length)。 – CapelliC

回答

1

使用aggregate庫作爲CappelliC建議,如果你想找到你的數據庫中的任何兩兩地之​​間的最小距離就可以了(根據謂詞路/ 4)。如果您想查找用戶輸入到程序中的最短路徑,則需要存儲該信息。一個簡單的方法是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 
     ). 
在SWI