Created
October 26, 2013 08:35
-
-
Save anonymous/7166824 to your computer and use it in GitHub Desktop.
A Javascript solution for https://github.com/blakeembrey/code-problems/tree/master/problems/spiral
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 | |
function f(m, n, x, y) { | |
var ans = [], endRecurse = false, arr; | |
var recurse = function(stride, curX, curY) { | |
var i, j; | |
if(endRecurse) { return; } | |
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); | |
recurse(stride + 2, curX + 1, curY + 1); | |
}; | |
var add = function(i, j) { | |
if((i == 0) && (j == (n-1))) { endRecurse = true; } | |
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); | |
recurse(1, x, y); | |
return ans; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment