All files / algorithms matrices.ts

97.61% Statements 41/42
66.66% Branches 6/9
100% Functions 6/6
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 62 63 64 65 66 67 68 69 70 71 72 7341x         1x 1x   1x 4x 16x       1x     1x 2x 2x   2x   2x     1x 1x 1x   1x   1x 4x 4x     1x     1x 1x 1x   1x   1x 4x 4x     1x     2x 1x   1x 1x     1x 4x       1x 2x     1x    
/**
 * The assumptions is that the matrices are N x M (either square or rectangular)
 * The matrices cannot have rows with different sizes.
 */
 
export function sum(matrix: number[][]): number {
  let sum = 0;
 
  for (let i = 0; i < matrix.length; i += 1) {
    for (let j = 0; j < matrix[i].length; j += 1) {
      sum += matrix[i][j];
    }
  }
 
  return sum;
}
 
function getShortestLength(matrix: number[][]): number {
  const rows = matrix.length;
  const columns = matrix[0].length;
 
  Iif (rows < columns) return rows;
 
  return columns;
}
 
export function sumDiagonal(matrix: number[][]): number {
  let sum = 0;
  let index = 0;
 
  const shortestLength = getShortestLength(matrix);
 
  while (index < shortestLength) {
    sum += matrix[index][index];
    index += 1;
  }
 
  return sum;
}
 
export function sumAntiDiagonal(matrix: number[][]): number {
  let sum = 0;
  let index = 0;
 
  const shortestLength = getShortestLength(matrix);
 
  while (index < shortestLength) {
    sum += matrix[index][matrix.length - 1 - index];
    index += 1;
  }
 
  return sum;
}
 
export function sumFrame(matrix: number[][]): number {
  let sum = 0;
 
  const numberOfRows = matrix.length;
  const numberOfColumns = matrix[0].length; // assuming every row has the same size
 
  // scann horizontally: top + bottom
  for (let index = 0; index < numberOfColumns; index += 1) {
    sum += matrix[0][index] + matrix[numberOfRows - 1][index];
  }
 
  // scan vertically: left + right
  for (let index = 1; index < numberOfRows - 1; index += 1) {
    sum += matrix[index][0] + matrix[index][numberOfColumns - 1];
  }
 
  return sum;
}