I use the CPLEX library to solve my problem. In my case, it is necessary that the number of items in the answer be odd. So I need to do the following:
IloExpr exp(env);
for (int i = 0; i < N; i++)
exp += X[i];
Model.add(exp == 1 || exp == 3 || exp == 5 || ext == 7 || ...etc)
It seems obvious that line with Model.add should look like this:
Model.add(exp % 2 != 0);
But I get an error:
Error C2678 binary '%': no operator found which takes a left-hand operand of type 'IloExpr' (or there is no acceptable conversion)
I have an idea that it is necessary to overload an operator %. To do this I am trying to create my own class:
class NewIloExpr : public IloExpr
{
public:
NewIloExpr& operator%(const IloNum& val)
{
// some code
return *this;
}
};
But I don't know what to write in the overload implementation (in place of the comment) to make it work. Does anyone have any ideas on this, or perhaps another solution to the problem?
It follows from the way that solvers like CPLEX work that using operators like mod will not work well as these are not linear functions. Also using a simple test like is_odd() will not help the search process as CPLEX will likely explore many values which are even and then reject them. A better trick for finding solutions with only odd-valued variables is to define another variable which is a plain IloIntVar or similar (lets call it v) that takes values 0...N, and define an expression whose value is 1+2*v. Then the expression will take values 1,3,5,... etc which is the set of values that you want.
Try creating another IloIntVar and expression like this and add a constraint that your exp expression must be equal to our newly-constructed expression which can only take odd values.