Created
October 28, 2013 06:27
-
-
Save anonymous/7192203 to your computer and use it in GitHub Desktop.
A Javascript solution for https://github.com/blakeembrey/code-problems/tree/master/problems/spiral. Bug fixes and improvements from https://gist.github.com/anonymous/7166824
This file contains 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
//A Javascript solution for https://github.com/blakeembrey/code-problems/tree/master/problems/spiral. | |
//Bug fixes and improvements from https://gist.github.com/anonymous/7166824 | |
function f(m, n, x, y) { | |
var ans = [], arr; | |
var traverse = function(curX, curY) { | |
var stride = 1; | |
while(ans.length !== (m * n)) { | |
addColumnOrRow(true, curY, curX - 1, curX - stride); | |
addColumnOrRow(false, curX - stride, curY - 1, curY - stride); | |
addColumnOrRow(true, curY - stride, curX - stride + 1, curX + 1); | |
addColumnOrRow(false, curX + 1, curY - stride + 1, curY + 1); | |
stride += 2; | |
curX++; | |
curY++; | |
} | |
}; | |
var add = function(i, j) { | |
if(arr[i] && arr[i][j]) { ans.push(arr[i][j]); } | |
}; | |
var addColumnOrRow = function(isCol, colOrRow, start, end) { | |
var i, inc = 1, rev = false; | |
if(start > end) { | |
inc = -1; | |
rev = true; | |
} | |
for(i = start; (rev ? i >= end : i <= end); i += inc) { | |
if(isCol) { | |
add(i, colOrRow); | |
} else { | |
add(colOrRow, i); | |
} | |
} | |
}; | |
var createArray = function(m, n) { | |
var i = 0, j = 0, a = [], cnt = 1, tmp; | |
for(i = 0; i < m; i++) { | |
tmp = []; | |
for(j = 0; j < n; j++) { tmp.push(cnt++); }; | |
a.push(tmp); } | |
return a; | |
}; | |
arr = createArray(m, n); | |
x--; | |
y--; | |
add(x, y); | |
traverse(x, y); | |
return ans; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment