0

I am working on a matrix spiral for coding interview practice. When the function matrix() is called with matrix(3) it will create a 3x3 matrix that spirals values 1 - 9 in a clockwise manner.

" 1 2 3 "
" 8 9 4 "
" 7 6 5 "

The actual array would be [[1,2,3],[8,9,4],[7,6,5]]

The problem is when I create my Array using the fill method then I get the result, [[8,9,5],[8,9,5],[8,9,5]]. But when I create the array with the commented out code that iterates and pushes then I get the correct answer.

Why does this happen? Is it because you can only use the fill method with static values?

Here is the code.

function matrix(n) {
  const results = Array(n);
  results.fill([], 0, n);
  //If I create the results array with this code then it works
  //   const results = [];
  //   for (let i = 0; i < n; i++) {
  //     results.push([]);
  //   }
  let counter = 1;
  let startColumn = 0;
  let startRow = 0;
  let endColumn = n - 1;
  let endRow = n - 1;

  while (startColumn <= endColumn && startRow <= endRow) {
    // For row positive
    for (let i = startColumn; i <= endColumn; i++) {
      results[startRow][i] = counter;
      counter++;
    }
    startRow++;
    //For column positive
    for (let i = startRow; i <= endRow; i++) {
      results[i][endColumn] = counter;
      counter++;
    }
    endColumn--;
    //For row negative
    for (let i = endColumn; i >= startColumn; i--) {
      results[endRow][i] = counter;
      counter++;
    }
    endRow--;
    //For column negative
    for (let i = endRow; i >= startRow; i--) {
      results[i][startColumn] = counter;
      counter++;
    }
    startColumn++;
  }
  return results;
}

document.querySelector("div").innerHTML = matrix(3);
<div></div>

.

Roskow
  • 320
  • 1
  • 7
  • 1
    When you `.fill` with a non-primitive, you've only created a single object in memory, so every array item is `===` to every other array item. If you want to create the array all at once, use `Array.from` instead – CertainPerformance Sep 30 '19 at 06:32
  • @CertainPerformance Perfect, exactly what I was looking for! Thanks! – Roskow Sep 30 '19 at 06:35

0 Answers0