5

I have been trying to figure this out for a while and need some help. I need to find the min/max values and print them out for a multidimensional array. Here are the two ways that I have tried.

import java.util.*;

class MinMax {
    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}};
        Arrays.sort(data);
        System.out.println("Minimum = " + data[0]);
        System.out.println("Maximum = " + data[data.length - 1]);
    }
}

This version complies but doesn't run.

import java.util.*;

class MinMax {
    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}};

    public static int getMaxValue(int[] numbers) {
        int maxValue = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxValue) {
                maxValue = numbers[i];
            }
            return maxValue;
            {
                public static int getMinValue (int[] numbers) {
                    int minValue = numbers[0];
                    for (int i = 1; i < numbers.length; i++) {
                        if (numbers[i] < minValue) {
                            minValue = numbers[i];
                        }
                    }
                return minValue;
            }

This version just throws me a bunch of errors in compiling. Any help is greatly appreciated.

3
  • Could you please indent your code properly Commented Jul 9, 2016 at 20:47
  • 2
    In each case you seem to be ignoring the fact that you have an array-of-arrays-of-int. Think about how to iterate visiting each int in each int[] array in data. Commented Jul 9, 2016 at 20:48
  • Which version of Java legalised methods inside methods inside methods? Commented Jul 9, 2016 at 20:59

4 Answers 4

9

I have a more fun solution using Java 8 :)

IntSummaryStatistics stats = Arrays.stream(data).flatMapToInt(Arrays::stream).collect(Collectors.summarizingInt(Integer::intValue));
int max = stats.getMax();
int min = stats.getMin();

It's a different solution than yours, obviously. But it does the same thing. To begin with, we convert the 2D array into a Stream of ints. In order to do this first we need to call flatMapToInt. We do this to stream all the elements in the array in a flat way. Imagine if we just start using a single index to iterate over the whole 2D array. It's something like that. Once we have converted the array into a stream, we will use IntSummaryStatistics in order to reuse the same stream for both min and max.

Sign up to request clarification or add additional context in comments.

6 Comments

Method references are fun: x -> Arrays.stream(x) can be simplified to Arrays::stream.
You know what I find really funny. Once I started doing the Java8 thing , some things are just soo... ridiculously simple and require so much less code. I wonder how have we coded before Java 8 ?
There was a small error in the example that I corrected through the usage of IntSummaryStatistics. @Fanchen Bao pointed out a stream can be consumed only once. Therefore we use IntSummaryStatistics in order to avoid recreating the same stream for min and max.
this code didn't work for me, however, a small change and it works by using this: Arrays.stream(gameField).flatMapToInt(Arrays::stream).summaryStatistics();
@luckyguy73 this really helped, not sure how Alex got his code to work as I had your same problem.
|
5

Ok, I've kinda fixed your code. Actually your mistake was that you have not been traversing all the cells of your multidimensional array.

So, I've added additional loop into getMinValue/getMinValue methods and fixed array elements addressing.

import java.util.*;

class MinMax {
    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}
        };
        System.out.println(getMaxValue(data));
        System.out.println(getMinValue(data));
    }


    public static int getMaxValue(int[][] numbers) {
        int maxValue = numbers[0][0];
        for (int j = 0; j < numbers.length; j++) {
            for (int i = 0; i < numbers[j].length; i++) {
                if (numbers[j][i] > maxValue) {
                    maxValue = numbers[j][i];
                }
            }
        }
        return maxValue;
    }

    public static int getMinValue(int[][] numbers) {
        int minValue = numbers[0][0];
        for (int j = 0; j < numbers.length; j++) {
            for (int i = 0; i < numbers[j].length; i++) {
                if (numbers[j][i] < minValue ) {
                    minValue = numbers[j][i];
                }
            }
        }
        return minValue ;
    }
}

1 Comment

Oh okay I see. Thank you so much! I've been pulling my hairs out on this one
0

Your problem is: You are sorting the array of int arrays instead of sorting each individual int in each int array.

To solve this: Loop through each int array in the array of int arrays.

Instructions for finding the maximum and minimum of a 2D int array using Arrays.sort():

  1. Declare a 2D int array to sort called data.
  2. Declare two ints, one to hold the maximum value, the other the minimum value.
    • The initial value of the maximum should be Integer.MIN_VALUE and the initial value of the minimum should be Integer.MAX_VALUE to make sure that negative values are handled.
  3. Loop through data from 0 to data.length:
    1. Sort data[i]
    2. Check if the first value of data[i] is less than the minimum and change it if it is.
    3. Check if the last value of data[i] is greater than the maximum and change it if it is.
  4. Output your result.

Example:

import java.util.Arrays;

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 maximum = Integer.MIN_VALUE;
        int minimum = Integer.MAX_VALUE;

        for(int i = 0; i < data.length; i++) {
            Arrays.sort(data[i]);

            if(data[i][0] < minimum) minimum = data[i][0];
            if(data[i][data[i].length - 1] > maximum) maximum = data[i][data[i].length - 1];
        }

        System.out.println("Minimum = " + maximum);  
        System.out.println("Maximum = " + minimum); 
    }
}

1 Comment

I was able to figure out how to find the values using a 1D array, thanks for the detail on how to declare it for a 2D array!
-2
package array;

public class Max_number {
    
    // 2 5 7 9
    // 3 6 8 1
    
    public static void main (String[] arg) {
        int a[][] = {{2,5,7,9},{3,6,8,1}};
        int max=a[0][0];
        for (int i=0; i<2; i++)   // row
        {
            for (int j=0; j<4; j++) // column
            {
                if(a[i][j]>max)
                {
                    max=a[i][j];
                }
            }
        }
        System.out.println("maximum number is"+max);
    }
}

1 Comment

Please don't just post code, but explain how this answers the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.