2017-02-18 66 views
0

最低值我是新的序言,所以让我们去,我做了我返回结果的几个规则,我想通过这些结果,找到的最低值,但我不知道该怎么做。搜索的结果,发现在序言

Path is a list. 
Cost is variable. 

成本不是清单的长度,成本是一个累积变量。我只想在所得结果中找到较低价值的可变成本。 查找最低值的变量成本并获取绑定的列表。

%graph non-directed 
route(a,b,1). 
route(a,d,1). 
route(a,h,1). 
route(b,c,1). 
route(b,a,1). 
route(b,e,1). 
route(c,b,1). 
route(c,f,1). 
route(c,e,1). 
route(d,e,1). 
route(d,a,1). 
route(d,g,1). 
route(e,b,1). 
route(e,c,1). 
route(e,d,1). 
route(f,c,1). 
route(f,i,1). 
route(f,h,1). 
route(g,d,1). 
route(g,j,1). 
route(g,l,1). 
route(h,a,1). 
route(h,f,1). 
route(h,k,1). 
route(i,f,1). 
route(i,l,1). 
route(i,k,1). 
route(j,g,1). 
route(j,m,1). 
route(j,o,1). 
route(k,h,1). 
route(k,i,1). 
route(k,n,1). 
route(l,i,1). 
route(l,o,1). 
route(l,m,1). 
route(l,g,1). 
route(m,j,1). 
route(m,l,1). 
route(m,n,1). 
route(n,m,1). 
route(n,o,1). 
route(n,k,1). 
route(o,l,1). 
route(o,n,1). 
route(o,j,1). 

travessiaCusto(A, B, Visitados,[B|Visitados], Custo1) :-route(A, B, Custo1). 
travessiaCusto(A, B, Visitados, Cam, Custo) :-route(A, C, Custo2), 
              C \== B, 
              \+ member(C, Visitados), 
       travessiaCusto(C, B, [C|Visitados], Cam, CustoResto), 
       Custo is Custo2 + CustoResto. 


caminhoCusto(A, B, Path, Cost) :-travessiaCusto(A, B, [A], Path, Cost). 

copy(L,R) :- accCp(L,R). 
accCp([],[]). 
accCp([H|T1],[H|T2]) :- accCp(T1,T2). 

上面的规则通过两个点的图形来查找所有可能的路线。 我想使用规则:

caminhoCusto(A, B, Path, Cost) :-travessiaCusto(A, B, [A], Path, Cost). 

我第一次尝试得到结果只有一个,但包含递归误差在if条件。

caminhoCustoMinimo(A,B,Path,Cost):-Cost is 100000000, 
       ,caminhoCusto(A,B,Path1,Cost1) 
       ,Cost1 =< Cost -> 
       (Cost is Cost1,copy(Path1,Path)). 

在上述规则中,我尝试将结果的值与最初设置的值进行比较,但没有成功。

+0

这是非常不清楚的。你正在描述一个通用的成本和路径。然后,您将显示带有4个变量的示例查询,结果显示两个变量。没有显示任何代码尝试,也没有关于您给定数据的信息。很多信息缺失。如果你已经尝试了一些东西,你应该显示该代码。 – lurker

+0

@lurker我现在编辑了一下。 –

+0

您显示的查询无法提供您显示的结果。该查询中的“A”和“B”发生了什么? – lurker

回答

0

findall(Y,caminhoCusto(A,B,_,Y),Costs)发现每一个路线,并放置在列表的费用。

sort(Costs,[Cost|_])将成本从最小到最大排序,然后采用第一个(即最小)元素 - 这实质上是一个最小函数,所以如果效率很关键,可以重写。

findall(X,caminhoCusto(A,B,X,Cost),[Path|_])找到具有最小成本每路线,然后采取第一 - 这是满足'只有一个路由的需求。

caminhoCustoMinimo(A,B,Path,Cost) :- 
    findall(Y,caminhoCusto(A,B,_,Y),Costs), 
    sort(Costs,[Cost|_]), 
    findall(X,caminhoCusto(A,B,X,Cost),[Path|_]). 

如果您希望它在同一时间以最低的成本来回报每航,一,我们与Paths取代[Path|_],然后用member(Path,Paths)找到以最低的成本每条路线:

caminhoCustoMinimo(A,B,Path,Cost) :- 
    findall(Y,caminhoCusto(A,B,_,Y),Costs), 
    sort(Costs,[Cost|_]), 
    findall(X,caminhoCusto(A,B,X,Cost),Paths), 
    member(Path,Paths). 
+0

非常感谢。 –