Add median of matrix (#4590)
This commit is contained in:
parent
536978919d
commit
5f5a61de87
30
src/main/java/com/thealgorithms/misc/MedianOfMatrix.java
Normal file
30
src/main/java/com/thealgorithms/misc/MedianOfMatrix.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Median of Matrix (https://medium.com/@vaibhav.yadav8101/median-in-a-row-wise-sorted-matrix-901737f3e116)
|
||||
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
|
||||
*/
|
||||
|
||||
public final class MedianOfMatrix {
|
||||
|
||||
public static int median(List<List<Integer>> matrix) {
|
||||
// Flatten the matrix into a 1D list
|
||||
List<Integer> linear = new ArrayList<>();
|
||||
for (List<Integer> row : matrix) {
|
||||
linear.addAll(row);
|
||||
}
|
||||
|
||||
// Sort the 1D list
|
||||
Collections.sort(linear);
|
||||
|
||||
// Calculate the middle index
|
||||
int mid = (0 + linear.size() - 1) / 2;
|
||||
|
||||
// Return the median
|
||||
return linear.get(mid);
|
||||
}
|
||||
}
|
34
src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java
Normal file
34
src/test/java/com/thealgorithms/misc/MedianOfMatrixtest.java
Normal file
@ -0,0 +1,34 @@
|
||||
package com.thealgorithms.misc;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class MedianOfMatrixtest {
|
||||
|
||||
@Test
|
||||
public void testMedianWithOddNumberOfElements() {
|
||||
List<List<Integer>> matrix = new ArrayList<>();
|
||||
matrix.add(Arrays.asList(1, 3, 5));
|
||||
matrix.add(Arrays.asList(2, 4, 6));
|
||||
matrix.add(Arrays.asList(7, 8, 9));
|
||||
|
||||
int result = MedianOfMatrix.median(matrix);
|
||||
|
||||
assertEquals(5, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMedianWithEvenNumberOfElements() {
|
||||
List<List<Integer>> matrix = new ArrayList<>();
|
||||
matrix.add(Arrays.asList(2, 4));
|
||||
matrix.add(Arrays.asList(1, 3));
|
||||
|
||||
int result = MedianOfMatrix.median(matrix);
|
||||
|
||||
assertEquals(2, result);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user