JAVA:最大的行和列

题目描述:

在这里插入图片描述

代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值