Array/Homework
AP CSA FRQ Array/Arraylist Homework
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 Matrix {
public static void main(String[] args) {
// Get matrix size from user
Scanner scan = new Scanner(System.in);
System.out.print("Enter the array size n: ");
int n = scan.nextInt();
// Make the array
int[][] array = new int[n][n];
// Fill array with random 0s and 1s
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
// Generate random 0 or 1
array[i][j] = (int)(Math.random() * 2);
}
}
// Print the array
System.out.println("The random array is");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]);
}
System.out.println();
}
// Find rows with most 1s
ArrayList<Integer> rowList = new ArrayList<>();
int mostOnes = 0;
// Check each row
for (int i = 0; i < array.length; i++) {
int count = 0;
// Count 1s in this row
for (int j = 0; j < array[i].length; j++) {
if (array[i][j] == 1) {
count = count + 1;
}
}
// If we found more 1s than before
if (count > mostOnes) {
mostOnes = count;
rowList.clear(); // Clear old row numbers
rowList.add(i); // Add new row number
}
// If we found same number of 1s
else if (count == mostOnes) {
rowList.add(i);
}
}
// Find columns with most 1s
ArrayList<Integer> colList = new ArrayList<>();
mostOnes = 0;
// Check each column
for (int j = 0; j < array[0].length; j++) {
int count = 0;
// Count 1s in this column
for (int i = 0; i < array.length; i++) {
if (array[i][j] == 1) {
count = count + 1;
}
}
// If we found more 1s than before
if (count > mostOnes) {
mostOnes = count;
colList.clear(); // Clear old column numbers
colList.add(j); // Add new column number
}
// If we found same number of 1s
else if (count == mostOnes) {
colList.add(j);
}
}
// Print results
System.out.print("The largest row index: ");
for (int i = 0; i < rowList.size(); i++) {
System.out.print(rowList.get(i));
if (i < rowList.size() - 1) {
System.out.print(", ");
}
}
System.out.println();
System.out.print("The largest column index: ");
for (int i = 0; i < colList.size(); i++) {
System.out.print(colList.get(i));
if (i < colList.size() - 1) {
System.out.print(", ");
}
}
System.out.println();
}
}
MatrixAnalysis.main(null);
Enter the array size n: The random array is
000100
110011
011000
100010
000001
101010
The largest row index: 1
The largest column index: 0, 4