Skip to content

Instantly share code, notes, and snippets.

@eldyvoon
Created January 5, 2018 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eldyvoon/812507e12f2f0482325f4f5712e8cc33 to your computer and use it in GitHub Desktop.
Save eldyvoon/812507e12f2f0482325f4f5712e8cc33 to your computer and use it in GitHub Desktop.
Matrix Spiral in JavaScript
//specs
matrix(2)
[[1,2],
[4,3]]
matrix(4)
[[1,2,3,4],
[12,13,14,5],
[11,16,15,6],
[10,9,8,7]]
function matrix(n) {
const result = [];
for (let i = 0; i < n; i++) {
result.push([]);
}
let counter = 1;
let startColumn = 0;
let endColumn = n - 1;
let startRow = 0;
let endRow = n - 1;
while (startColumn <= endColumn && startRow <= endRow) {
for (let i = startColumn; i <= endColumn; i++) {
result[startRow][i] = counter;
counter++;
}
startRow++;
for (let i = startRow; i <= endRow; i++) {
result[i][endColumn] = counter;
counter++;
}
endColumn--;
for (let i = endColumn; i >= startColumn; i--) {
result[endRow][i] = counter;
counter++;
}
endRow--;
for (let i = endRow; i >= startRow; i--) {
result[i][startColumn] = counter;
counter++;
}
startColumn++;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment