[英]Find index of minimum value in each row in 2D Array in java
I need to get the index of the minimum value in each row in my 2D array (array [][]) in Java.我需要在 Java 中获取二维数组(数组 [][])中每一行的最小值的索引。 MY array holds several floats I'm a beginner, so please don't hate me and help me.我的数组有几个浮点数我是初学者,所以请不要恨我并帮助我。 Thanks!谢谢!
void findMinimumIndex( float[][] data )
{
int x = 0 , y = 0;
float assumedMin = 0.0f;
int lastSmallestXIndex , lastSmallestYIndex;
ArrayList<Integer> minIndexListInRows = new ArrayList<>();
for( x = 0; x < data.length; x++ )
{
for( y = 1 , assumedMin = data[x][y - 1]; y < data[x].length; y++ )
{
if( assumedMin < data[x][y] )
{
assumedMin = data[x][y];
lastSmallestXIndex = x;
lastSmallestYIndex = y;
}
}
System.out.println("In (" + x + "," + y + "), smallest float is: " + assumedMin + ", At: {" + lastSmallestXIndex + "," + lastSmallestYIndex + "}");
}
}
minIndexListInRows, is where you can apply your tricks to to atleast play your part, this code area is your smoking gun; minIndexListInRows,是你可以应用你的技巧来至少发挥你的作用的地方,这个代码区域是你的吸烟枪;
for( y = 1 , assumedMin = data[x][y - 1]; y < data[x].length; y++ )
{
if( assumedMin < data[x][y] )
{
assumedMin = data[x][y];
lastSmallestXIndex = x;
lastSmallestYIndex = y;
}
}
You could use an auxiliary method rowMinsIndex
where you pass in in your two dimensional array like so:您可以使用辅助方法rowMinsIndex
在其中传入二维数组,如下所示:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[][] twoDimensionalArray = new int[][]{
{ 1, 2, 5 },
{ 4, 3, 6 },
{ 7, 5, 9 }
};
System.out.println("The twoDimensionalArray is: " + Arrays.deepToString(twoDimensionalArray));
int[] minsOfEachRow = rowMinsIndex(twoDimensionalArray);
for(int i = 0; i < minsOfEachRow.length; i++) {
System.out.println("The index of the minimum of row " + i + " is: " + minsOfEachRow[i]);
}
}
public static int[] rowMinsIndex(int[][] nums) {
int [] count = new int [nums.length];
int [] minIndexes = new int [nums.length];
Arrays.fill(count, Integer.MAX_VALUE);
for(int i = 0; i < count.length; i++){
for(int x = 0; x < nums[0].length; x++){
if(nums[i][x] < count[i]){
count[i] = nums[i][x];
minIndexes[i] = x;
}
}
}
return minIndexes;
}
}
Ouput:输出:
The twoDimensionalArray is: [[1, 2, 5], [4, 3, 6], [7, 5, 9]]
The index of the minimum of row 0 is: 0
The index of the minimum of row 1 is: 1
The index of the minimum of row 2 is: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.