Exercise 12: Enter the Matrix Spiral

Directions

Write a function that accepts an integer N and returns a NxN spiral matrix.

Examples

matrix(2)
    [[1, 2],
    [4, 3]]
  matrix(3)
    [[1, 2, 3],
    [8, 9, 4],
    [7, 6, 5]]
 matrix(4)
    [[1, 2,  3, 4],
    [12, 13, 14, 5],
    [11, 16, 15, 6],
    [10,  9,  8, 7]]

Guidlines

Pseudo Code 03_16

Solution

In [1]:
function matrix(n) {
  let results = [];

  if (n > 1){
    for (let i=0; i<n; i++){
     results.push([]);
    }    
  }

  let counter = 1;
  let startCol = 0, endCol = n-1;
  let startRow = 0, endRow = n-1;

  while (startCol <= endCol && startRow <= endRow){
    // Top row
    for (let i = startCol; i <= endCol; i++){
      results[startRow][i] = counter;
      counter++;
    }
    startRow++;

    // Right column
    for (let i = startRow; i <= endRow; i++){
      results[i][endCol] = counter;
      counter++;
    }
    endCol--;

    // Bottom
    for (let i = endCol; i >= startCol; i--){
      results[endRow][i] = counter;
      counter++;
    }
    endRow--;

    // Left column
    for (let i = endRow; i >= startRow; i--){
      results[i][startCol] = counter;
      counter++;
    }
    startCol++;
  }

  return results;
}
In [2]:
matrix(2)
Out[2]:
[ [ 1, 2 ], [ 4, 3 ] ]
In [3]:
matrix(3)
Out[3]:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
In [4]:
matrix(4)
Out[4]:
[ [ 1, 2, 3, 4 ],
  [ 12, 13, 14, 5 ],
  [ 11, 16, 15, 6 ],
  [ 10, 9, 8, 7 ] ]