[英]java: searching for the minimum in a 2d array and giving back the position of the minimum (row and coumn)
我有一个二维数组,我需要从中知道最小值。 数组中的数字可能不止一次,在这种情况下,第一个是最小的。 之后,我将需要知道在哪个位置(行和列)找到最小值。
我已经在寻找最小值的位置,但是我被确切的位置所困。 到目前为止,您将在下面看到我的代码。
double lowest = Double.parseDouble(excelMatrix[1][1]);
for(int r = 1; r<excelMatrix.length-1; r++){
for(int c = 2; c<excelMatrix[r].length; c++){
double number = Double.parseDouble(excelMatrix[r][c]);
if(lowest > number) lowest = number;
}
}
System.out.print(lowest);
我希望有人可以帮助我解决这个问题。 提前非常感谢您!
Java中的Indxing 0-based
,因此您将完全忽略第一行。 之后,您将忽略第一列中除excelMatrix[1][1]
之外的所有元素。 正确的实现将是:
double lowest = Double.parseDouble(excelMatrix[0][0]);
int row = 0, column = 0;
for(int r = 0; r< excelMatrix.length; r++) {
for(int c = 0; c<excelMatrix[r].length; c++) {
double number = Double.parseDouble(excelMatrix[r][c]);
if(lowest > number) {
lowest = number;
row = r, column = c;
}
}
}
System.out.print(lowest + " at row: " + row + "and column: " + column);
假设您已使用基于1的索引保存了excelMatrix
,则应可以进行以下操作:
添加两个变量以保存最小数量的位置,例如: lowestRow
和lowestCol
。 码:
double lowest = Double.parseDouble(excelMatrix[1][1]);
int lowestRow = 1;
int lowestCol = 1;
for(int r = 1; r<excelMatrix.length; r++){
for(int c = 1; c<excelMatrix[r].length; c++){
double number = Double.parseDouble(excelMatrix[r][c]);
if(lowest > number) {
lowest = number;
lowestRow = r;
lowestCol = c;
}
}
}
System.out.println(lowest);
System.out.println("Row Position of minimum element is" + lowestRow);
System.out.println("Column Position of minimum element is" + lowestCol);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.