Skip to content

Instantly share code, notes, and snippets.

@nigelwtf
Last active October 14, 2016 04:09
Show Gist options
  • Select an option

  • Save nigelwtf/dbb1a1448f2fbcd1efd5 to your computer and use it in GitHub Desktop.

Select an option

Save nigelwtf/dbb1a1448f2fbcd1efd5 to your computer and use it in GitHub Desktop.
Javascript Spiral Matrix Problem
function spiralMatrix(n) {
var total = n * n,
sides = n,
x = 0,
y = 0,
dx = 1,
dy = 0,
matrix = [],
i = 0,
j = 0;
while(sides--) {
matrix[sides] = [];
}
sides = n;
while(i < total) {
matrix[y][x] = i++;
if (++j === sides) {
var dyVal = dy;
j = 0;
if(dx == 0) {
dyVal = -dy;
dx = -dx;
}
dy = dx;
dx = dyVal;
if (dx == 0) {
sides--;
}
}
x += dx;
y += dy;
}
return matrix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment