Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 16, 2022 06:45 pm GMT

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.

Image description

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.

Image description

Meanwhile, If some expert came across this article. Please do minify the above 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

For further updates:

Follow @urstrulyvishwak


Original Link: https://dev.to/urstrulyvishwak/spiral-matrix-in-javascript-2hii

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To