-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheight-queens-puzzle.v1.js
332 lines (281 loc) · 7.51 KB
/
eight-queens-puzzle.v1.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
const QUEEN = '*';
const ATTACKED = '·';
const COLLISION = 'x';
const EMPTY = ' ';
// How to Document Classes
// https://stackoverflow.com/questions/27343152/jsdoc-how-to-document-prototype-methods
/**
* Square of a Board.
* @class
*/
const Square = (function () {
/**
* Initializes a new instance of Square.
* @constructs Square
*/
function Square() {
/**
* Piece that is being hold.
* @name Square#holdingPiece
* @type {object}
* @example
* // {
* // display: QUEEN
* // attacks: []
* // }
*/
this.holdingPiece = null;
/**
* List of attackers to this Square.
* @name Square#attackedBy
* @type {Array}
*/
this.attackedBy = Object.create(null);
}
/**
* Prints the square with its content.
* @example
* // [*] - Square holding a Queen
* // [x] - Attacked by multiple
* // [·] - Attacked Square
* // [ ] - Empty Square
* @function Square#toString
*/
Square.prototype.toString = function () {
function printSquare(val) {
return `[${val}]`;
}
const attackedCount = Object.keys(this.attackedBy).length;
if (this.holdingPiece && !attackedCount) {
return printSquare(this.holdingPiece.display);
} else if (this.holdingPiece && attackedCount) {
return printSquare(COLLISION);
} else if (!this.holdingPiece && attackedCount) {
return printSquare(ATTACKED);
} else {
return printSquare(EMPTY);
}
};
/**
* Tells if a Square is empty and NOT attacked.
* @function Square#isEmpty
*/
Square.prototype.isEmpty = function () {
return !this.holdingPiece && !Object.keys(this.attackedBy).length;
};
return Square;
})();
// ==================================================
/**
* ChessBoard.
* @class
*/
const Board = (function () {
/**
* Initializes a new instance of Board.
* @constructs Board
* @param {number} boardSize
*/
function Board(boardSize) {
/**
* Board Size.
* @name Board#boardSize
* @type {number}
*/
this.boardSize = boardSize;
/**
* ChessBoard.
* @name Board#board
* @type {Array}
*/
this._board = new Array(boardSize);
/**
* Number of Queens.
* @name Board#queens
* @type {number}
*/
this.queens = 0;
/**
* Initializes the board as an Array of Arrays of Squares
*/
function init() {
for (let i = 0; i < boardSize; i++) {
this._board[i] = new Array(boardSize);
for (let j = 0; j < boardSize; j++) {
this._board[i][j] = new Square();
}
}
}
init.call(this);
}
/**
* Prints the board.
* @example
* // board of size 3
* // [*][·][·]
* // [·][*][·]
* // [·][·][*]
* @function Board#toString
*/
Board.prototype.toString = function () {
return this._board.map(row => row.map(square => square.toString()).join('')).join('\n');
};
/**
* Returns the board as a string in a single row.
* @example
* // board of size 3
* // [*][·][·][·][*][·][·][·][*]
* @function Board#serialize
*/
Board.prototype.serialize = function () {
return this._board.map(row => row.map(square => square.toString()).join('')).join('');
};
/**
* Checks if a position is inside the boundaries of the board.
* @param {number} x Square's X position
* @param {number} y Square's Y position
* @function Board#isInLimit
*/
Board.prototype.isInLimit = function (x, y) {
if (y >= 0 && y < this.boardSize && x >= 0 && x < this.boardSize) {
return true;
}
return false;
};
/**
* Gets the list of attacked Squares from a given position.
* @function Board#getTargetSquares
* @param {Object} position Attacker's position in the board
* @param {number} position.x Attacker's X position
* @param {number} position.y Attacker's Y position
* @returns {Array} List of attacked Squares
*/
Board.prototype.getTargetSquares = function ({ y: attackerY, x: attackerX }) {
const squares = [];
let y, x;
// horizontal
for (x = 0; x < this.boardSize; x++) {
if (x !== attackerX) {
squares.push({ y: attackerY, x });
}
}
// vertical
for (y = 0; y < this.boardSize; y++) {
if (y !== attackerY) {
squares.push({ y, x: attackerX });
}
}
// diagonal top left
y = attackerY;
x = attackerX;
while (this.isInLimit(--y, --x)) {
squares.push({ y, x });
}
// diagonal top right
y = attackerY;
x = attackerX;
while (this.isInLimit(--y, ++x)) {
squares.push({ y, x });
}
// diagonal bottom left
y = attackerY;
x = attackerX;
while (this.isInLimit(++y, --x)) {
squares.push({ y, x });
}
// diagonal bottom right
y = attackerY;
x = attackerX;
while (this.isInLimit(++y, ++x)) {
squares.push({ y, x });
}
return squares;
};
/**
* Places a Queen piece in the board
* and updates the Squares that are attacked by it.
* @function Board#placeQueen
* @param {Object} position Queen's position in the board
* @param {number} position.x Queen's X position
* @param {number} position.y Queen's Y position
*/
Board.prototype.placeQueen = function ({ x, y }) {
const attacks = this.getTargetSquares({ x, y });
const queenPositionKey = `${y}${x}`;
this._board[y][x].holdingPiece = {
display: QUEEN,
attacks,
};
attacks.forEach(({ y, x }) => {
this._board[y][x].attackedBy[queenPositionKey] = true;
});
this.queens++;
};
/**
* Removes a Queen piece from the board
* and cleans the attack from the Squares that are attacked by it.
* @function Board#removeQueen
* @param {Object} position Queen's position in the board
* @param {number} position.x Queen's X position
* @param {number} position.y Queen's Y position
*/
Board.prototype.removeQueen = function ({ x, y }) {
if (!this._board[y][x].holdingPiece) {
return;
}
const queenPositionKey = `${y}${x}`;
const attacks = this._board[y][x].holdingPiece.attacks;
attacks.forEach(({ y, x }) => {
delete this._board[y][x].attackedBy[queenPositionKey];
});
this._board[y][x].holdingPiece = null;
this.queens--;
};
/**
* Returns a list of the unnattacked Squares in the board.
* @function Board#getUnattackedPositions
* @returns {Array} List of unnatacked Squares
*/
Board.prototype.getUnattackedPositions = function () {
const unattacked = [];
this._board.forEach((row, y) => {
row.forEach((square, x) => {
if (square.isEmpty()) {
unattacked.push({ y, x });
}
});
});
return unattacked;
};
/**
* Tells if the board has `n` queens.
* @function Board#hasNQueens
* @param {number} nQueens Number of total queens
*/
Board.prototype.hasNQueens = function (nQueens) {
return this.queens === nQueens;
};
/**
* Solves the nQueens Puzzle.
* @function Board#solve
* @param {number} nQueens Number of total queens.
*/
Board.prototype.solve = function (nQueens) {
if (this.hasNQueens(nQueens)) {
return this.serialize();
}
const unattacked = this.getUnattackedPositions();
for (let i = 0, len = unattacked.length; i < len; i++) {
const position = unattacked[i];
this.placeQueen(position);
const solution = this.solve(nQueens);
if (solution) {
return solution;
}
this.removeQueen(position);
}
return false;
};
return Board;
})();
module.exports = Board;