Last active
August 17, 2023 06:05
-
-
Save MohamedGamil/780417c70265c1b62bb379b5a23de196 to your computer and use it in GitHub Desktop.
HackerRank: 2D Array - DS (Solution)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const fs = require('fs'); | |
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++]; | |
} | |
/* | |
* Complete the 'hourglassSum' function below. | |
* | |
* The function is expected to return an INTEGER. | |
* The function accepts 2D_INTEGER_ARRAY arr as parameter. | |
*/ | |
function hourglassSum(arr) { | |
// Number of hourglasses per row (fixed) | |
const perRow = 4; | |
// Number of hourglasses (fixed) | |
const total = 16; | |
// Hourglasses sums array | |
const sums = []; | |
// Loop through each hourglass and calculate its sum | |
for (let k = 0; k < total; k++) { | |
// The starting index of the hourglass is determined by ceiling | |
// the product of dividing current hourglass index by | |
// `perRow` (4), then limiting the number to (0). | |
const i = Math.max(Math.ceil(k / perRow) - 1, 0); | |
// Loop through each hourglass per row | |
for (let j = 0; j < perRow; j++) { | |
// Calculate the upper columns ⏳ by slicing from `j` to `j + 3` | |
// where `j` is limited to the number of hourglasses per row. | |
const upper = arr[i] | |
.slice(j, j + 3) | |
.reduce((t, v) => t += v, 0); | |
// Calculate the lower columns ⌛️ by slicing from `j` to `j + 3` | |
// where `j` is limited to the number of hourglasses per row. | |
// And `i + 2` which points to 2 steps lower at current | |
// row index. | |
const lower = arr[i + 2] | |
.slice(j, j + 3) | |
.reduce((t, v) => t += v, 0); | |
// Get the value of the middle column at `i + 1`, and `j + 1` | |
const middle = arr[i + 1][j + 1]; | |
// Push the hourglass sum to the array | |
sums.push( | |
upper + lower + middle | |
); | |
} | |
} | |
// Return the highest value using a combination of the | |
// spread operator and `Math.max(...)` function. | |
return Math.max(...sums); | |
} | |
function main() { | |
const ws = fs.createWriteStream(process.env.OUTPUT_PATH); | |
let arr = Array(6); | |
for (let i = 0; i < 6; i++) { | |
arr[i] = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10)); | |
} | |
const result = hourglassSum(arr); | |
ws.write(result + '\n'); | |
ws.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Function code only: