Last active
October 14, 2016 04:09
-
-
Save nigelwtf/dbb1a1448f2fbcd1efd5 to your computer and use it in GitHub Desktop.
Javascript Spiral Matrix Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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