Skip to content

Matrix Elements Sum

After becoming famous, the CodeBots decided to move into a new building together. Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted! Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms.

Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0).

Example

  • For

    matrix = [
        [0, 1, 1, 2],
        [0, 5, 0, 0],
        [2, 0, 3, 3]
    ]

    the output should be

    matrix_elements_sum(matrix) = 9.
    Image Credit: CodeSignal
  • For

      matrix = [
        [1, 1, 1, 0],
        [0, 5, 0, 1],
        [2, 1, 3, 10]
      ]

    the output should be

    `solution(matrix) = 9`.
    Image Credit: CodeSignal

    Note that the free room in the final column makes the full column unsuitable for bots (not just the room directly beneath it). Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9.

Solution

py
def matrix_elements_sum(matrix):
    rent = 0
    for section in range(len(matrix[0])):
        for room in range(len(matrix)):
            if matrix[room][section] == 0:
                # ghost found, exit the entire section below
                break
            rent += matrix[room][section]
    return rent


print(matrix_elements_sum([
    [0, 1, 1, 2],
    [0, 5, 0, 0],
    [2, 0, 3, 3]
]))
js
function matrixElementsSum(matrix) {
  let rent = 0;
  for (let section = 0; section < matrix[0].length; section++) {
    for (let room = 0; room < matrix.length; room++) {
      if (matrix[room][section] === 0) {
        break;
      }
      rent += matrix[room][section];
    }
  }
  return rent;
}

console.log(
  matrixElementsSum([
    [0, 1, 1, 2],
    [0, 5, 0, 0],
    [2, 0, 3, 3],
  ])
);

my thoughts are neither my employer's nor my wife's