IBM ILOG Solver User's Manual > Developing Solver Applications > Designing Models > Back propagate costs > Example

Let's assume that we want to maximize a sum of five variables that are integers between 0 and 3, inclusive, and let's count the number of tries necessary to do so.

ILCGOAL2(computeSum, IlcIntVar, var, IlcIntVarVarArray, vars){
  IloSolver solver = getSolver();
  IlcInt sum = 0;
  for(IlcInt i = 0; i < vars.getSize(); i++)
    sum += vars[i].getValue();
  var.setValue(sum);
  return 0;
}

ILOCPGOALWRAPPER2(computeSum, solver, IloNumVar, var, IloNumVarArray, vars){
  IlcIntVarArray svars = solver.getIntVarArray(vars);
  IlcIntVar svar = solver.getIntVar(var);
  return IlcComputeSum(solver, var, vars);
}


int main(){
  IloEnv env;
  IloModel m(env);
  IloIntVarArray vars(env, 5, 0, 3);
  IloIntVar sum(env, 0, 100);
  m.add(vars);
  m.add(sum);
  m.add(IloMaximize(env, sum));
  IloSolver s(m);
  s.solve(IloGenerate(env, vars) && computeSum(env, sum, vars)); // not good
  cout << "Sum = " << s.getIntVar(sum) << endl;
  cout << "#tries = " << s.getNumberOfChoicePoints() << endl;
  env.end();
  return 0;
}


Here's the output of this code:

Sum = 15
#tries = 5145

In the code that we just discussed, the program evaluates the cost function only after choosing values. In the next version, a constraint is set to reduce the domains before the search for a solution.

int main(){
  IloEnv env;
  IloModel m(env);
  IloIntVarArray vars(env, 5, 0, 3);
  IloIntVar sum(env, 0, 100);
  m.add(sum == IloSum(vars));  // good
  m.add(IloMaximize(env, sum));
  IloSolver s(m);
  s.solve(IloGenerate(env, vars));
  cout << "Sum = " << s.getIntVar(sum) << endl;
  cout << "#tries = " << s.getNumberOfChoicePoints() << endl;
  env.end();
  return 0;
}

This version finds the maximal solution with far fewer tries than the previous one, and thus, of course, represents considerable improvement in performance. Here's its output:

Sum = 15
#tries = 45