ILOG TSP 得到空输出

ILOG TSP getting null output

我一直在通过实施 TSP 问题来学习 Cplex Java API。我想创建随机权重在 50-1000 之间的对象,如下所示:

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;
}

然后,当我想检查 main 方法中 generateObjs 方法的输出时:

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

    IloCplex cplex = new IloCplex();
    IloLinearNumExpr expr;

    expr = generateObjs(10, cplex);

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

它给出如下输出:

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

但是我想得到这样的输出:

(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]+ ...

指定城市之间的路径,权重随机。

您很接近,但您需要在 generateObjs 方法中创建个人 IloNumVar。例如,您可以这样做:

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;
}