-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.js
More file actions
55 lines (50 loc) · 1.25 KB
/
Board.js
File metadata and controls
55 lines (50 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Board {
constructor(positions, nQueen) {
positions.sort();
this.nQueen = nQueen;
this.queenPositions = new Set(positions);
this.queenPositionArray = positions;
this.hash = this.hashCode();
}
// Print out the solution
show() {
let board = [];
let boardSize = this.nQueen * this.nQueen;
for (let i = 0; i < boardSize; i++) {
if (i % this.nQueen == 0) {
board.push("\n");
}
if (this.queenPositions.has(i)) {
board.push(" Q ");
} else {
board.push(" * ");
}
}
console.log(board.join(""));
}
// Get all of the possible neighbors
neighbors() {
let boardSize = this.nQueen * this.nQueen;
let neighbors = [];
let queenPositions = [];
for (let q = 0; q < this.queenPositions.size; q++) {
queenPositions.push(this.queenPositionArray[q]);
}
for (let i = 0; i < boardSize; i++) {
neighbors.push(new Board([i].concat(queenPositions), this.nQueen));
}
return neighbors;
}
// Hash the current board
hashCode() {
if (this.queenPositions.size === 0) {
return -1;
}
let hash = 0;
for (var pos of this.queenPositions) {
hash = hash * 31 + pos;
}
return hash;
}
}
module.exports = Board;