丸三角四角

IT業界にしがみつく新人SEが立派なプログラマになろうともがく奮闘記

【Java】連立方程式を解く_Ver3

コード更新致しました。

固有処理基底クラスを更新したので、更新したコードを紹介いたします。

import static java.lang.Double.parseDouble;
import static java.lang.System.out;
import volume0.BaseExe;

public class SimultaneousEquation extends BaseExe {

    public static void main(String[] args) {
        new SimultaneousEquation().exeSysIn();
    }

    @Override
    protected void execute() throws Exception {
        while (judgeInData()) {
            double[] xy = getXY(getIn(getInData().split(" ")));
            out.printf("%4.3f %4.3f\n", xy[0], xy[1]);
        }
    }

    private double[] getIn(String[] abcdefList) {
        double[] in = new double[6];
        for (int i = 0; i < 6; i++) {
            in[i] = parseDouble(abcdefList[i]);
        }
        return in;
    }

    public double[] getXY(double[] in) {
        double[] xy = new double[2];
        xy[0] = (in[1] * in[5] - in[2] * in[4]) / (in[1] * in[3] - in[0] * in[4]);
        xy[0] = judge(xy[0]);
        xy[1] = (in[2] - in[0] * xy[0]) / in[1];
        xy[1] = judge(xy[1]);
        return xy;
    }

    public double judge(double num) {
        return (num == -0.0) ? 0.0 : num;
    }
}

テストドライバは以下になります。

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import volume0.BaseTest;

public class SimultaneousEquationTest extends BaseTest {

    private SimultaneousEquation se;

    @Before
    public void setUp() throws Exception {
        super.setUp();
        se = new SimultaneousEquation();
    }

    @After
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Test
    public void testSimul0001() {
        se.exeFileIn("./data/volume0_0004/0001/in.txt");
        assertOutList("./data/volume0_0004/0001/out.txt");
    }

    @Test
    public void testSimul0002() {
        se.exeFileIn("./data/volume0_0004/0002/in.txt");
        assertOutList("./data/volume0_0004/0002/out.txt");
    }
}

テストドライバ内で使用している「in.txt」・「out.txt」の内容は以下になります。

0001/in.txt
1 2 3 4 5 6
2 -1 -2 -1 -1 -5
0002/in.txt
2 -1 -3 1 -1 -3
2 -1 -3 -9 9 27
0001/out.txt
-1.000 2.000
1.000 4.000
0002/out.txt
0.000 3.000
0.000 3.000

Ver1で問題の解説等行なっているので、そちらを参照してください。

dadainu.hateblo.jp

アルゴリスムで困った時は、以下の本を参考にしてます。Javaに置き換えるのが少々難解ですが、、、

固有処理の基底クラスは以下の記事に記載していますので、参考にしてください。

dadainu.hateblo.jp

テストドライバで継承しているクラスは以下の記事に記載していますので、参考にしてみてください。

dadainu.hateblo.jp