Skip to content

Commit 95116db

Browse files
authored
refactor: improving MedianOfMatrix (TheAlgorithms#6376)
refactor: improving MedianOfMatrix
1 parent 25aaa6e commit 95116db

File tree

2 files changed

+26
-10
lines changed

2 files changed

+26
-10
lines changed

src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,19 @@ private MedianOfMatrix() {
1414
}
1515

1616
public static int median(Iterable<List<Integer>> matrix) {
17-
// Flatten the matrix into a 1D list
18-
List<Integer> linear = new ArrayList<>();
17+
List<Integer> flattened = new ArrayList<>();
18+
1919
for (List<Integer> row : matrix) {
20-
linear.addAll(row);
20+
if (row != null) {
21+
flattened.addAll(row);
22+
}
2123
}
2224

23-
// Sort the 1D list
24-
Collections.sort(linear);
25-
26-
// Calculate the middle index
27-
int mid = (0 + linear.size() - 1) / 2;
25+
if (flattened.isEmpty()) {
26+
throw new IllegalArgumentException("Matrix must contain at least one element.");
27+
}
2828

29-
// Return the median
30-
return linear.get(mid);
29+
Collections.sort(flattened);
30+
return flattened.get((flattened.size() - 1) / 2);
3131
}
3232
}

src/test/java/com/thealgorithms/matrix/MedianOfMatrixTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
package com.thealgorithms.matrix;
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
45

56
import java.util.ArrayList;
67
import java.util.Arrays;
8+
import java.util.Collections;
79
import java.util.List;
810
import org.junit.jupiter.api.Test;
911

@@ -31,4 +33,18 @@ public void testMedianWithEvenNumberOfElements() {
3133

3234
assertEquals(2, result);
3335
}
36+
37+
@Test
38+
public void testMedianSingleElement() {
39+
List<List<Integer>> matrix = new ArrayList<>();
40+
matrix.add(List.of(1));
41+
42+
assertEquals(1, MedianOfMatrix.median(matrix));
43+
}
44+
45+
@Test
46+
void testEmptyMatrixThrowsException() {
47+
Iterable<List<Integer>> emptyMatrix = Collections.emptyList();
48+
assertThrows(IllegalArgumentException.class, () -> MedianOfMatrix.median(emptyMatrix), "Expected median() to throw, but it didn't");
49+
}
3450
}

0 commit comments

Comments
 (0)