【问题标题】:How can I use the jsLPSolver library locally in a browser?如何在浏览器中本地使用 jsLPSolver 库?
【发布时间】:2021-09-08 17:20:49
【问题描述】:

我想在浏览器中本地使用 jsLPSolver 库,而不是通过 Node.js,来运行线性编程优化。

按照自述文件的“安装”部分,我正在从 unpkg.com 加载solver.js 脚本。

我尝试了 README 的“使用”部分中的确切示例,但收到错误 Uncaught ReferenceError: require is not defined。看起来 require.js 库可能会为那些不使用 Node.js 的人提供解决方法。但后来我发现了 JWally 的示例 here,它没有使用 require()。但是,当我在下面显示的脚本中运行它时,我在控制台中收到错误 Uncaught ReferenceError: Solver is not defined

如何解决这个问题,以便我可以在浏览器中运行 jsLPSolver?感觉我可能遗漏了一些基本的东西,这不是 jsLPSolver 特有的。

<script src="https://unpkg.com/javascript-lp-solver/prod/solver.js"></script>
<script>
var solver = new Solver,
    results,
    model = {
    optimize: "profit",
    opType: "max",
    constraints: {
        "Costa Rican" : {max: 200},
        "Etheopian": {max: 330}
    },
    variables: {
        "Yusip": {"Costa Rican" : 0.5, "Etheopian": 0.5, profit: 3.5},
        "Exotic": {"Costa Rican" : 0.25, "Etheopian": 0.75, profit: 4}
    }
};

results = solver.solve(model);
console.log(results);
</script>

【问题讨论】:

    标签: javascript linear-programming


    【解决方案1】:

    <script src="https://unpkg.com/javascript-lp-solver/prod/solver.js"></script>
    <script>
      const model = {
        optimize: "profit",
        opType: "max",
        constraints: {
          "Costa Rican": {
            max: 200
          },
          Etheopian: {
            max: 330
          },
        },
        variables: {
          Yusip: {
            "Costa Rican": 0.5,
            Etheopian: 0.5,
            profit: 3.5
          },
          Exotic: {
            "Costa Rican": 0.25,
            Etheopian: 0.75,
            profit: 4
          },
        },
      };
    
      // We don't need to declare 'solver', it is already exported via the script we load
      const results = solver.Solve(model); // Note the capital '.Solve'
      console.log("Results", results);
    </script>

    请试试这个。我相信您的困惑来自使用通过 Node.js 解释的示例的文档。您无需声明求解器变量,它已通过导入的脚本为您导出。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      相关资源
      最近更新 更多