Snail
October 2013
A snail matrix generator in 133 bytes
s=function(e,c,d,b,f,h,g){c=[[]];d=1;b=h=0;for(f=-1;e;e--){for(g=1;g<2*e;g++)g>e?b+=d:f+=d,c[b]||(c[b]=[]),c[b][f]=++h;d=-d}return c}
Demo:
Size:
A snail matrix generator in 133 bytes
s=function(e,c,d,b,f,h,g){c=[[]];d=1;b=h=0;for(f=-1;e;e--){for(g=1;g<2*e;g++)g>e?b+=d:f+=d,c[b]||(c[b]=[]),c[b][f]=++h;d=-d}return c}
/**
* Snail
* @param n: the size of the matrix (n*n)
* @return: a 2D array with integers
*/
s = function(n,a,d,x,y,c,i){
// a is the result matrix
a = [[]];
// d is the direction: right, bottom = 1; left, top = -1
d = 1;
// c is the counter value.
c = 0;
// x and y are the coordinates of the number in the matrix
x = 0;
y = -1;
// Loop while n decrements
for(; n; n--){
// The two following loops are merged in the minified code:
// fill n columns
for(i = 0; i < n; i++){
y += d;
a[x][y] = ++c;
}
// fill n-1 lines
for(i = 0; i < n - 1; i++){
x += d;
if(!a[x]){
a[x] = [];
}
a[x][y] = ++c;
}
// change direction
d = -d;
}
return a;
}