Homework

Write a program that randomly fills in 0s and 1s into an n-by-n matrix, prints the matrix, and finds the rows and columns with the most 1s. (Hint: Use two ArrayLists to store the row and column indices with the most 1s.)

Here is a sample run of the program, printed in the console:

Enter the array size n: 4
The random array is
0011
0011
1101
1010
The largest row index: 2
The largest column index: 2, 3 
 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter the array size n: ");
int n = Integer.parseInt(reader.readLine());

int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        matrix[i][j] = (int) (Math.random() * 2);
    }
}

System.out.println("The random array is");
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        System.out.print(matrix[i][j]);
    }
    System.out.println();
}

ArrayList<Integer> AL2dRows = new ArrayList<>();
int maxRowCount = 0;

for (int i = 0; i < n; i++) {
    int rowCount = 0;
    for (int j = 0; j < n; j++) {
        if (matrix[i][j] == 1) {
            rowCount++;
        }
    }
    if (rowCount > maxRowCount) {
        maxRowCount = rowCount;
        AL2dRows.clear();
        AL2dRows.add(i);
    } else if (rowCount == maxRowCount) {
        AL2dRows.add(i);
    }
}

ArrayList<Integer> AL2dCols = new ArrayList<>();
int maxColCount = 0;

for (int j = 0; j < n; j++) {
    int colCount = 0;
    for (int i = 0; i < n; i++) {
        if (matrix[i][j] == 1) {
            colCount++;
        }
    }
    if (colCount > maxColCount) {
        maxColCount = colCount;
        AL2dCols.clear();
        AL2dCols.add(j);
    } else if (colCount == maxColCount) {
        AL2dCols.add(j);
    }
}

System.out.print("The largest row index: ");
for (int i = 0; i < AL2dRows.size(); i++) {
    System.out.print(AL2dRows.get(i));
    if (i < AL2dRows.size() - 1) System.out.print(", ");
}
System.out.println();

System.out.print("The largest column index: ");
for (int i = 0; i < AL2dCols.size(); i++) {
    System.out.print(AL2dCols.get(i));
    if (i < AL2dCols.size() - 1) System.out.print(", ");
}
System.out.println();
Enter the array size n: The random array is
01110
00010
00001
00000
10011
The largest row index: 0, 4
The largest column index: 3