2

I've been learning Cplex Java API by implementing TSP problem. I want to create obj with random weights between 50-1000 as seen below:

public static IloLinearNumExpr generateObjs(Integer n, IloCplex cplex) throws IloException{

    IloNumVar[][] x = new IloNumVar[n][n];
    IloLinearNumExpr expr = cplex.linearNumExpr();
    Random r = new Random();


    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            if(i != j) {
                expr.addTerm(50 + r.nextInt(951), x[i][j]);
            }
        }
    }

    return expr;
}

then, when I want to examine the output of generateObjs method in main method:

public static void main(String args[]) throws IloException {

    IloCplex cplex = new IloCplex();
    IloLinearNumExpr expr;

    expr = generateObjs(10, cplex);

    System.out.println(expr.toString());
 }

it gives the output as below:

(663.0*null + 941.0*null + 754.0*null + 324.0*null + 228.0*null + ...

However I want to get an output like:

(663.0*x[0][1]+ 941.0*x[0][2] + 754.0*x[0][3] + 324.0*x[0][4] + 228.0*x[0][5]+ ...

which specifies the paths between the cities with random weights.

1 Answers1

1

You're close, but you need to create the individual IloNumVar's in the generateObjs method. For example, you could do this, like so:

public static IloLinearNumExpr generateObjs(Integer n, IloCplex cplex) throws IloException{

   IloNumVar[][] x = new IloNumVar[n][n];
   IloLinearNumExpr expr = cplex.linearNumExpr();
   Random r = new Random();

   for(int i = 0; i < n; i++) {
      x[i] = cplex.numVarArray(n, 0.0, Double.MAX_VALUE);
      for(int j = 0; j < n; j++) {
         x[i][j].setName("x[" + i + "][" + j + "]");
         if(i != j) {
            expr.addTerm(50 + r.nextInt(951), x[i][j]);
         }
      }
   }

   return expr;
}
rkersh
  • 4,447
  • 2
  • 22
  • 31