Tom
Tom

Reputation: 19

prolog question find maximum using negation operator \+

I have got some values H, and I would like to find the maximum one using \+, how can i do it?

maxValue(X) :-
  Get(Id, X),
  \+( Get(Id, Y), X < Y ).

don't have a clue....please help, thanks!

Upvotes: 0

Views: 744

Answers (2)

user502187
user502187

Reputation:

Using negation is one way to find the maximum. And it really works. Here is an example:

   p(2).  
   p(1).  
   p(3).  

   ?- p(X), \+ (p(Y), Y > X).  
   X = 3

But the complexity will be O(n*n) where n is the number of facts. But the maximum can be determined in O(n). So maybe the following is more efficient for large fact bases:

   :- dynamic(the_max/1).  
   update_max(X) :-  
      the_max(Y), X>Y, !, retract(the_max(Y)), assertz(the_max(X)).  
   update_max(_).  

   find_max(X) :-  
      assertz(the_max(0)),  
      (p(Y), update_max(Y), fail; true),  
      retract(the_max(X)).  

   ?- find_max(X).  
   X = 3

But watch out, when you use it from multiple threads, you need to adapt it a little, i.e. make the_max thread local.

Best Regards

Upvotes: 3

Related Questions