Skip to content

Instantly share code, notes, and snippets.

@aSapien
Last active August 31, 2016 06:44
Show Gist options
  • Save aSapien/49a28806a4fed094ccf42cf3c8c83973 to your computer and use it in GitHub Desktop.
Save aSapien/49a28806a4fed094ccf42cf3c8c83973 to your computer and use it in GitHub Desktop.
Print a square matrix (2x2, 4x4, 16x16, etc) in a clockwise spiral from outside in
var mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
var DIRECTIONS = {
FORWARD: 1,
BACKWARD: -1
};
var AXIS = {
X: 'X',
Y: 'Y'
};
function spiralMat(mat) {
// init
var position = {
X: -1, //before first step
Y: 0
};
var matLength = mat.length;
var stepsCount = matLength;
var direction = DIRECTIONS.FORWARD;
var axis = AXIS.X;
function takeStep() {
position[axis] = position[axis] + direction;
}
function printLine() {
var currentSteps = stepsCount;
while (currentSteps) {
takeStep();
console.log(mat[position.Y][position.X]);
currentSteps--;
}
}
function rotate() {
if (direction === DIRECTIONS.FORWARD) {
if (axis === AXIS.X) {
axis = AXIS.Y;
stepsCount--;
return;
}
if (axis === AXIS.Y) {
axis = AXIS.X;
direction = DIRECTIONS.BACKWARD;
return;
}
}
if (direction === DIRECTIONS.BACKWARD) {
if (axis === AXIS.X) {
axis = AXIS.Y;
stepsCount--;
return;
}
if (axis === AXIS.Y) {
axis = AXIS.X;
direction = DIRECTIONS.FORWARD;
}
}
}
while(stepsCount) {
printLine();
rotate();
}
}
spiralMat(mat); //result: 1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment