I was playing with javascript trying to create a classic spiral matrix like this one:
01 02 03 04
12 13 14 05
11 16 15 06
10 09 08 07
But when I debugged my code, I noticed something weird:
The matrix array is filling the space
[1][x]
when j
is 0
How is that possible?
What is the explanation for this behavior?
Here is the piece of code:
var draw = function(direction, dim) {
var directions = ['right', 'down', 'left', 'up'];
var __matrix = Array(dim[0]).fill(Array(dim[1]).fill(0));
var fill = {};
fill.right = function(nextIndex, matrix, j, i, value) {
if(value === (dim[0] * dim[1])) { return matrix; }
if(matrix[j][i] === 0) { matrix[j][i++] = value++; }
else { i--; nextIndex++; }
debugger;
return fill[directions[nextIndex]].apply({}, arguments);
}
fill.down = function() { }; //todo
fill.left = function() { }; //todo
fill.up = function() { }; //todo
return fill[direction](directions.indexOf(direction), __matrix, 0, 0, 1);
};
console.log(draw('right', [4,4]));