-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2d_array.js
More file actions
61 lines (47 loc) · 1.51 KB
/
2d_array.js
File metadata and controls
61 lines (47 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* @link Problem definition [[docs/hackerrank/interview_preparation_kit/arrays/2d_array.md]]
*/
function gethourGlass(arr, positionX, positionY) {
const result = [];
// top
result.push(arr[positionX - 1][positionY - 1]);
result.push(arr[positionX - 1][positionY]);
result.push(arr[positionX - 1][positionY + 1]);
// middle
result.push(arr[positionX][positionY]);
// bottom
result.push(arr[positionX + 1][positionY - 1]);
result.push(arr[positionX + 1][positionY]);
result.push(arr[positionX + 1][positionY + 1]);
return result;
}
function hourglassSum(arr) {
let matrixSize = 0;
if (arr?.[0]) {
matrixSize = arr.length;
}
const matrixStartIndex = 1;
const matrixStopIndex = matrixSize - 2;
console.debug(`matrix size ${matrixSize}`);
let maxHourglassSum = null;
// recorrido
for (let i = matrixStartIndex; i <= matrixStopIndex; i++) {
for (let j = matrixStartIndex; j <= matrixStopIndex; j++) {
// hourglass centers
console.debug(`posicion (${i},${j}): ${arr[i][j]}`);
const houglassValues = gethourGlass(arr, i, j);
const thisHourglassSum = houglassValues.reduce((a, b) => a + b, 0);
console.debug(houglassValues, `thisHourglassSum: ${thisHourglassSum}`);
if (
maxHourglassSum === undefined ||
maxHourglassSum === null ||
thisHourglassSum > maxHourglassSum
) {
maxHourglassSum = thisHourglassSum;
}
}
}
return maxHourglassSum;
}
export default { hourglassSum };
export { hourglassSum };