2D Arrays HW
here is my 2d arrays HW frq
public class ArrayResizer {
/**
* this checks if every value in row r of array2D is not zero
*/
public static boolean isNonZeroRow(int[][] array2D, int r) {
for (int value : array2D[r]) {
if (value == 0) {
return false; // it finds a zero, so the row aint non-zero
}
}
return true; // no zeros found, row is all non-zero
}
/**
* counts how many rows in the array2D have all non-zero values
*/
public static int numNonZeroRows(int[][] array2D) {
int count = 0;
for (int r = 0; r < array2D.length; r++) {
if (isNonZeroRow(array2D, r)) {
count++; // increases count if the row has no zeros
}
}
return count;
}
/**
* creates a new 2D array with only non-zero rows from array2D
*/
public static int[][] resize(int[][] array2D) {
int newRowCount = numNonZeroRows(array2D); // getss number of non-zero rows
int[][] resizedArray = new int[newRowCount][array2D[0].length];
int newRowIdx = 0;
for (int r = 0; r < array2D.length; r++) {
if (isNonZeroRow(array2D, r)) {
// copies the non-zero row into the new array
for (int c = 0; c < array2D[0].length; c++) {
resizedArray[newRowIdx][c] = array2D[r][c];
}
newRowIdx++; // moves to the next row in the new array
}
}
return resizedArray;
}
}