Skip to content

refactor: improving MedianOfMatrix #6376

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions src/main/java/com/thealgorithms/matrix/MedianOfMatrix.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@ private 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);

// Calculate the middle index
int mid = (0 + linear.size() - 1) / 2;
if (flattened.isEmpty()) {
throw new IllegalArgumentException("Matrix must contain at least one element.");
}

// Return the median
return linear.get(mid);
Collections.sort(flattened);
return flattened.get((flattened.size() - 1) / 2);
}
}
16 changes: 16 additions & 0 deletions src/test/java/com/thealgorithms/matrix/MedianOfMatrixTest.java
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -31,4 +33,18 @@ public void testMedianWithEvenNumberOfElements() {

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");
}
}
Loading