Mark Roff
Mark Roff

Reputation: 1

Returning the lowest even number from a 2D array of positive integers

I'm having trouble returning the lowest even number from a 2D array, however if there isn't an even number, I need to return -1. Right now I think I have the main part on how to simply return the lowest number, however I am having trouble going from here and getting the -1 return, and to check for the even number.

public static int array2DLowestEvenNumber(int[][] nums) {
  int min = nums[0][0];
  for (int j = 0; j < nums.length; j++) {
    for (int i = 0; i < nums[j].length; i++) {
      if (nums[j][i] < min) {
        min = nums[j][i];
      }
    }
  }
  return min;
}

public static void main(String[] args) {
  System.out.println(array2DLowestEvenNumber(new int[][]{{8,2},{2,4}}));
  System.out.println(array2DLowestEvenNumber(new int[][]{{1,50,102},{4,6,7}}));
}

Upvotes: 0

Views: 324

Answers (3)

user16072798
user16072798

Reputation:

You can use enhanced for loops as follows:

public static void main(String[] args) {
    int[][] arr1 = {{8, 2}, {2, 4}};
    int[][] arr2 = {{1, 50, 102}, {4, 6, 7}};
    int[][] arr3 = {{9, 11, 1}, {3, 5, 7}};
    System.out.println(lowestEvenNumber(arr1)); // 2
    System.out.println(lowestEvenNumber(arr2)); // 4
    System.out.println(lowestEvenNumber(arr3)); // -1
}
public static int lowestEvenNumber(int[][] arr) {
    // the maximum value an integer
    // can have is odd = 2147483647
    int min = Integer.MAX_VALUE;
    // rows of the array
    for (int[] row : arr)
        // elements of the rows
        for (int el : row)
            // even number and less than the minimum
            if (el % 2 == 0 && el < min)
                // new minimum
                min = el;
    // minimum even number of the array, or -1
    return min == Integer.MAX_VALUE ? -1 : min;
}

Upvotes: 1

user16055287
user16055287

Reputation:

You can use streams as follows:

public static void main(String[] args) {
    int[][] arr1 = {{8, 2}, {2, 4}};
    int[][] arr2 = {{1, 50, 102}, {4, 6, 7}};
    int[][] arr3 = {{3, 5, 7}, {9, 11, 1}};
    System.out.println(lowestEvenNumber(arr1)); // 2
    System.out.println(lowestEvenNumber(arr2)); // 4
    System.out.println(lowestEvenNumber(arr3)); // -1
}
public static int lowestEvenNumber(int[][] arr) {
    return Arrays.stream(arr)
            // Stream<int[]> to IntStream
            .flatMapToInt(Arrays::stream)
            // even numbers
            .filter(i -> i % 2 == 0)
            // minimum of the array
            .min().orElse(-1);
}

Upvotes: 1

peter
peter

Reputation: 593

The most straightforward solution is:

int min = -1;
for (int j = 0; j < nums.length; j++) {
    for (int i = 0; i < nums[j].length; i++) {
        if(nums[j][i] % 2 == 0) {
            if (nums[j][i] < min || min == -1) {
                min = nums[j][i];
            }
        }
    }
}
return min;

Upvotes: 0

Related Questions