题目描述:
代码:
package cqut.mywork;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Test09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the array size n: ");
int[][] matrix = getRandomMatrix(input.nextInt());
System.out.println("The random array is ");
printMatrix(matrix);
System.out.println("The largest row index: " + getMostRowIndex(matrix).toString().replaceAll("[\\[\\]]", ""));
System.out.println("The largest column index: " + getMostColumnIndex(matrix).toString().replaceAll("[\\[\\]]", ""));
input.close();
}
// 生成随机矩阵
public static int[][] getRandomMatrix(int n) {
Random r = new Random();
int[][] matrix = new int[n][n];
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = r.nextInt(2);
return matrix;
}
// 打印矩阵
public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}
}
// 获取最多1的row
public static ArrayList<Integer> getMostRowIndex(int[][] matrix) {
ArrayList<Integer> row = new ArrayList<>();
int[] maxRow = new int[matrix.length];
int sum = 0, max = 0;
for (int i = 0; i < matrix.length; i++) {
sum = 0;
for (int j = 0; j < matrix[i].length; j++)
sum += matrix[i][j];
if (sum > max)
max = sum;
maxRow[i] = sum;
}
for (int i = 0; i < maxRow.length; i++) {
if (maxRow[i] == max)
row.add(i);
}
return row;
}
// 获取最多1的column
public static ArrayList<Integer> getMostColumnIndex(int[][] matrix) {
ArrayList<Integer> column = new ArrayList<>();
int[] maxColumn = new int[matrix.length];
int sum = 0, max = 0;
for (int i = 0; i < matrix.length; i++) {
sum = 0;
for (int j = 0; j < matrix.length; j++)
sum += matrix[j][i];
if (sum > max)
max = sum;
maxColumn[i] = sum;
}
for (int i = 0; i < maxColumn.length; i++) {
if (maxColumn[i] == max)
column.add(i);
}
return column;
}
}
运行结果:
Enter the array size n: 5
The random array is
1 1 1 1 1
0 1 1 0 0
1 0 0 1 0
1 0 0 0 0
0 1 1 0 1
The largest row index: 0
The largest column index: 0, 1, 2