I'm using CP-SAT Solver in Java, and my objective is to minimize the range in the max and min values of an array of IntVars.
Creating IntVars for the max and min values in the array in Java is no problem. The challenge is creating the range IntVar in Java. In Python it's simple:
range = model.NewIntVar(1, 1000, "range")
model.Add(range == max - min)
model.Minimize(range)
I know that with OR-Tools in Java I need to use model.addEquality, instead of ==. But how to accomplish the subtraction to get the 'range' IntVar? I thought of using LinearExpr.sum on an IntVar[] containing max and the negative of min, where the negative of min comes from: LinearExpr.term(min, -1). But LinearExpr.term returns a LinearExpr, and LinearExpr.sum only accepts arrays of IntVars.
How can this be done in Java?
The cumbersome java way :-)
model.AddEquality(LinearExpr.Sum(new IntVar[] {x, y}), 1);
This is shown in the rabbit + pheasant sample.