テストによって形成された行列の最大値を見つけるコードが必要です。また、行列が空の場合、Integer.MIN_VALUEを返します。私のコードは
int max = -1;
if (matrix.length == 0 ) return Integer.MIN_VALUE;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
}
System.out.println("max value in myArray: " + max);
return max;
}
このコードの問題は、行列が空の場合にInteger.MIN_VALUEを返さず、代わりに-1を返すことです。必要なときになぜInteger.MIN_VALUEを行わないのかわかりません。このコード行が機能しない理由
このテストによってマトリックスが形成されます
@Test
public void testMaxMatrix() {
FirstSteps firstSteps = new FirstSteps();
int[][] matrix1 = {{1, 2, 3}, {3, 4, 5}, {6, 7, 8}};
assertEquals(8, firstSteps.max(matrix1));
int[][] matrix2 = {{100, 200, 300}, {3, 4, 5}, {6, 7, 8}};
assertEquals(300, firstSteps.max(matrix2));
int[][] matrix3 = {{-1, -2, -3}, {-3, -4, -5}, {-6, -7, -8}};
assertEquals(-1, firstSteps.max(matrix3));
int[][] matrix4 = {{}};
assertEquals(Integer.MIN_VALUE, firstSteps.max(matrix4));
}
{{}}
は空ではありません:空の配列を1つ含む配列です。次のようにして確認できます。
if (matrix.length == 1 && matrix[0].length == 0) return Integer.MIN_VALUE;
または、実際の空の配列を使用するようにテストケースを変更します。
int[][] matrix4 = {};
assertEquals(Integer.MIN_VALUE, firstSteps.max(matrix4));
または、の初期値max
をInteger.MIN_VALUE に設定しますが、これにより、-1未満の行列の値でのアルゴリズムの動作が変更されることに注意してください。
int max = Integer.MIN_VALUE;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加