2017-03-09 153 views
0

我編寫了一個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

請提供更多詳情。你試圖完成什麼任務?您是否想要將解決方案變量序列化爲電子表格?你想將輸出流式傳輸到文件中嗎?你做了什麼嘗試?結果是什麼? – Ahmedov

+0

我想將解決方案的值發送到調用函數的電子表格。我嘗試使用谷歌腳本solution.getvariable和solution.getobjectivefunction調用並返回調用,電子表格中沒有顯示任何內容。 – user7686691

回答

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()]); 
} 
+0

謝謝。我會試一試。 – user7686691

+0

@ user7686691請在您決定解決問題後點擊旁邊的複選標記來接受答案。 – Ahmedov