Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Created October 27, 2017 12:00
Show Gist options
  • Save jonasraoni/18fd34ae1e87957603777bc85ed39b90 to your computer and use it in GitHub Desktop.
Save jonasraoni/18fd34ae1e87957603777bc85ed39b90 to your computer and use it in GitHub Desktop.
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