Home > Software engineering >  Where is "0" coming from in my unzip() return? How do we create the inner loop where the i
Where is "0" coming from in my unzip() return? How do we create the inner loop where the i

Time:10-27

Coding Challenge:

Write a function, unzip, which accepts a matrix of nRows rows and nCol columns. It should return a new array, of numCol rows and numRows columns, which regroups elements.

unzip([
  [1, 2],
  [3, 4],
]);
// [[1,3],[2,4]]

unzip([
  [1, 2, 3],
  [4, 5, 6],
]);
// [[1,4],[2,5],[3,6]]

unzip([["a"], ["b"], ["c"]]);
// [['a','b','c']]

I'm not sure how to implement the inner forloop logic.

My thought process:

results[0][0] = arr[0][0] // outer
results[0][1] = arr[1][0] // inner (flipped)
results[1][0] = arr[0][1] // inner (flipped)
results[1][1] = arr[1][1] // outer

Attempt:

Prepopulate the results array with 0s and then insert the correct values

unzip([[1, 2], [3, 4]]);

function unzip(arr) {
  const results = [];
  const row = arr[0].length;
  const col = arr.length;

  for (let i = 0; i < row; i  ) {
    results.push([0, 0]);
  }

  for (let i = 0; i < results.length; i  ) {
    results[i][i] = arr[i][i];
    for (let j = results.length - 1; j > i; j--) {
      results[i][j] = arr[j][i];
    }
  }


  return results;
} // [ [1, 3], [0, 4]], correct: [[1, 3], [2, 4]]

Where in the world is this "0" coming from in my return? There is no 0 in the original array

CodePudding user response:

In addition to what Mike said in comment (square matrix), your code starts from a result full of 0s. And then does as if result was filled with the initial value, and swapping them.

I mean, your double loop excludes cases where j<i. And yet, it only affects result[i][j]. So, how result[i][j] are supposed to get non-0 values when j<i?

Keeping your logic, as much as possible

function unzip(arr) {
  const results = [];
  const row = arr[0].length;
  const col = arr.length;

  for (let i = 0; i < row; i  ) {
    results.push(new Array(col).fill(0));
  }

  for (let i = 0; i < row; i  ) {
    for (let j = col - 1; j >= 0; j--) {
      results[i][j] = arr[j][i];
    }
  }


  return results;
} 

Note that I also removed the specific treatment for result[i][i], which has no reason to be. It is just one value among others. And which fails if matrix is not square. And used your variable row and col, to avoid also assuming in the loop that it is square.

A shorter version (without using your logic)

function unzip(arr){
    result=[];
    for(let i=0; i<arr[0].length; i  ){
        result.push(arr.map((l)=>l[i]));
    }
    return result;
}

Each line of result is the ith column of arr, which you can get by getting l[i] with l being all lines of arr. Which is what arr.map((l)=>l[i]) does.

  • Related