user3285450
user3285450

Reputation: 1

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. 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 + " ");
    }
}

Upvotes: 0

Views: 5231

Answers (3)

Alex Johnson
Alex Johnson

Reputation: 534

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.

EDIT: WOW, I missed the part about the indices.

Upvotes: 0

Rainbolt
Rainbolt

Reputation: 3660

Use a Point to keep track of your indices.

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."); 
}

Upvotes: 0

Vincent van der Weele
Vincent van der Weele

Reputation: 13177

You should keep track of both the x and y index of the maximum/minimum element. 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;
}

Upvotes: 2

Related Questions