
在处理二维数组(矩阵)数据时,我们经常需要找出特定维度上的统计信息,例如哪一行或哪一列的平均值最高。最初,这可能通过两个独立的方法来实现:一个用于查找最高平均行,另一个用于查找最高平均列。然而,将这两个功能合并到一个方法中会面临几个挑战:
由于Java方法不能直接返回多个独立的值,我们需要一种机制来封装这些值。以下是几种常见的方法:
可以使用 int[] 或 String[] 来存储结果。例如,new int[]{rowIndex, colIndex}。 优点:简单直接。 缺点:语义不明确,调用者需要记住数组中每个位置代表的含义。
创建一个简单的Java类(Plain Old Java Object),包含所需的字段(例如 highestRowIndex 和 highestColIndex),以及相应的构造函数、getter方法等。 优点:语义清晰,可扩展性强。 缺点:代码量相对较大。
Java Record 是 Java 16 引入的一种特殊类,专为不可变数据载体设计,非常适合作为方法的多值返回类型。它自动生成构造函数、访问器、equals()、hashCode() 和 toString() 方法,代码简洁高效。
示例:使用 Record 定义结果类型
public record HighestAverageResult(int highestRowIndex, int highestColIndex) {
// 可以添加自定义方法,例如用于格式化输出
@Override
public String toString() {
return "R" + (highestRowIndex + 1) + "C" + (highestColIndex + 1);
}
public String getRowString() {
return "R" + (highestRowIndex + 1);
}
public String getColumnString() {
return "C" + (highestColIndex + 1);
}
}通过定义 HighestAverageResult 这个 Record,我们的合并方法就可以返回一个包含行和列索引的单一对象,并且可以方便地进行字符串格式化。
立即学习“Java免费学习笔记(深入)”;
现在我们将两个独立的功能合并到一个方法中,并修正原始代码中的逻辑错误。
import java.util.Arrays;
// 定义用于返回结果的Record类型
public record HighestAverageResult(int highestRowIndex, int highestColIndex) {
// 默认的访问器方法已由Record自动生成
// 提供一个自定义的toString方法,以符合R3C3的输出格式
@Override
public String toString() {
// 索引通常从0开始,但输出要求R3、C3,所以需要加1
return "R" + (highestRowIndex + 1) + ", C" + (highestColIndex + 1);
}
// 可以提供单独的格式化方法
public String toCombinedString() {
return "R" + (highestRowIndex + 1) + "C" + (highestColIndex + 1);
}
}
public class ArrayAverageFinder {
/**
* 查找二维数组中具有最高平均值的行和列的索引。
*
* @param grid 一个二维的double类型数组。
* @return 包含最高平均行索引和最高平均列索引的HighestAverageResult对象。
* 如果输入数组为空或不规则,返回-1作为索引。
*/
public static HighestAverageResult findHighestAverageRowAndColumn(double[][] grid) {
// 处理空数组或不规则数组的情况
if (grid == null || grid.length == 0 || grid[0].length == 0) {
System.out.println("Warning: Input grid is empty or invalid.");
return new HighestAverageResult(-1, -1); // 返回无效索引
}
int numRows = grid.length;
int numCols = grid[0].length; // 假设所有行的列数相同
// --- 查找最高平均行 ---
double maxRowAverage = Double.MIN_VALUE; // 初始化为最小值,确保任何有效平均值都能被更新
int highestRowIndex = -1;
for (int i = 0; i < numRows; i++) {
double currentRowSum = 0;
// 确保行不为空
if (grid[i].length == 0) {
System.out.println("Warning: Row " + i + " is empty, skipping.");
continue;
}
for (int j = 0; j < grid[i].length; j++) {
currentRowSum += grid[i][j];
}
double currentRowAverage = currentRowSum / grid[i].length;
if (currentRowAverage > maxRowAverage) {
maxRowAverage = currentRowAverage;
highestRowIndex = i;
}
// System.out.println("Average of row " + (i + 1) + " = " + currentRowAverage); // 调试输出
}
// System.out.println("Highest average row is R" + (highestRowIndex + 1) + " with average " + maxRowAverage); // 调试输出
// --- 查找最高平均列 ---
double maxColAverage = Double.MIN_VALUE; // 初始化为最小值
int highestColIndex = -1;
for (int j = 0; j < numCols; j++) { // 遍历每一列
double currentColSum = 0;
for (int i = 0; i < numRows; i++) { // 遍历当前列的所有行
currentColSum += grid[i][j];
}
double currentColAverage = currentColSum / numRows; // 列平均值是列和除以行数
if (currentColAverage > maxColAverage) {
maxColAverage = currentColAverage;
highestColIndex = j;
}
// System.out.println("Average of column " + (j + 1) + " = " + currentColAverage); // 调试输出
}
// System.out.println("Highest average column is C" + (highestColIndex + 1) + " with average " + maxColAverage); // 调试输出
return new HighestAverageResult(highestRowIndex, highestColIndex);
}
public static void main(String[] args) {
double[][] matrix = {
{1.0, 2.0, 3.0},
{4.0, 5.0, 6.0},
{7.0, 8.0, 9.0}
};
System.out.println("Testing with matrix:");
for (double[] row : matrix) {
System.out.println(Arrays.toString(row));
}
HighestAverageResult result = findHighestAverageRowAndColumn(matrix);
System.out.println("\nResult: " + result); // 使用Record的toString方法
System.out.println("Combined String: " + result.toCombinedString()); // 使用自定义方法
System.out.println("Highest average row: " + result.getRowString());
System.out.println("Highest average column: " + result.getColumnString());
double[][] anotherMatrix = {
{10.0, 1.0, 2.0},
{3.0, 40.0, 5.0},
{6.0, 7.0, 80.0}
};
System.out.println("\nTesting with another matrix:");
for (double[] row : anotherMatrix) {
System.out.println(Arrays.toString(row));
}
HighestAverageResult result2 = findHighestAverageRowAndColumn(anotherMatrix);
System.out.println("\nResult: " + result2);
System.out.println("Combined String: " + result2.toCombinedString());
}
}通过本文,我们学习了如何将查找二维数组最高平均行和最高平均列的功能合并到一个方法中。关键的解决方案包括:
这种方法不仅提升了代码的模块化和可读性,也为处理类似的多结果返回场景提供了通用的解决方案。
以上就是Java中合并查找二维数组最高平均行与列的方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号