Repository navigation
Expand file tree
/
Copy pathpractice.js
More file actions
139 lines (126 loc) · 3.05 KB
/
Copy pathpractice.js
File metadata and controls
139 lines (126 loc) · 3.05 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
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
//'normal array'
//const tilesOutOfPlace = require('./tilesOutOfPlace');
const tilesOutOfPlace = (n) => {
const arr = [[1, 2, 3], [4, 5, 6], [7, 8, 0]];
let count = 0;
for (let i = 0; i < 3; ++i){
for (let j = 0; j < 3; ++j){
if (n[i][j] !== arr[i][j] && arr[i][j] !== 0) {
count++;
}
}
}
return count;
}
class Coordinate {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
class State {
constructor(n) {
this.board = n;
this.star = tilesOutOfPlace(this.board)
}
}
const swapTile = (n, x, y) => {
let hole = findHole(n)
let holex = hole.x
let holey = hole.y
let next = [...n];
next[holex][holey] = next[x][y]
next[x][y] = 0
//printer(next)
return next;
}
let findHole = (n) => {
let x, y;
for (let i = 0; i < 3; ++i){
for (let j = 0; j < 3; ++j){
if (n[i][j] === 0) {
x = i;
y = j;
break;
}
}
}
return {x,y}
}
const children = (n, d) => {
let hole = findHole(n)
let x = hole.x
let y = hole.y
let up = new Coordinate(x, y-1)
let down = new Coordinate(x, y+1)
let left = new Coordinate(x - 1, y)
let right = new Coordinate(x + 1, y)
let swap = []
let options = [up, down, left, right]
for (let opt of options) {
if (opt.x >= 0) {
if (opt.x <= 2) {
if (opt.y >= 0) {
if (opt.y <= 2) {
swap.push(opt);
}
}
}
}
}
let actual = []
for (let iter of swap) {
const newArray = n.map(a => ({...a}));
let cur = swapTile(newArray, iter.x, iter.y)
actual.push(new State(cur))
}
return actual
}
const printer = (n) => {
console.log(n[0][0] + " | " + n[0][1] + " | " + n[0][2])
console.log("--+---+--")
console.log(n[1][0] + " | " + n[1][1] + " | " + n[1][2])
console.log("--+---+--")
console.log(n[2][0] + " | " + n[2][1] + " | " + n[2][2])
console.log()
console.log()
}
const sample = [[1, 8, 2], [0, 4, 3], [7, 6, 5]]
const goal = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
const visited = []
const valid = (n) => {
for (let v of visited) {
if (n === v) {
return false;
}
}
return true;
}
const runner = () => {
let queue = []
queue.push(new State(sample))
while (queue.length > 0) {
queue = queue.sort((a, b) => {
return b.star - a.star
})
let next = queue.pop();
let board = next.board;
printer(board);
console.log(next.star)
if (next.star === 0) {
console.log("END")
break;
}
if (valid(board)) {
for (let chil of children(board)) {
if (valid(chil.board)) {
queue.push(chil)
}
}
}
visited.push(board)
}
console.log("printed")
}
runner();
console.log('after');