Last active
September 6, 2015 02:14
-
-
Save arcesino/952198d98ad3bdd1d960 to your computer and use it in GitHub Desktop.
Write a function that prints the matrix to the standard output (stdout) on a single line starting in the upper-left corner and continuing clockwise, in circles, from exterior towards interior.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var snakePrint = function(numbers, width) { | |
var xyTo1D = function(x, y) { | |
return y * width + x; | |
}; | |
var matrix = numbers.split(','), | |
directions = [[1, 0], [0, 1], [-1, 0], [0, -1]], | |
output = '', | |
snake = { | |
length: 0, | |
x: 0, | |
y: 0, | |
direction: 0, | |
walk: function() { | |
var index = xyTo1D(this.x, this.y); | |
output += matrix[index] + ' '; | |
matrix[index] = undefined; | |
this.length++; | |
this.x += directions[this.direction][0]; | |
this.y += directions[this.direction][1]; | |
}, | |
turnRight: function () { | |
this.direction = (this.direction + 1) % 4; | |
}, | |
isBlocked: function () { | |
var x1 = this.x + directions[this.direction][0]; | |
var y1 = this.y + directions[this.direction][1]; | |
return x1 == width || y1 == width || matrix[xyTo1D(x1, y1)] === undefined; | |
} | |
}; | |
while (snake.length < width * width) { | |
if (snake.isBlocked()) { | |
snake.turnRight(); | |
} | |
snake.walk(); | |
} | |
console.log(output); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment