Skip to content

Instantly share code, notes, and snippets.

Created October 28, 2013 06:27
Show Gist options
  • Save anonymous/7192203 to your computer and use it in GitHub Desktop.
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
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