# Fill out a spiral matrix

I got this question during my interview:

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: matrix filled out as a spiral [[1]]

/*PSEUDO:
rowMin = 0
rowMax = n - 1
colMin = 0
colMax = n - 1
counter = 1
matrix = []
create the matrix:
loop from 0 to n - 1
array
loop from 0 to n-1
push 0 into array
while rowMin <= rowMax and colMin <= colMax
loop on rowMin from colMin to colMax.  col
matrix[rowMin][col] becomes counter++
rowMin++
loop on colMax and from rowMin to rowMax.  row
matrix[row][colMax] becomes counter++
colMax--
loop on rowMax from colMax to colMin.  col
matrix[rowMax][col] becomes counter++
rowMax--
loop on colMin from rowMax to rowMin.  row
matrix[row][colMin] becomes counter++
colMin++
return matrix
*/

const spiralMatrix = (n) => {
const matrix = [];
let rowMin = 0,
rowMax = n - 1,
colMin = 0,
colMax = n - 1,
counter = 1;

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

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

return matrix;
}

console.log(spiralMatrix(10));

• it would be interesting to see this problem solved without random access. Left to right, top to bottom, in the same order you'd output to a terminal. – Oh My Goodness Mar 21 '19 at 8:54

Seems mostly solid to me. I just have two small remarks:

const spiralMatrix = (n) => {


I'm not a big fan of using the arrow syntax here. The arrow syntax is (mostly) used for inline functions. For a "top level" function I'd prefer a normal, more readable (and hoisted) function declaration:

function spiralMatrix(n) {


The only disadvantage I see is that const prevents accidental overwriting, which I don't see as an serious problem in this case.

And .fill(0) during initialization of the arrays is unnecessary.