Home > Software design >  Turning a multidimensional array into a single array
Turning a multidimensional array into a single array

Time:10-06

I'm doing the following codesignal:

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
solution(matrix) = 9.

This is what I came up with, but it's not passing.

function solution(matrix) {
    let rooms = []
for (let i = 0; i < matrix.length; i  ) {
  if (matrix[i] !== 0 || matrix[i-4] !== 0) {
    rooms.push(i)      
  } 
}
    rooms.reduce((a, b) => a   b, 0)
    }

I think it's not passing because its three small arrays in one large one. So is there a way to easily combine the three small arrays into one large one, then I can loop over it and run the conditional?

CodePudding user response:

You don't need to convert to 1d array as it will be extra work, instead you solve it as follows:

you need to check whether the item above the one you are currently at is 0 or not. The item above any item in a 2d array is at index [i-1][j] where i is your current item. Make sure at i = 0 you directly add the item to the array to avoid getting index out of bounds exception.

This is my code:

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

let sum = 0;

for(i = 0; i < matrix.length; i  ) {
  for(j = 0; j < matrix[i].length; j  ) {
    if(i === 0) {
         sum  = matrix[i][j];
         continue;
    }
    if(i - 1 < 0) continue;
    if(matrix[i - 1][j] !== 0) sum  = matrix[i][j];
  }
}

console.log(sum)

CodePudding user response:

Loop over rows & columns, when 0 is found, sum 0 for that and further values in that column:

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

function solution (matrix) {
  let skip = {}, sum = 0;
  for (const a of matrix)
    for (let i = 0; i < a.length; i  )
      sum  = skip[i] || (skip[i] = !a[i]) ? 0 : a[i];
  return sum;
};

console.log(solution(matrix));

  • Related