Debugging - Use Caution When Reinitializing Variables Inside a Loop

Hello,
I dont understand the base of the problem. it says the function creates m rows and n columns, meaning we should have m rows while it only has 1 row but m subarrays. does not make any sense to me.
please advise.
thanks

  **Your code so far**
function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
  // Adds the m-th row into newArray
  row=[]

  for (let j = 0; j < n; j++) {
    // Pushes n zeroes into the current row to create the columns
    row.push(0);
  }
  // Pushes the current row, which now has n zeroes in it, to the array
  newArray.push(row);
}
return newArray;
}

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

  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36

Challenge: Debugging - Use Caution When Reinitializing Variables Inside a Loop

Link to the challenge:

this code will give you this output:

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

each subarray here - it represents a row

number of elements in each subarray - its number of columns

If I will rewrite this output in more… I don’t know… more like I has been taught to write matrix in high school:

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

maybe it will help to deal with some confusion.

1 Like

it does not have 1 row

subarrays and rows are kinda the same thing here. Thus it has m rows

1 Like

Thank you it really helped. but still if we consider each subarray one item, then we have one column (n=1 not 2). Can you explain that too?

No, we have exactly n columns.
Lets modify function you posted:

function zeroArray(m, n) {
// Creates a 2-D array with m rows and n columns of zeroes
let newArray = [];
let row = [];
for (let i = 0; i < m; i++) {
  // Adds the m-th row into newArray
  row=[]

  for (let j = 0; j < n; j++) {
    // Pushes n zeroes into the current row to create the columns
    row.push(String(i) + ',' + String(j));
  }
  // Pushes the current row, which now has n zeroes in it, to the array
  newArray.push(row);
}
return newArray;
}

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

/* OUTPUT
[ [ '0,0', '0,1' ], 
  [ '1,0', '1,1' ], 
  [ '2,0', '2,1' ] ];
*/

I changed some stuff - actually just one line - where we pushing elements in subarrays
so now you can see that every element of every sub array represents one specific element of matrix,
and every element has two , you can say, coordinates -
first coordinate represents row,
second coordinate represents column

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.