|
| 1 | +/** |
| 2 | + * The assumptions is that the matrices are N x M (either square or rectangular) |
| 3 | + * The matrices cannot have rows with different sizes. |
| 4 | + */ |
| 5 | + |
| 6 | +export function sum(matrix: number[][]): number { |
| 7 | + let sum = 0; |
| 8 | + |
| 9 | + for (let i = 0; i < matrix.length; i += 1) { |
| 10 | + for (let j = 0; j < matrix[i].length; j += 1) { |
| 11 | + sum += matrix[i][j]; |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + return sum; |
| 16 | +} |
| 17 | + |
| 18 | +function getShortestLength(matrix: number[][]): number { |
| 19 | + const rows = matrix.length; |
| 20 | + const columns = matrix[0].length; |
| 21 | + |
| 22 | + if (rows < columns) return rows; |
| 23 | + |
| 24 | + return columns; |
| 25 | +} |
| 26 | + |
| 27 | +export function sumDiagonal(matrix: number[][]): number { |
| 28 | + let sum = 0; |
| 29 | + let index = 0; |
| 30 | + |
| 31 | + const shortestLength = getShortestLength(matrix); |
| 32 | + |
| 33 | + while (index < shortestLength) { |
| 34 | + sum += matrix[index][index]; |
| 35 | + index += 1; |
| 36 | + } |
| 37 | + |
| 38 | + return sum; |
| 39 | +} |
| 40 | + |
| 41 | +export function sumAntiDiagonal(matrix: number[][]): number { |
| 42 | + let sum = 0; |
| 43 | + let index = 0; |
| 44 | + |
| 45 | + const shortestLength = getShortestLength(matrix); |
| 46 | + |
| 47 | + while (index < shortestLength) { |
| 48 | + sum += matrix[index][matrix.length - 1 - index]; |
| 49 | + index += 1; |
| 50 | + } |
| 51 | + |
| 52 | + return sum; |
| 53 | +} |
| 54 | + |
| 55 | +export function sumFrame(matrix: number[][]): number { |
| 56 | + let sum = 0; |
| 57 | + |
| 58 | + const numberOfRows = matrix.length; |
| 59 | + const numberOfColumns = matrix[0].length; // assuming every row has the same size |
| 60 | + |
| 61 | + // scann horizontally: top + bottom |
| 62 | + for (let index = 0; index < numberOfColumns; index += 1) { |
| 63 | + sum += matrix[0][index] + matrix[numberOfRows - 1][index]; |
| 64 | + } |
| 65 | + |
| 66 | + // scan vertically: left + right |
| 67 | + for (let index = 1; index < numberOfRows - 1; index += 1) { |
| 68 | + sum += matrix[index][0] + matrix[index][numberOfColumns - 1]; |
| 69 | + } |
| 70 | + |
| 71 | + return sum; |
| 72 | +} |
0 commit comments