Spiral Matrix v-1
Write a function that accepts an integer N and returns a NxN spiral matrix.’
Example:
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]]
function matrix(n) {
const results = [];
for (let i = 0; i < n; i++) {
results.push([]);
}
let counter = 1;
let startColumn = 0;
let endColumn = n - 1;
let startRow = 0;
let endRow = n - 1;
while (startColumn <= endColumn && startRow <= endRow) {
// TOP row
for (let i = startColumn; i <= endColumn; i++) {
results[startRow][i] = counter;
counter++;
}
startRow++;
// Right Column
for (let i = startRow; i <= endRow; i++) {
results[i][endColumn] = counter;
counter++;
}
endColumn--;
// Bottom Row
for (let i = endColumn; i >= startColumn; i--) {
results[endRow][i] = counter;
counter++;
}
endRow--;
// start column
for (let i = endRow; i >= startRow; i--) {
results[i][startColumn] = counter;
counter++;
}
startColumn++;
}
return results;
}
We create a function called matrix with parameter called n and variable called results=[]
We start looping with for loop for all the numbers and if found it is used .push to push into the results array
We create 5 variable to keep track with our rows and columns
let counter = 1;
let startColumn = 0;
let endColumn = n - 1;
let startRow = 0;
let endRow = n - 1;
Then we use the while loop like this while (startColumn <= endColumn && startRow <= endRow)
First we check the TOP ROW and we create for loop where i = startColumn and is less than endColumn and also we increment by 1;
Inside the loop we check results of startRow and i and equal to counter then we increment counter by 1; after that we increment startRow by 1 with startRow++
results[startRow][i] = counter;
counter++;
}
startRow++;
Then we check the Righ Column and we create for loop where i = startRow i<= endRow and i++
results[i][endColumn] = counter;
counter++;
}
endColumn–;
Then we check the Bottom Row and we create for loop where i = endColumn i>= startRow and i–
results[endRow][i] = counter;
counter++;
}
endRow–;
Then we check the Start Column and we create for loop where i = endRow i>= startRow and i–
results[i][startColumn] = counter;
counter++;
}
startColumn++;
In the end we return the return results