Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Given a square matrix of at least 3x3, print its elements following a spiral path
function print(o){
var
m = o.length >> 1,
r = m,
c = m + 1;
p = function(){
console.log(o[r][c]);
},
left = function(i){
for(; c > i; p(--c));
},
right = function(i){
for(; c < i; p(++c));
},
up = function(i){
for(; r > i; p(--r));
},
down = function(i){
for(; r < i; p(++r));
};
for(var i = 0; ++i <= m; ){
left(m - i);
down(m + i);
right(m + i);
up(m - i);
}
left(0);
}
print([
[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment