Created
October 23, 2020 14:48
-
-
Save beshur/2a1c63d62ebf939cebcb8bf9ab052204 to your computer and use it in GitHub Desktop.
hourglassSum.js
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
/* | |
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 | |
*/ | |
function hourglassSum(arr) { | |
const results = []; | |
const hourGlassIndices = [ | |
[0, 1, 2], | |
[null, 1, null], | |
[0, 1, 2] | |
]; | |
const hourGlassPositions = [ | |
[1, 1, 1, 1], | |
[1, 1, 1, 1], | |
[1, 1, 1, 1], | |
[1, 1, 1, 1] | |
]; | |
const getHourGlassSum = function(arr, x, y) { | |
return hourGlassIndices.reduce((rowSum, row, rowIndex) => { | |
let rowValue = row.reduce((colSum, column, columnIndex) => { | |
if (hourGlassIndices[rowIndex][columnIndex] !== null) { | |
colSum += arr[rowIndex + y][columnIndex + x]; | |
} | |
return colSum; | |
}, 0); | |
return rowSum += rowValue; | |
}, 0); | |
}.bind(null, arr); | |
hourGlassPositions.forEach((row, rowIndex) => { | |
row.forEach((col, columnIndex) => { | |
results.push(getHourGlassSum(columnIndex, rowIndex)); | |
}); | |
}); | |
console.log(results); | |
return Math.max.apply(null, results); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment