HackerRank - Java 2D Array

You are given a 6x6 2D array. An hourglass in an array is a portion shaped like this:
a b c
  d
e f g
For example, if we create an hourglass using the number 1 within an array full of zeros, it may look like this:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
Actually, there are many hourglasses in the array above. The three leftmost hourglasses are the following:

1 1 1     1 1 0     1 0 0
  1         0         0
1 1 1     1 1 0     1 0 0
The sum of an hourglass is the sum of all the numbers within it. The sum for the hourglasses above are 7, 4, and 2, respectively.

In this problem you have to print the largest sum among all the hourglasses in the array.

Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample Output
19

Explanation
The hourglass which has the largest sum is:

2 4 4
  2
1 2 4

Java Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;

public class java2DArray {
    public static int hourGlassSum(int[][] filter, int[][] grid, int i1, int j1){
        int m = 0;
        int n = 0;
        int res = 0;
        for(int i = i1; i < i1+3; i++){
            for(int j = j1; j < j1+3; j++) {
                res += filter[m][n] * grid[i][j];
                n++;
            }
            m++;
            n=0;
        }
        return res;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
   
        List<List<Integer>> arr = new ArrayList<>();
   
        IntStream.range(0, 6).forEach(i -> {
            try {
                arr.add(
                    Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                        .map(Integer::parseInt)
                        .collect(toList())
                );
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
   
        int[][] grid = new int[6][6];
        int i = 0, j = 0;
        for (List<Integer> l: arr) {
            for (int val: l){
                grid[i][j] = val;
                j++;
            }
            i++;
            j=0;
        }
   
        int[][] filter = {
            {1,1,1},
            {0,1,0},
            {1,1,1}
        };
        int res = Integer.MIN_VALUE;
        for(int m = 0; m < 4; m++ ) {
            for (int n = 0; n < 4 ; n++) {
                res = Math.max(hourGlassSum(filter, grid, m, n), res);
            }
        }
   
        bufferedReader.close();
   
        System.out.println(res);
    }
}

Note: Comment if you want Explanation.

No comments:

Post a Comment

HTML Forms - Input Types - Cheat Sheet

Popular Posts