【Java】4つの整数和の組み合わせ_Ver2
Ver1のコードは不適切だったため、コード更新致しました。
Ver2では、4つの整数和をリストのインデックスに紐付け、保持する数値をカウントアップするようにしました。入力はそのインデックスから組み合わせを出力するようにしました。また、固有処理基底クラスを継承するようにし、テストドライバ用基底クラスを更新したので、更新したコードを紹介いたします。
import static java.lang.Integer.parseInt;
import static java.lang.System.out;
import java.util.Scanner;
import volume0.BaseExe;
public class Sumof4Integers extends BaseExe {
public static void main(String[] args) {
new Sumof4Integers().exeSysIn();
}
@Override
protected void execute(Scanner scan) {
String inDataStr = "";
int[] combiList = getConb();
while (scan.hasNextLine() && !"".equals(inDataStr = scan.nextLine())) {
out.println(combiList[parseInt(inDataStr)]);
}
}
private int[] getConb() {
int[] combiList = new int[51];
for (int a = 0; a < 10; a++)
for (int b = 0; b < 10; b++)
for (int c = 0; c < 10; c++)
for (int d = 0; d < 10; d++)
combiList[a + b + c + d]++;
return combiList;
}
}
入力に対する処理を固有処理基底クラスを継承したことで無くなったため、だいぶコードスッキリしました。テストドライバは以下になります。
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import volume0.BaseTest;
public class Sumof4IntegersTest extends BaseTest {
private Sumof4Integers s4i;
@Before
public void setUp() throws Exception {
super.setUp();
s4i = new Sumof4Integers();
}
@After
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void test() {
s4i.exeFileIn("./data/volume0_0008/in.txt");
assertOutList("./data/volume0_0008/out.txt");
}
}
Ver1のテストドライバでは「trycatch」文がありましたが、それが無くなったことでテストドライバもスッキリしました。テストドライバ内で使用している「in.txt」・「out.txt」は以下の内容になります。
in.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
out.txt
4
10
20
35
56
84
120
165
220
282
348
415
480
540
592
633
660
670
660
633
592
540
480
415
348
282
220
165
120
84
56
35
20
10
4
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
Ver1の記事は以下になります。
今回の問題は以下にあります。
アルゴリスムで困った時は、以下の本を参考にしてます。Javaに置き換えるのが少々難解ですが、、、
固有処理の基底クラスは以下の記事に記載していますので、参考にしてください。
テストドライバで継承しているクラスは以下の記事に記載していますので、参考にしてみてください。