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 

HW

public class RandomMatrix {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the array size n: ");
        int n = sc.nextInt();
        
        int[][] matrix = new int[n][n];
        Random rand = new Random();
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = rand.nextInt(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> rowMax = new ArrayList<>();
        int maxRowCount = -1;
        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) {
                rowMax.clear();
                rowMax.add(i);
                maxRowCount = rowCount;
            } else if (rowCount == maxRowCount) {
                rowMax.add(i);
            }
        }

        ArrayList<Integer> colMax = new ArrayList<>();
        int maxColCount = -1;
        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) {
                colMax.clear();
                colMax.add(j);
                maxColCount = colCount;
            } else if (colCount == maxColCount) {
                colMax.add(j);
            }
        }

        System.out.print("The largest row index: ");
        for (int i : rowMax) {
            System.out.print(i + " ");
        }
        System.out.println();

        System.out.print("The largest column index: ");
        for (int j : colMax) {
            System.out.print(j + " ");
        }
        System.out.println();
        
        sc.close();
    }
}