Saturday, January 26, 2019

2D Array - DS - Hacker Rank Solution

Given a  2D Array:
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
We define an hourglass in  to be a subset of values with indices falling in this pattern in 's graphical representation:
a b c
  d
e f g
There are  hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.
For example, given the 2D array:
-9 -9 -9  1 1 1 
 0 -9  0  4 3 2
-9 -9 -9  1 2 3
 0  0  8  6 6 0
 0  0  0 -2 0 0
 0  0  1  2 4 0
We calculate the following  hourglass values:
-63, -34, -9, 12, 
-10, 0, 28, 23, 
-27, -11, -2, 10, 
9, 17, 25, 18
Our highest hourglass value is  from the hourglass:
0 4 3
  1
8 6 6
Note: If you have already solved the Java domain's Java 2D Array challenge, you may wish to skip this challenge.
Function Description
Complete the function hourglassSum in the editor below. It should return an integer, the maximum hourglass sum in the array.
hourglassSum has the following parameter(s):
  • arr: an array of integers
Input Format
Each of the  lines of inputs  contains  space-separated integers .
Constraints
Output Format
Print the largest (maximum) hourglass sum found in .
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
 contains the following hourglasses:
image
The hourglass with the maximum sum () is:
2 4 4
  2
1 2 4
2D Array - DS -  - Hacker Rank Solution
Given the fixed small size of the problem, brute force is fine.
Points to note:-
  1. Negative values possible.
  2. Maximum sum can be less than zero.
  3. Range of element value is -9 to 9.
  4. Numbers to be summed for each hourglass = 7.
  5. Minimum possible value for sum = .
So we'll initialize our maxSum to -63. From there, we just calculate the sums of all hourglasses and return the maxSum. Here is an implementation of the function in Python:
def array2D(arr):

    # want to find the maximum hourglass sum
    # minimum hourglass sum = -9 * 7 = -63
    maxSum = -63
    
    for i in range(4):
        for j in range(4):
        
            # sum of top 3 elements
            top = sum(arr[i][j:j+3])
            
            # sum of the mid element
            mid = arr[i+1][j+1]
            
            # sum of bottom 3 elements
            bottom = sum(arr[i+2][j:j+3])
            
            hourglass = top + mid + bottom
            
            if hourglass > maxSum:
                maxSum = hourglass
                
    return maxSum
public class Solution {
    private static final int _MAX = 6; // size of matrix
    private static final int _OFFSET = 2; // hourglass width
    private static int matrix[][] = new int[_MAX][_MAX];
    private static int maxHourglass = -63; // initialize to lowest possible sum (-9 x 7)
    
    /** Given a starting index for an hourglass, sets maxHourglass
    *   @param i row 
    *   @param j column 
    **/
    private static void hourglass(int i, int j){
        int tmp = 0; // current hourglass sum
        
        // sum top 3 and bottom 3 elements
        for(int k = j; k <= j + _OFFSET; k++){
            tmp += matrix[i][k]; 
            tmp += matrix[i + _OFFSET][k]; 
        }
        
        // sum middle element
        tmp += matrix[i + 1][j + 1]; 
        
        if(maxHourglass < tmp){
            maxHourglass = tmp;
        }
    }

    public static void main(String[] args) {
        // read inputs
        Scanner scan = new Scanner(System.in); 
        for(int i=0; i < _MAX; i++){
            for(int j=0; j < _MAX; j++){
                matrix[i][j] = scan.nextInt();
            }
        }
        scan.close();
        
        // find maximum hourglass
        for(int i=0; i < _MAX - _OFFSET; i++){
            for(int j=0; j < _MAX - _OFFSET; j++){
                hourglass(i, j);
            }
        }
        
        // print maximum hourglass
        System.out.println(maxHourglass);
    }
}

9 comments:

  1. int hourglassSum(int arr_rows, int arr_columns, int **arr) {
    int sum[4][4];
    int i,j,maxsum;
    for(i=0;i<arr_rows-1;i++){
    for(j=0;j<arr_columns-1;j++){
    sum[i][j]=arr[i][j]+arr[i+1][j]+arr[i+2][j]+arr[i+1][j+1]+arr[i][j+2]+arr[i+1][j+2]+arr[i+2][j+2]; }
    }
    maxsum=sum[0][0];
    for(i=0;i<arr_rows-1;i++){
    for(j=0;j<arr_columns-1;j++){
    if(maxsum<=sum[i][j]){
    maxsum=sum[i][j];
    }

    }
    }
    printf("%d",maxsum);
    return 0;
    }

    int main()
    {
    int i,j,arr_rows,arr_columns,maxsum;
    int **arr[6][6];
    arr_rows=arr_columns=6;
    for(i=0;i<arr_rows;i++){
    for(j=0;j<arr_columns;j++){
    scanf("%d ",arr[i][j]);
    }
    }
    maxsum=hourglassSum(arr_rows,arr_columns,**arr);
    printf("%d",maxsum);
    }
    please check my code and tell me whats wrong..i am not able to debug

    ReplyDelete
  2. include header file #include in program.
    also use * in printf("%d",*arr[i][j]);

    ReplyDelete
  3. There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.

    For example, given the 2D array:
    #!/bin/python3

    import math
    import os
    import random
    import re
    import sys

    # Complete the hourglassSum function below.
    def hourglassSum(arr):
    lst=[]
    lr = len(arr[0])-3
    for i in range(len(arr[0])):
    if i<=lr:
    m1=sum(arr[0][0+i:3+i])+(arr[1][1+i])+sum(arr[2][0+i:3+i])
    lst.append(m1)

    if i<=lr:
    m2=sum(arr[1][0+i:3+i])+(arr[2][1+i])+sum(arr[3][0+i:3+i])
    lst.append(m2)

    if i<=lr:
    m3=sum(arr[2][0+i:3+i])+(arr[3][1+i])+sum(arr[4][0+i:3+i])
    lst.append(m3)

    if i<=lr:
    m4=sum(arr[3][0+i:3+i])+(arr[4][1+i])+sum(arr[5][0+i:3+i])
    lst.append(m4)

    return max(lst)


    if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    arr = []

    for _ in range(6):
    arr.append(list(map(int, input().rstrip().split())))

    result = hourglassSum(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

    ReplyDelete
  4. is there any c++ users who exist in the world

    ReplyDelete
  5. #!/bin/python3

    import math
    import os
    import random
    import re
    import sys

    # Complete the hourglassSum function below.
    def hourglassSum(arr):
    a = []
    for k in range(0,4):
    for i in range(0,4):
    sum = 0
    for j in range(0,3):
    sum += (arr[k][i+j] + arr[2+k][i+j])
    sum += arr[1+k][1+i]
    a.append(sum)

    return max(a)

    if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    arr = []

    for _ in range(6):
    arr.append(list(map(int, input().rstrip().split())))

    result = hourglassSum(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

    ReplyDelete

Powered by Blogger.