Skip to content

Instantly share code, notes, and snippets.

@beshur
Created October 23, 2020 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beshur/2a1c63d62ebf939cebcb8bf9ab052204 to your computer and use it in GitHub Desktop.
Save beshur/2a1c63d62ebf939cebcb8bf9ab052204 to your computer and use it in GitHub Desktop.
hourglassSum.js
/*
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