Day 11: 2D Arrays(30 Days of Code)

Task

Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.

Example

In the array shown above, the maximum hourglass sum is 7 for the hourglass in the top left corner.

Input Format

There are 6 lines of input, where each line contains 6 space-separated integers that describe the 2D Array A.

Constraints

  • -9 <= A[i][j] <= 9
  • 0 <= i,j <= 5

Output Format

Print the maximum hourglass sum in A.

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

 A contains the following hourglasses:

1 1 1   1 1 0   1 0 0   0 0 0
   1       0       0       0
 1 1 1   1 1 0   1 0 0   0 0 0
 0 1 0   1 0 0   0 0 0   0 0 0
   1       1       0       0
 0 0 2   0 2 4   2 4 4   4 4 0
 1 1 1   1 1 0   1 0 0   0 0 0
   0       2       4       4
 0 0 0   0 0 2   0 2 0   2 0 0
 0 0 2   0 2 4   2 4 4   4 4 0
   0       0       2       0
 0 0 1   0 1 2   1 2 4   2 4 0


The hourglass with the maximum sum (19) is:

2 4 4
  2
1 2 4

solution:

1)JavaScript:

'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}



function main() {

    let arr = Array(6);

    for (let i = 0; i < 6; i++) {
        arr[i] = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
    }
    //write your code from here...
    var arrs = []
    for (var i = 1; i < arr.length - 1;i++){
        for (var j = 1; j < arr[i].length - 1; j++){
            var sum = 0;
            sum = parseInt(arr[i-1][j-1]) + parseInt(arr[i-1][j]) + parseInt(arr[i-1][j+1]);
            sum = sum + parseInt(arr[i][j]);
            sum = sum + parseInt(arr[i+1][j-1]) + parseInt(arr[i+1][j]) + parseInt(arr[i+1][j+1]);
            arrs.push(sum);
        }
    }
   console.log(Math.max.apply(null, arrs));
}