Print out N by N Spiral Matrix in javascript I got this question during my practice interview.
Matrices - N Spiral Matrix
Prompt
Given an integer N, output an N x N spiral matrix with integers 1 through N.
Examples:
Input:  3

Output: [[1, 2, 3],
         [8, 9, 4],
         [7, 6, 5]]

Input: 1

Output: [[1]]

My solution is below:
function spiralMatrix(n) {
  const matrix = [];
  let counter = 1,
    rowMin = 0,
    rowMax = n - 1,
    colMin = 0,
    colMax = n - 1;

  for (let i = 0; i &lt; n; i++) {
    matrix.push(new Array(n).fill(0));
  }

  while (rowMin &lt;= rowMax &amp;&amp; colMin &lt;= colMax) {
    for (let col = colMin; col &lt;= colMax; col++) {
      matrix[rowMin][col] = counter++;
    }
    rowMin++;
    for (let row = rowMin; row &lt;= rowMax; row++) {
      matrix[row][colMax] = counter++;
    }
    colMax--;
    for (let col = colMax; col &gt;= colMin; col--) {
      matrix[rowMax][col] = counter++;
    }
    rowMax--;
    for (let row = rowMax; row &gt;= rowMin; row--) {
      matrix[row][colMin] = counter++;
    }
    colMin++;
  }

  return matrix;
}

console.log(spiralMatrix(10));
This code is well written;

Comments


You have no comments whatsoever, fortunately the code reads well


JSHint.com


Your code passes all checks, well done