我编写了一个Google脚本来优化数学编程问题,但我无法弄清楚如何利用优化脚本在电子表格中显示最佳解决方案。
以下是Google脚本:
function myFunction() {
var engine = LinearOptimizationService.createEngine();
// Add variables, constraints and define the objective with addVariable(), addConstraint(), etc.
// Add two variables, 0 <= x <= 10 and 0 <= y <= 5
engine.addVariable('x', 0, 10);
engine.addVariable('y', 0, 5);
// Create the constraint: 0 <= 2 * x + 5 * y <= 10
var constraint = engine.addConstraint(0, 10);
constraint.setCoefficient('x', 2);
constraint.setCoefficient('y', 5);
// Create the constraint: 0 <= 10 * x + 3 * y <= 20
var constraint = engine.addConstraint(0, 20);
constraint.setCoefficient('x', 10);
constraint.setCoefficient('y', 3);
// Set the objective to be x + y
engine.setObjectiveCoefficient('x', 1);
engine.setObjectiveCoefficient('y', 1);
// Engine should maximize the objective
engine.setMaximization();
// Solve the linear program
var solution = engine.solve();
任何帮助将不胜感激。
答案 0 :(得分:0)
下面提供了完整的工作代码。您需要添加一个函数来将解决方案写入活动电子表格。为此,我添加了一个新函数addSolution(solution)
,然后将solution
对象的每个成员写入各自的单元格。
function myFunction() {
var engine = LinearOptimizationService.createEngine();
// Add variables, constraints and define the objective with addVariable(), addConstraint(), etc.
// Add two variables, 0 <= x <= 10 and 0 <= y <= 5
engine.addVariable('x', 0, 10);
engine.addVariable('y', 0, 5);
// Create the constraint: 0 <= 2 * x + 5 * y <= 10
var constraint = engine.addConstraint(0, 10);
constraint.setCoefficient('x', 2);
constraint.setCoefficient('y', 5);
// Create the constraint: 0 <= 10 * x + 3 * y <= 20
var constraint = engine.addConstraint(0, 20);
constraint.setCoefficient('x', 10);
constraint.setCoefficient('y', 3);
// Set the objective to be x + y
engine.setObjectiveCoefficient('x', 1);
engine.setObjectiveCoefficient('y', 1);
// Engine should maximize the objective
engine.setMaximization();
// Solve the linear program
var solution = engine.solve();
addProduct(solution)
}
function addSolution(solution) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([solution.getObjectiveValue(), solution.getStatus(), solution.getVariableValue('x'), solution.getVariableValue('y'),solution.isValid()]);
}