IBM ILOG Solver User's Manual > More on Modeling > Using the Distribute Constraint: Car Sequencing > Suggested answers > Exercise 4

Use the IloDistribute constraint to solve for a magic sequence. A magic sequence is a sequence of n + 1 values (x0, x1, ..., xn) such that 0 appears in the sequence x0 times, 1 appears x1 times, ..., and n appears in the sequence xn times. The numbers in the magic sequence have a sum equal to n + 1.

For example, for n = 3, the following sequence is a solution: (1, 2, 1, 0). That is, 0 is present once, 1 is present twice, 2 is present once, and 3 is not present (present zero times, as it were).

Describe, model, and solve this problem. Write the code so that you can solve magic sequences of different sizes, but find a solution for a magic sequence of size n = 10. This is a problem with a high level of modeling difficulty.

Suggested Answer

Describe

Model

Solve

The complete program follows. You can also view it online in the file YourSolverHome/examples/src/carseq_basic_ex4.cpp.

# include <ilsolver/ilosolverint.h>
 
ILOSTLBEGIN
 
int main(int argc, char** argv){
  IloEnv env;
  try {
    IloModel model(env);
    IloInt n = (argc > 1) ? atoi(argv[1]) : 10;
    IloInt i;
    IloIntVarArray vars(env, n + 1, 0, n + 1);
    IloIntArray coeffs(env, n + 1);
    for (i = 0; i < n + 1; i++)
      coeffs[i] = i;
    model.add(IloDistribute(env, vars, coeffs, vars));
    // redundant constraint
    model.add(IloScalProd(vars,coeffs) == n + 1);
    IloSolver solver(model);
    if (solver.solve(IloGenerate(env, vars, IloChooseMinSizeInt))) {
      for (i = 0; i < n + 1; i++)
        solver.out() << solver.getValue(vars[i]) << " ";
      solver.out() << endl;
    } 
    else
      solver.out() << "No solution" << endl;
    solver.printInformation();
  }
  catch (IloException& ex) {
    cerr << "Error: " << ex << endl;
  }
  env.end();
  return 0;
}
 

Results

You should get the following results, though the information displayed by IloSolver::printInformation will vary depending on platform, machine, configuration, and so on.

7 2 1 0 0 0 0 1 0 0 0 
Number of fails               : 5
Number of choice points       : 6
Number of variables           : 23
Number of constraints         : 14
Reversible stack (bytes)      : 4044
Solver heap (bytes)           : 12084
Solver global heap (bytes)    : 8088
And stack (bytes)             : 4044
Or stack (bytes)              : 4044
Search Stack (bytes)          : 4044
Constraint queue (bytes)      : 11144
Total memory used (bytes)     : 47492
Running time since creation   : 0.01