Last active
April 2, 2022 22:54
-
-
Save rwillians/ff61238a352fa377a94577e32aae5dec to your computer and use it in GitHub Desktop.
Hacker Rank - DS - 2D Arrays - JavaScript
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 input = [ | |
[-9, -9, -9, 1, 1, 1], | |
[ 0, -9, 0, 4, 3, 2], | |
[-9, -9, -9, 1, 2, 3], | |
[ 0, 0, 8, 6, 6, 0], | |
[ 0, 0, 0, -2, 0, 0], | |
[ 0, 0, 1, 2, 4, 0] | |
] | |
const buildVectorsForSquareMatrix = (matrixSize) => { | |
const vectors = [] | |
for (let x = 0; x < matrixSize; x++) { | |
for (let y = 0; y < matrixSize; y++) { | |
vectors.push([x, y]) | |
} | |
} | |
return vectors | |
} | |
const maybeHourglassFromStartingVector = ([x, y], matrix, matrixSize) => { | |
// we're too close to the bottom edge, the hourglass won't fit | |
if ((y + 3) > matrixSize) { | |
return null | |
} | |
// we're too close to the right edge, the hourglass won't fit | |
if ((x + 3) > matrixSize) { | |
return null | |
} | |
// x0 x1 x2 | |
// y0 -9 -9 -9 | |
// y1 -9 | |
// y2 -9 -9 -9 | |
return [ | |
matrix[y].slice(x, x + 3), | |
[ matrix[y + 1][x + 1] ], | |
matrix[y + 2].slice(x, x + 3) | |
] | |
} | |
const sumMatrix = (matrix) => { | |
return matrix | |
.flat() | |
.reduce((a, b) => a + b) | |
} | |
const getHourglassWithHighestSum = (matrix) => { | |
const matrixSize = matrix.length | |
const hourglassSums = buildVectorsForSquareMatrix(matrixSize) | |
.map((startingVector) => maybeHourglassFromStartingVector(startingVector, matrix, matrixSize)) | |
.filter((hourglass) => hourglass !== null) | |
.map(hourglass => sumMatrix(hourglass)) | |
return Math.max(...hourglassSums) | |
} | |
console.log('max', getHourglassWithHighestSum(input)) | |
// 28 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment