Home > database >  2D Array loop behaving strangely (FCC)
2D Array loop behaving strangely (FCC)

Time:10-07

I'm doing a learning exercise and am trying to understand the following code. I thought I had a handle on arrays and loops, but this one has got me very confused.

The below code:

  function zeroArray(m, n) 
  {  
  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i  ) 
  {    
    for (let j = 0; j < n; j  ) 
    {      
      row.push(0);
    }    
    newArray.push(row);
  }
  return newArray;

 }

 let matrix = zeroArray(3, 2);
 console.log(matrix);

Returns

[ [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ] ]

However I would have expected it to return

[ [ 0, 0, ],
  [ 0, 0, 0, 0, ],
  [ 0, 0, 0, 0, 0, 0 ] ]

Given that in each i loop, we are pushing (0) to row[] twice, before pushing row[] into newArray.

This isn't happening though, and in my VSCode debugger it looks as though in each i loop, every existing index of newArray is being updated with the latest version of the row[] array.

Why is this?

CodePudding user response:

You need to make a copy of the array when pushing to newArray:

function zeroArray(m, n) {
  let newArray = [];
  let row = [];

  for (let i = 0; i < m; i  ) {
    for (let j = 0; j < n; j  ) {
      row.push(0);
    }
    newArray.push(row.slice());
  }
  return newArray;

}

let matrix = zeroArray(3, 2);
console.log(JSON.stringify(matrix));

CodePudding user response:

1) Start outer loop with i = 1 upto i <= m, so the loop count will be m

for (let i = 1; i <= m; i  ) {

2) You should create a new row every time the inner loop start and push row into newArray after the inner loop ends

3) Set inner loop condition as j < n * i

  for (let j = 0; j < n * i; j  ) {

function zeroArray(m, n) {
  let newArray = [];
  // const row = []   // (-)
  for (let i = 1; i <= m; i  ) {
    const row = []; // ( )
    for (let j = 0; j < n * i; j  ) { // ( )
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;
}

let matrix = zeroArray(3, 2);
console.log(matrix);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Matrix m x n should be m rows and n cols. So for 3, 2 you expect

[
  [0, 0],
  [0, 0],
  [0, 0],
]

Just declare row inside the first loop:

function zeroArray(m, n) {
  const newArray = [];

  for (let i = 0; i < m; i  ) {
    const row = [];
    for (let j = 0; j < n; j  ) {
      row.push(0);
    }
    newArray.push(row);
  }
  return newArray;

}

let matrix = zeroArray(3, 2);
console.log(matrix);

  • Related