Home > Net >  JAVA How to find the highest number in each row of a 2d array
JAVA How to find the highest number in each row of a 2d array

Time:11-01

I have made it find the max and min value in the entire 2d array seen below but now I'm wanting to make it find the highest value in each row and don't really know how to go about it.

public class Main
{

  public static void main ( String[] args )  
  {
    int[][] data = { {3, 2, 5},
                     {1, 4, 4, 8, 13},
                     {9, 1, 0, 2},
                     {0, 2, 6, 3, -1, -8} };

    
    int max = data[0][0];
    int min = data[0][0];
  
    
    for ( int row=0; row < data.length; row  )
    {
      for ( int col=0; col < data[row].length; col  ) 
      {
         if (data[row][col] > max){
           max = data[row][col];
           
         }
         if (data[row][col] < min){
           min = data[row][col];
         }
      }
    }  

    System.out.println( "max = "   max   "; min = "   min );

  }
}      

I keep getting results like

2
5
4
4
8
1
3
1
1
2
2
6
6
6
6

CodePudding user response:

public static int max(int[][] data) {
    int max = Integer.MIN_VALUE;
    
    for(int row = 0; row < data.length; row  )
        for(int col = 0; col < data[row].length; col  )
            max = Math.max(max, data[row][col]);
    
    return max;
}

public static int min(int[][] data) {
    int min = Integer.MAX_VALUE;

    for(int row = 0; row < data.length; row  )
        for(int col = 0; col < data[row].length; col  )
            min = Math.min(min, data[row][col]);

    return min;
}

public static int[] minPerRow(int[][] data) {
    int[] min = new int[data.length];
    Arrays.fill(min, Integer.MIN_VALUE);

    for(int row = 0; row < data.length; row  )
        for(int col = 0; col < data[row].length; col  )
            min[row] = Math.min(min[row], data[row][col]);

    return min;
}

public static int[] maxPerRow(int[][] data) {
    int[] max = new int[data.length];
    Arrays.fill(max, Integer.MAX_VALUE);

    for(int row = 0; row < data.length; row  )
        for(int col = 0; col < data[row].length; col  )
            max[row] = Math.max(max[row], data[row][col]);

    return max;
}

CodePudding user response:

The following code will print the max and min for each row

for ( int row=0; row < data.length; row  )
{
  for ( int col=0; col < data[row].length; col  ) 
  {
     //Find max as usual
     if (data[row][col] > max){
       max = data[row][col];
     }
     
     //Find min as usual
     if (data[row][col] < min){
       min = data[row][col];
     }
  }
  
  //Print min/max for this row
  System.out.println("row = "   row   "; max = "   max   "; min = "   min );
  
  //Reset min/max
  max = Integer.MIN_VALUE;
  min = Integer.MAX_VALUE;
}

If you'd like to still find the overall max/min, instead of printing the values, add them to an array and find the max/min from there

  • Related