Created
February 5, 2016 16:02
-
-
Save vicneanschi/5a68fec29cbb8e4990b5 to your computer and use it in GitHub Desktop.
This file contains 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
"use strict"; | |
function Graph(){ | |
this.vertices = {}; | |
//graph.addVertex('vFrom', {'vTo1': 1, 'vTo2': 1}); | |
this.addVertex = function(name, edges) { | |
this.vertices[name] = edges; | |
} | |
} | |
/** | |
* [0,0] coordinates represents A1 square | |
*/ | |
function Chessboard() { | |
var cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; | |
var rows = [1, 2, 3, 4, 5, 6, 7, 8]; | |
// x[+,-][1], y[+,-][2] | |
// x[+,-][2], y[+,-][1] | |
this.knightMoves = function (x, y) { | |
var result = []; | |
function addIfValid(x1, y1) { | |
if (x1 < 0 || x1 > cols.length -1 || y1 < 0 || y1 > rows.length -1) return; | |
result.push(cols[x1] + rows[y1]); | |
} | |
addIfValid(x+1, y+2); | |
addIfValid(x+1, y-2); | |
addIfValid(x-1, y+2); | |
addIfValid(x-1, y-2); | |
addIfValid(x+2, y+1); | |
addIfValid(x+2, y-1); | |
addIfValid(x-2, y+1); | |
addIfValid(x-2, y-1); | |
return result; | |
} | |
this.squareName = function (x, y) { | |
return cols[x] + rows[y]; | |
} | |
this.forEach = function(func){ | |
for(var x=0; x < cols.length; x++) { | |
for(var y=0; y<rows.length; y++) { | |
func(x, y); | |
} | |
} | |
} | |
} | |
(function findSolution(){ | |
var chessboard = new Chessboard(); | |
var x=0, y=0; | |
var moves = chessboard.knightMoves(x, y); | |
console.log('Possible moves from %s: %s', chessboard.squareName(x, y), moves); | |
var x=2, y=2; | |
var moves = chessboard.knightMoves(x, y); | |
console.log('Possible moves from %s: %s', chessboard.squareName(x, y), moves); | |
var graph = new Graph(); | |
//graph.addVertex('a1', {'b3': 1, 'c2': 1}); | |
chessboard.forEach(function(x,y){ | |
var moves = chessboard.knightMoves(x, y); | |
console.log(chessboard.squareName(x, y), moves); | |
//graph.addVertex(cols[x] + rows[y], moves); | |
}); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment