-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoard.js
More file actions
111 lines (103 loc) · 2.34 KB
/
Board.js
File metadata and controls
111 lines (103 loc) · 2.34 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
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
class Board {
constructor(moveLedTo, slidePos, positions) {
this.slidePos = slidePos;
this.moveLedTo = moveLedTo;
this.positions = positions;
this.hash = this.hashCode();
this.manhattan = this.manhattanCost();
this.moveCount = 0;
}
getTotalCost() {
return this.manhattan + this.moveCount;
}
manhattanCost() {
let cost = 0;
for (let i = 0; i < 9; i++) {
cost +=
Math.abs(this.getCol(this.positions[i]) - this.getCol(i)) +
Math.abs(this.getRow(this.positions[i]) - this.getRow(i));
}
return cost;
}
// Print out the solution
show() {
let board = [];
for (let i = 0; i < 9; i++) {
if (i % 3 == 0 && i !== 0) {
board.push("\n");
}
board.push(` ${this.positions[i]} `);
}
console.log(board.join(""));
console.log();
}
//Get the row of the current number
getRow(pos) {
return Math.trunc(pos / 3);
}
//Get the col of the current number
getCol(pos) {
return pos % 3;
}
//Get new board based on current move and newPosition
getNewBoard(move, newPos) {
let newBoard = this.positions.slice(0);
let temp = newBoard[newPos];
newBoard[newPos] = 0;
newBoard[this.slidePos] = temp;
return new Board(move, newPos, newBoard);
}
// Get new state based on the current move
/*
1 : Up
2: Down
3: Left
4: Right
*/
getState(move) {
if (move === 1) {
return this.getNewBoard(1, this.slidePos - 3);
}
if (move === 2) {
return this.getNewBoard(2, this.slidePos + 3);
}
if (move === 3) {
return this.getNewBoard(3, this.slidePos - 1);
}
return this.getNewBoard(4, this.slidePos + 1);
}
// Get all of the possible nextMoves
/*
1 : Up
2: Down
3: Left
4: Right
*/
nextMoves() {
let nextMoves = [];
let row = this.getRow(this.slidePos);
let col = this.getCol(this.slidePos);
if (row !== 0) {
nextMoves.push(this.getState(1));
}
if (row !== 2) {
nextMoves.push(this.getState(2));
}
if (col !== 0) {
nextMoves.push(this.getState(3));
}
if (col !== 2) {
nextMoves.push(this.getState(4));
}
return nextMoves;
}
// Hash the current board
hashCode() {
let hash = 0;
for (var pos of this.positions) {
hash = hash * 31 + pos;
}
return hash;
}
}
module.exports = Board;