Search code examples
constraint-programminggecode

How to constrain a variable depending on the value of an other variable in Gecode


I am working with the Gecode toolkit and I want to model the following scenario.

I have two variables x and y. Depending on the value of x, y should be of a certain value. E.g. if x is 1, y should be 3, if x is 2, y should be 5. How should I model this in Gecode?

I currently use reified constraints to model this situation as can be seen in this gist. The crux is to use a BoolVar and two reified constraints to set the corresponding values.

for (IntVarValues i(x); i(); ++i) {
    BoolVar b = BoolVar(*this, 0, 1);
    rel(*this, x, IRT_EQ, i.val(), b);
    rel(*this, y, IRT_EQ, f(i.val), b);
}

I was wondering if there is a better way to model this situation.


Solution

  • A functional transformation from x to y (i.e., one where each value for x is assigned a single value for y) is best done through the element constraint when possible. The constraint takes an array that maps the domain of x to the domain of y, starting at the zero index.

    For your example, you can use the following (assuming that invalid is an int not in the domain of y ):

    IntArgs mapping(3,  invalid, 3, 5);
    element(*this, mapping, x, y);