I need to solve an assignment problem with Google Apps Script. The LinearOptimizationService seemed to be promising so what I tried is to port a corresponding example from the google or-tools .
Unfortunately, I couldn't find out a way how I set up the constraint that each worker is assigned to exactly one task.
The working code (without the constraint) is as follows:
function myFunction() {
// Create the variables
var engine = LinearOptimizationService.createEngine();
const costMatrix = [[7,5,4,8,3]
,[2,5,6,7,1]
,[2,8,9,5,2]
,[2,5,6,7,1]
,[2,8,1,5,9]]
const capacities = [1,1,1,1,1]
// initialize the decision variables
x = new Array(costMatrix.length);
for (let i=0; i<costMatrix.length; i++){
x[i] = new Array(costMatrix[0].length);
for (let j=0; j<costMatrix[0].length; j++){
x[i][j] = engine.addVariable(`x${i}${j}`, 0, 1, LinearOptimizationService.VariableType.INTEGER);
}
}
// Each worker is assigned to at most one task.
for (let i = 0; i < costMatrix.length; ++i) {
constraint = engine.addConstraint(0, 1);
for (let j = 0; j < costMatrix[0].length; ++j) {
constraint.setCoefficient(`x${i}${j}`, 1);
}
}
// Each task is assigned to exactly one worker.
for (let j = 0; j < costMatrix[0].length; ++j) {
constraint = engine.addConstraint(1, 1);
for (let i = 0; i < costMatrix.length; ++i) {
constraint.setCoefficient(`x${i}${j}`, 1);
}
}
for (let i = 0; i < costMatrix.length; ++i) {
for (let j = 0; j < costMatrix[0].length; ++j) {
engine.setObjectiveCoefficient(`x${i}${j}`, costMatrix[i][j]);
}
}
engine.setMinimization()
// Solve the linear program
var solution = engine.solve(30);
if (!solution.isValid()) {
throw 'No solution ' + solution.getStatus();
}
Logger.log('ObjectiveValue: ' + solution.getObjectiveValue());
for (let i=0; i<costMatrix.length; i++){
for (let j=0; j<costMatrix[0].length; j++){
Logger.log(`Value of: x${i}${j} ` + solution.getVariableValue(`x${i}${j}`));
}
}
}
Any help is appreciated.
Thanks