开发者

Prolog program to find the minimum and next minimum in a list

开发者 https://www.devze.com 2023-02-27 17:49 出处:网络
I want to create a prolog program so that it can search for the minimum number in a list and when the user asks for more solutions (using the ; symbol) the program returns the next minimum number. If

I want to create a prolog program so that it can search for the minimum number in a list and when the user asks for more solutions (using the ; symbol) the program returns the next minimum number. If the user asks for another solution it returns the next number and so on. I've created the minimum predicate but can't make it开发者_C百科 to backtrack to get more results, please help.

Thanks in advance.

P.S I am using Swi-prolog


We define list_nextmin_gt/3 based on list_minnum/2, tfilter/3 and dif/3:

list_nextmin_gt(Zs0, M, Zs) :-
   list_minnum(Zs0, M0),
   tfilter(dif(M0), Zs0, Zs1),
   (  M0 = M, 
      Zs = Zs1
   ;  list_nextmin_gt(Zs1, M, Zs)
   ).

Sample query:

?- list_nextmin_gt([3,2,1,2,3], M, Rest).
(  M = 1, Rest = [3,2,2,3]
;  M = 2, Rest = [3,3]
;  M = 3, Rest = []
;  false
).

Or, if you don't care about the remaining list items, simply write:

?- list_nextmin_gt([3,2,1,2,3], M, _).
(  M = 1
;  M = 2
;  M = 3
;  false
).


Utterly simple solution: Sort the list and return each member of this list:

min(List, Min) :-
    sort(List, Sorted),
    member(Min, Sorted).
0

精彩评论

暂无评论...
验证码 换一张
取 消