Example Questions | Strategies | Homework |
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
Solution
ArrayList<ArrayList<Integer>> FIFHFAGDFEGE_1_26 = new ArrayList<ArrayList<Integer>>();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the array size n: ");
int input = scanner.nextInt();
System.out.print(input);
scanner.close();
Random random = new Random();
System.out.println();
System.out.println("The random array is");
int highestRowValue = 0;
int highestColValue = 0;
ArrayList<Integer> rowIndicies = new ArrayList<Integer>();
ArrayList<Integer> colIndicies = new ArrayList<Integer>();
//row finder
for(int i=0;i<input;i++)
{
int value = 0;
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int j=0;j<input;j++)
{
arr.add(random.nextInt(2));
value += arr.get(j);
System.out.print(arr.get(j));
}
if(value==highestRowValue)
{
highestRowValue = value;
rowIndicies.add(i);
}
if(value>highestRowValue)
{
highestRowValue = value;
rowIndicies = new ArrayList<Integer>();
rowIndicies.add(i);
}
FIFHFAGDFEGE_1_26.add(arr);
System.out.println();
}
//col finder
for(int i=0;i<input;i++)
{
int value = 0;
for(int j=0;j<input;j++)
{
value += FIFHFAGDFEGE_1_26.get(j).get(i);
}
if(value==highestColValue)
{
highestColValue = value;
colIndicies.add(i);
}
if(value>highestColValue)
{
highestColValue = value;
colIndicies = new ArrayList<Integer>();
colIndicies.add(i);
}
}
System.out.println("The largest row index: ");
for(int i=0;i<rowIndicies.size();i++)
{
System.out.print(rowIndicies.get(i) +", ");
}
System.out.println();
System.out.println("The largest column index: ");
for(int i=0;i<colIndicies.size();i++)
{
System.out.print(colIndicies.get(i) +", ");
}
Enter the array size n:
4
The random array is
1100
1101
0100
1010
The largest row index:
1,
The largest column index:
0, 1,