Chadoblie
Chadoblie

Reputation: 31

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

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 to backtrack to get more results, please help.

Thanks in advance.

P.S I am using Swi-prolog

Upvotes: 3

Views: 831

Answers (2)

repeat
repeat

Reputation: 18726

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
).

Upvotes: 2

Paweł Płazieński
Paweł Płazieński

Reputation: 124

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

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

Upvotes: 0

Related Questions