2015年11月18日水曜日

lp_solveでJavaプログラム実行(配列利用)

lp_solveを利用するときに配列を利用する場合

int constraint[][] = {{-18,-900,370,10},{-74,-230,550,20},{-34,-2090,340,11},{-80,-1410,452,15},{18,900,0,0}};
int object[] = {0,0,370,10};
のように、制約条件と目的関数の係数配列を用意
これをそれぞれ文字列として変数にいれておく

import lpsolve.*;
public class LP {

    public static void main(String[] args) {

        int constraint[][] = {{-18,-900,370,10},{-74,-230,550,20},{-34,-2090,340,11},{-80,-1410,452,15},{18,900,0,0}};
        int object[] = {0,0,370,10};

        try {
            LpSolve solver = LpSolve.makeLp(constraint.length, object.length);//constraints, variables
            solver.setOutputfile("debug");
            String stc = "", sto = "";
            for(int i = 0;i < constraint.length; i++){
                stc = "";
                for(int j = 0; j < constraint[i].length; j++){
                        stc += constraint[i][j];
                        stc += " ";
                }
                if(i == constraint.length -1 )
                        solver.strAddConstraint(stc, LpSolve.EQ,1);
                else
                        solver.strAddConstraint(stc, LpSolve.LE,0);
            }

            for(int i = 0; i < object.length; i++){
                        sto += object[i];
                        sto += " ";
            }
            solver.setMaxim();
            solver.strSetObjFn(sto);
            solver.solve();
            System.out.println("Value of objective function: " + solver.getObjective());
            double var[] = solver.getPtrVariables();
            for(int i = 0; i < var.length; i++){
                System.out.println("var[" + i + "] = " + var[i]);
            }
            solver.deleteLp();
        }
        catch (LpSolveException e) {
            e.printStackTrace();
        }
    }

}

このような形になる。次はDBから値を持ってきて配列にいれて計算を行う。

0 件のコメント:

コメントを投稿