问题描述
我需要使用 Google Apps 脚本解决分配问题。 LinearOptimizationService 似乎很有前途,所以我尝试的是移植相应的 example from the google or-tools 。
不幸的是,我无法找到一种方法来设置每个工人只分配给一个任务的约束。
工作代码(无约束)如下:
function myFunction() {
// Create the variables
var engine = LinearOptimizationService.createEngine();
const costMatrix = [[7,5,4,8,3],[2,6,7,1],9,2],1,9]]
const capacities = [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}`,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}`));
}
}
}
感谢任何帮助。
谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)