Skip to content

Instantly share code, notes, and snippets.

@arrbxr
Created September 12, 2018 21:21
Show Gist options
  • Save arrbxr/5cced401e6b08c4d6dd8e875c63226e0 to your computer and use it in GitHub Desktop.
Save arrbxr/5cced401e6b08c4d6dd8e875c63226e0 to your computer and use it in GitHub Desktop.
matrix spiral problem created by arrbxr - https://repl.it/@arrbxr/matrix-spiral-problem
function matrix(n) {
let result = [];
for(let i = 0; i < n; i++) {
result.push([]);
}
let counter = 1;
let startColun = 0;
let endColumn = n - 1;
let startRow = 0;
let endRow = n - 1;
while(startColun <= endColumn && startRow <= endRow) {
// Top row
for(let i = startColun; i <= endColumn; i++) {
result[startRow][i] = counter;
counter++;
}
startRow++;
// Right column
for(let i = startRow; i <= endRow; i++) {
result[i][endColumn] = counter;
counter++;
}
endColumn--;
// Bottom row
for(let i = endColumn; i >= startColun; i--) {
result[endRow][i] = counter;
counter++;
}
endRow--;
// start column
for(let i = endRow; i >= startRow; i--) {
result[i][startColun] = counter;
counter++;
}
startColun++;
}
return result;
}
matrix(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment