Skip to content

Instantly share code, notes, and snippets.

@rakibulalam
Created May 20, 2020 00:11
Show Gist options
  • Select an option

  • Save rakibulalam/6526295a62dc4f22bd7cada5c80cde12 to your computer and use it in GitHub Desktop.

Select an option

Save rakibulalam/6526295a62dc4f22bd7cada5c80cde12 to your computer and use it in GitHub Desktop.

Revisions

  1. rakibulalam created this gist May 20, 2020.
    60 changes: 60 additions & 0 deletions hourglassSum.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    'use strict';

    const fs = require('fs');

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

    let inputString = '';
    let currentLine = 0;

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

    process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
    .split('\n')
    .map(str => str.replace(/\s*$/, ''));

    main();
    });

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

    // Complete the hourglassSum function below.
    function hourglassSum(arr) {

    const n = arr.length;
    let max = 0;
    for (let i = 0; i < n - 2; i++) {
    const sn = arr[i].length;
    for (let j = 0; j < sn - 2; j++) {
    if (i + 2 < n && j + 2 < sn) {
    const sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j] + arr[i + 2][j + 1] + arr[i + 2][j + 2];
    max = max <= sum || (max === 0 && i === 0) ? sum : max;
    }

    }

    }
    return max;
    }

    function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    let arr = Array(6);

    for (let i = 0; i < 6; i++) {
    arr[i] = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10));
    }

    let result = hourglassSum(arr);

    ws.write(result + "\n");

    ws.end();
    }