2D Data Cleaning & Validation
Clean and validate 2D integer data: guard null rows, bounds-check indices, clamp out-of-range values, normalize jagged shapes, and produce validation reports.
Why Clean 2D?
Goal: Make 2D integer data safe and consistent. We will: (1) guard null rows, (2) verify bounds per row, (3) clamp values into a valid range, (4) normalize jagged shapes when needed, and (5) produce a validation report.
Nulls & Bounds
Step 1: Replace null rows with empty arrays and copy values defensively. Provide an inBounds helper to guard per-row lengths.
public class Main {
// Make a defensive copy of m. Replace null rows with empty arrays.
static int[][] copyOrEmpty(int[][] m) {
if (m == null) return new int[0][0];
int[][] out = new int[m.length][];
for (int r = 0; r < m.length; r = r + 1) {
if (m[r] == null) {
out[r] = new int[0];
} else {
out[r] = new int[m[r].length];
for (int c = 0; c < m[r].length; c = c + 1) out[r][c] = m[r][c];
}
}
return out;
}
// Safe bounds check for jagged matrices
static boolean inBounds(int[][] m, int r, int c) {
return m != null && r >= 0 && r < m.length && m[r] != null && c >= 0 && c < m[r].length;
}
public static void main(String[] args) {
int[][] raw = new int[][] { null, {1, 2, 3}, {4} };
int[][] cleaned = copyOrEmpty(raw);
System.out.println("rows = " + cleaned.length);
for (int r = 0; r < cleaned.length; r = r + 1) System.out.println("row " + r + " len = " + cleaned[r].length);
System.out.println("inBounds(1,2) = " + inBounds(cleaned, 1, 2)); // true
System.out.println("inBounds(2,2) = " + inBounds(cleaned, 2, 2)); // false
}
}