Larkin
Larkin

Reputation: 21

Find the maximum of an atom in clingo

I am a starter with clingo and I can't for the life of me figure out how to get the max value of a given atom.
e.g.

x(1..9).
x_max(X) :- x(X), x(Y), X>Y.

The result I would like to have in this case would be x_max(9).

Upvotes: 0

Views: 1346

Answers (2)

s1l3n0
s1l3n0

Reputation: 221

I'll first modify a bit the first answer and then provide a more general example.

x(1..9). % equivalent to x(1). x(2). [...] x(9).

% find the max across predicates x
x_max(X) :- x(X), X = #max{X_i: x(X_i)}. 

%%% entails x_max(9)

The X_i is the internal variable across which the max is computed. This value is assigned to X. The x(X) is a (safe) constraint necessary for how the solver works.

We consider now a more complex predicate of the form r(X, Y):

r(1, 3). r(3, 3). r(3, 2). r(5, 6). r(5, 3). 

% find the max across the parameters X
xmax(X) :- r(X, _), X = #max{X_i: r(X_i, _)}. 

%%% entails xmax(5) 

% find the max across the parameters Y 
ymax(Y) :- r(_, Y), Y = #max{Y_i: r(_, Y_i)}. 

%%% entails ymax(6) 

% find the max across Y conditioned by parameter X
ymax_x(Y, X) :- r(X, Y), Y = #max{Y_i: r(X, Y_i)}. 

%%% entails ymax_x(3,1) ymax_x(3,3) ymax_x(6,5)  

Upvotes: 0

Larkin
Larkin

Reputation: 21

Try this:

max_x(X) :- x(X), #max {XX,1:x(XX)} = X.

Upvotes: 1

Related Questions