## DEV Community # Spiral Matrix in Javascript

This is one interesting interview question.

Generally, we know the matrix of any size but what is special about Spiral here.

2 * 2 Matrix can be:

[[1,2],
[3,4]]

So, it spiral version is:

[[1,2],
[4,3]]

3 * 3 Matrix can be:
[[1,2,3],
[4,5,6],
[7,8,9]]

So, it's spiral version is:
[[1,2,3],
[8,9,4],
[7,6,5]]

An image can explain better rather much long theories. I tried it using below image. Ok. Now, I implemented this using javascript.

Here, is the code:

``````function spiralMatrix(n) {
const arr = Array.from({ length: n }, () => []);
let row = 0;
let col = 0;
let rowEnd = n - 1;
let colEnd = n - 1;
let counter = 1;
while (col <= colEnd && row <= rowEnd) {

// Top row & middle value (Where col === colEnd && row === rowEnd)
for (let i = col; i <= colEnd; i++) {
arr[row][i] = counter;
counter++;
}
row++;

// end column
for (let i = row; i <= rowEnd; i++) {
arr[i][colEnd] = counter;
counter++;
}
colEnd--;

// end row
for (let i = colEnd; i >= col; i--) {
arr[rowEnd][i] = counter;
counter++;
}
rowEnd--;

// First col from end
for (let i = rowEnd; i >= row; i--) {
arr[i][col] = counter;
counter++;
}
col++;
}
return arr;
}
``````

I would love to explain how I achieved it.

Here is the GIF that makes you get the Pseudo code behind this code. Thanks.

# 💎 Love to see your response

1. Like - You reached here means. I think, I deserve a like.
2. Comment - We can learn together.
3. Share - Makes others also find this resource useful.
4. Subscribe / Follow - to stay up to date with my daily articles.
5. Encourage me - You can buy me a Coffee

## Let's discuss further.

1. Just DM @urstrulyvishwak
2. Or mention
@urstrulyvishwak ``````//           y
//           |
//    16 15 14 13 12
//    17  4  3  2 11
// -- 18  5  0  1 10 --- x
//    19  6  7  8  9
//    20 21 22 23 24
//           |
//
// Given coordinates (x,y) return "spiral index". Source:
// https://stackoverflow.com/questions/9970134/get-spiral-index-from-location/9971465#9971465
//
function spiralIndex(x, y) {
const y2 = y * y;
const x2 = x * x;
if (y2 >= x2) {
const value = 4 * y2 - y - x;
return y >= x ? value : value - 2 * (y - x);
}
const value = 4 * x2 - y - x;
return y >= x ? value : value + 2 * (y - x);
}

function makeToValue(n) {
const n2 = n * n;
if (n % 2 === 0) {
const baseY = n / 2;
const baseX = baseY - 1;
return (row, column) => n2 - spiralIndex(column - baseX, baseY - row);
}

const base = (n - 1) / 2;
return (row, column) => n2 - spiralIndex(base - column, row - base);
}

function spiralMatrix(n) {
const toValue = makeToValue(n);
const config = { length: n };
return Array.from(config, (_vr, row) =>
Array.from(config, (_vc, column) => toValue(row, column))
);
}

console.log(spiralMatrix(3)); // [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
console.log(spiralMatrix(4)); // [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
``````

This seems to work as well

``````function spiralMatrix(n) {
if (n < 1) return [];

const matrix = Array.from({ length: n }, (_v, _i) => []);
let row = 0, column = 0, value = 1;
for (let low = 0, high = n - 1; low <= high; high -= 1) {
for (; column < high; matrix[row][column] = value, column += 1, value += 1);
for (; row < high; matrix[row][column] = value, row += 1, value += 1);
for (; column > low; matrix[row][column] = value, column -= 1, value += 1);
for (low += 1; row > low; matrix[row][column] = value, row -= 1, value += 1);
}
matrix[row][column] = value;
return matrix;
}

console.log(spiralMatrix(3)); // [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
console.log(spiralMatrix(4)); // [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]}
``````

Though the arrays are going to be the holey rather than the packed kind.

DEV Community

## Visualizing Promises and Async/Await 🤓 ☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓