mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-12-19 07:00:35 +08:00
refactor: improving MedianOfMatrix (#6376)
refactor: improving MedianOfMatrix
This commit is contained in:
committed by
GitHub
parent
25aaa6e064
commit
95116dbee4
@@ -14,19 +14,19 @@ public final class MedianOfMatrix {
|
||||
}
|
||||
|
||||
public static int median(Iterable<List<Integer>> matrix) {
|
||||
// Flatten the matrix into a 1D list
|
||||
List<Integer> linear = new ArrayList<>();
|
||||
List<Integer> flattened = new ArrayList<>();
|
||||
|
||||
for (List<Integer> row : matrix) {
|
||||
linear.addAll(row);
|
||||
if (row != null) {
|
||||
flattened.addAll(row);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort the 1D list
|
||||
Collections.sort(linear);
|
||||
if (flattened.isEmpty()) {
|
||||
throw new IllegalArgumentException("Matrix must contain at least one element.");
|
||||
}
|
||||
|
||||
// Calculate the middle index
|
||||
int mid = (0 + linear.size() - 1) / 2;
|
||||
|
||||
// Return the median
|
||||
return linear.get(mid);
|
||||
Collections.sort(flattened);
|
||||
return flattened.get((flattened.size() - 1) / 2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package com.thealgorithms.matrix;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@@ -31,4 +33,18 @@ public class MedianOfMatrixTest {
|
||||
|
||||
assertEquals(2, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMedianSingleElement() {
|
||||
List<List<Integer>> matrix = new ArrayList<>();
|
||||
matrix.add(List.of(1));
|
||||
|
||||
assertEquals(1, MedianOfMatrix.median(matrix));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEmptyMatrixThrowsException() {
|
||||
Iterable<List<Integer>> emptyMatrix = Collections.emptyList();
|
||||
assertThrows(IllegalArgumentException.class, () -> MedianOfMatrix.median(emptyMatrix), "Expected median() to throw, but it didn't");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user