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
import java.util.ArrayList;
import java.util.Scanner;
public class MatrixMaxOnes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the array size n: ");
int n = input.nextInt();
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();
}
int maxRowCount = 0;
ArrayList<Integer> maxRows = new ArrayList<>();
for (int i = 0; i < n; i++) {
int rowCount = 0;
for (int j = 0; j < n; j++) {
rowCount += matrix[i][j];
}
if (rowCount > maxRowCount) {
maxRowCount = rowCount;
maxRows.clear();
maxRows.add(i);
} else if (rowCount == maxRowCount) {
maxRows.add(i);
}
}
int maxColCount = 0;
ArrayList<Integer> maxCols = new ArrayList<>();
for (int j = 0; j < n; j++) {
int colCount = 0;
for (int i = 0; i < n; i++) {
colCount += matrix[i][j];
}
if (colCount > maxColCount) {
maxColCount = colCount;
maxCols.clear();
maxCols.add(j);
} else if (colCount == maxColCount) {
maxCols.add(j);
}
}
System.out.println("The largest row index: " + listToString(maxRows));
System.out.println("The largest column index: " + listToString(maxCols));
}
private static String listToString(ArrayList<Integer> list) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i < list.size() - 1) {
sb.append(", ");
}
}
return sb.toString();
}
}
MatrixMaxOnes.main(null);
Enter the array size n: The random array is
0011000
0000010
0110011
1111001
1101001
0001000
0001001
The largest row index: 3
The largest column index: 3