简体   繁体   English

查找2D数组中最大和最小数字的索引

[英]finding the index of largest and smallest numbers in a 2D Array

I'm really stumped trying to find the index of the largest and smallest numbers of a 5x5 array with random numbers up to 1000 generated into them. 我真的很难找到5x5阵列的最大和最小数字的索引,其中随机数量高达1000。 Here my code: 这是我的代码:

import java.util.Random;

public class MaxMinArray {

    public static void main (String args[]) {

    int x=0, y=0, max=0, min=1000;;
    int[][] numbers = new int[5][5];

    for (x=0; x<numbers.length; x++) {                  //outer for          
        for(y=0; y<numbers.length; y++) {               //inner for    
            numbers[x][y]= (int)(Math.random()*1000);   //random generator

            if(max < numbers[x][y])                     //max number
                max = numbers[x][y];

            if(min>numbers[x][y])                       //min number
                min = numbers[x][y];

            int maxIndex = 0;

            for(int index = 1; index<numbers.length; index++)
                if(numbers[maxIndex]< numbers[index])
                    maxIndex = index;
            }
        }
        System.out.println("Max number in array:" + max + " ");
        System.out.println("Max number is in" + maxIndex + " ");
        System.out.println("Min number in array:" + min + " ");
    }
}

You should keep track of both the x and y index of the maximum/minimum element. 您应该跟踪最大/最小元素的xy索引。 No need to post-process, it's just a matter of bookkeeping: 无需后期处理,只需记账:

if(max < numbers[x][y]) {
    max = numbers[x][y];
    maxX = x;
    maxY = y;
}

Use a Point to keep track of your indices. 使用Point来跟踪您的指数。

Point min = new Point(0, 0); 
Point max = new Point(0, 0);

for(int[] row: numbers) {
    for(int col= 0; col < row.length; col++) {
        if(numbers[row][col] < numbers[min.X][min.Y])
            {max.X = row; min.Y = col;}
        if(numbers[row][col] > numbers[max.X][max.Y])
            {max.X = row; max.Y = col;}
    } 
}

if(numbers.length > 0) {
    System.out.println(numbers[min.X][min.Y] + " is the minimum.");
    System.out.println(numbers[max.X][max.Y] + " is the maximum."); 
}

for something of this small of scale, a simple double for loop should be the simplest to understand and utilize. 对于这种小规模的东西,简单的双循环应该是最容易理解和利用的。

int n=5;
int min = array[0][0]; 
int[] minIndex = {0,0};
int max = array[0][0];
int[] maxIndex = {0,0};

for (int i=0; i<n; i++) 
{
for (int j=0; j<n; j++) 
{
if (array[i][j] < min) 
{ 
min = array[i][j];
minIndex[0] = i;
minIndex[1] = j;
}
if (array[i][j] > max) { 
max = array[i][j];
maxIndex[0] = i;
maxIndex[1] = j;
}
}
}

For non-trivial dimensions this might be a slow method, but for this size matrix n^2 complexity is fine. 对于非平凡的维度,这可能是一种缓慢的方法,但对于这个大小矩阵,n ^ 2复杂度很好。

EDIT: WOW, I missed the part about the indices. 编辑:哇,我错过了关于指数的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM