-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm.js
387 lines (363 loc) · 12.2 KB
/
algorithm.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { rows, cols } from "./index.js";
class Algorithm {
createPath(parentForCell, startKey, targetKey) {
// Creating path array which stores path from source to destinatiom
const path = [];
let current = targetKey;
while (current !== startKey) {
let [cRow, cCol] = current.split("|");
let currBox = document.querySelector(`[row="${cRow}"][col="${cCol}"]`);
path.push(currBox);
current = parentForCell[current].key;
}
let [sRow, sCol] = current.split("|");
let sBox = document.querySelector(`[row="${sRow}"][col="${sCol}"]`);
path.push(sBox);
path.forEach(async (box, i) => {
box.classList.replace("pathSecondary", "pathPrimary");
let pathLength = path.length;
if (i > 0 && i < pathLength - 1) box.innerHTML = pathLength - i - 1;
});
}
waitForSeconds = (secs) => {
return new Promise((resolve) => {
setTimeout(resolve, secs * 1000);
});
};
// checks for validness of given row and col
check(row, col) {
if (col == -1 || row == -1) return false;
if (row < rows && col < cols) {
// checking if there is wall at row, col position
let wall = parseInt(
document
.querySelector(`[row="${row}"][col="${col}"]`)
.getAttribute("wall")
);
if (!wall) return true;
}
return false;
}
checkWithVisited(row, col, visited) {
if (col == -1 || row == -1) return false;
if (row < rows && col < cols) {
// checking if there is wall at row, col position and if it's already visited
let wall = parseInt(
document
.querySelector(`[row="${row}"][col="${col}"]`)
.getAttribute("wall")
);
if (!wall && !visited[row][col]) return true;
}
return false;
}
}
class depthFirstSearch extends Algorithm {
depthFirstSearchAlgo = async () => {
let startBox = document.getElementById("startBox");
let endBox = document.getElementById("endBox");
let startRow = parseInt(startBox.getAttribute("row"));
let startCol = parseInt(startBox.getAttribute("col"));
let endRow = parseInt(endBox.getAttribute("row"));
let endCol = parseInt(endBox.getAttribute("col"));
var visited = new Array(parseInt(rows)).fill(false);
for (var j = 0; j < rows; j++) {
visited[j] = new Array(parseInt(cols)).fill(false);
}
const stack = [];
const parentForCell = {};
const startKey = `${startRow}|${startCol}`;
const targetKey = `${endRow}|${endCol}`;
// No parent for startKey
parentForCell[startKey] = { key: undefined };
stack.push({
row: startRow,
col: startCol,
});
const speedSlider = document.querySelector("#speed");
let timeMultiplier = speedSlider.value;
speedSlider.addEventListener("change", () => {
timeMultiplier = speedSlider.value;
});
while (stack.length !== 0) {
const { row, col } = stack.pop();
const currentKey = `${row}|${col}`;
// All adjacent vertices of current vertex
const neighbours = [
{ row: row, col: col - 1 },
{ row: row + 1, col: col },
{ row: row - 1, col: col },
{ row: row, col: col + 1 },
];
// On finding destination exit from loop
if (currentKey === targetKey) {
break;
}
// Make current vetex as visited
visited[row][col] = true;
let nBox = document.querySelector(`[row="${row}"][col="${col}"]`);
// managing visualization speed
await this.waitForSeconds(0.2 / timeMultiplier);
if (nBox && nBox !== startBox) nBox.classList += " pathSecondary";
for (let i = 0; i < neighbours.length; i++) {
let nRow = neighbours[i].row;
let nCol = neighbours[i].col;
let key = `${nRow}|${nCol}`;
if (!this.checkWithVisited(nRow, nCol, visited)) continue;
// if key is not present then add it
if (!(key in parentForCell)) {
parentForCell[key] = {
key: currentKey,
};
}
stack.push(neighbours[i]);
}
}
if (!(targetKey in parentForCell)) {
alert("No path Found");
return;
}
// Creating path array which stores path from source to destinatiom
this.createPath(parentForCell, startKey, targetKey);
};
}
class breadthFirstSearch extends Algorithm {
breadthFirstSearchAlgo = async () => {
const queue = [];
const parentForCell = {};
const startBox = document.getElementById("startBox");
const endBox = document.getElementById("endBox");
const startRow = startBox.getAttribute("row");
const startCol = startBox.getAttribute("col");
const endRow = endBox.getAttribute("row");
const endCol = endBox.getAttribute("col");
const targetKey = `${endRow}|${endCol}`;
let foundDestn = false;
queue.push({
row: parseInt(startRow),
col: parseInt(startCol),
});
const startKey = `${startRow}|${startCol}`;
// start key doesnt have an parent
parentForCell[startKey] = { key: undefined };
const speedSlider = document.querySelector("#speed");
let timeMultiplier = speedSlider.value;
speedSlider.addEventListener("change", () => {
// console.log(speedSlider.value);
timeMultiplier = speedSlider.value;
});
while (queue.length > 0) {
// dequeue from queue
const { row, col } = queue.shift();
const currentKey = `${row}|${col}`;
const neighbours = [
{ row: row - 1, col },
{ row: row, col: col - 1 },
{ row: row + 1, col },
{ row, col: col + 1 },
];
if (currentKey === targetKey) {
foundDestn = true;
break;
}
for (let i = 0; i < neighbours.length; i++) {
let nRow = neighbours[i].row;
let nCol = neighbours[i].col;
let key = `${nRow}|${nCol}`;
// check if out of bound
if (!this.check(nRow, nCol)) {
continue;
}
let nBox = document.querySelector(`[row="${nRow}"][col="${nCol}"]`);
if (key in parentForCell) {
// check if it is visited
continue;
}
// if it is not already visited
// const current=document
parentForCell[key] = {
key: currentKey,
};
queue.push(neighbours[i]);
if (key === targetKey) {
break;
}
await this.waitForSeconds(0.2 / timeMultiplier);
if (nBox) nBox.classList += " pathSecondary";
}
}
// console.dir(parentForCell);
if (!foundDestn) {
alert("No path found");
return;
}
this.createPath(parentForCell, startKey, targetKey);
};
}
class astar extends Algorithm {
// Give heuristic value for current row and col (Manhattan Heuristic)
heuristic(row, col, endRow, endCol) {
return Math.abs(row - endRow) + Math.abs(col - endCol);
}
// g : cost to move from the starting position to the current position
// h : estimated cost to move from current positon to final destination
// f : total cost to move from start to end via current ( g + h)
astarAlgo = async () => {
let startBox = document.getElementById("startBox");
let endBox = document.getElementById("endBox");
let startRow = parseInt(startBox.getAttribute("row"));
let startCol = parseInt(startBox.getAttribute("col"));
let endRow = parseInt(endBox.getAttribute("row"));
let endCol = parseInt(endBox.getAttribute("col"));
const startKey = `${startRow}|${startCol}`;
const targetKey = `${endRow}|${endCol}`;
const closeSet = {};
const openSet = {};
openSet[startKey] = {
f: this.heuristic(startRow, startCol, endRow, endCol),
g: 0,
};
closeSet[startKey] = {
f: this.heuristic(startRow, startCol, endRow, endCol),
g: 0,
key: undefined,
};
let foundDestn = false;
const speedSlider = document.querySelector("#speed");
let timeMultiplier = speedSlider.value;
speedSlider.addEventListener("change", () => {
timeMultiplier = speedSlider.value;
});
// console.log(Object.keys(openSet).length === 0);
while (Object.keys(openSet).length !== 0) {
var lowest = Object.keys(openSet)[0];
for (var key in openSet) {
if (openSet[key].f < openSet[lowest].f) lowest = key;
}
if (lowest === targetKey) {
foundDestn = true;
break;
}
let [row, col] = lowest.split("|");
row = parseInt(row);
col = parseInt(col);
delete openSet[lowest];
let mainkey = lowest;
let nBox = document.querySelector(`[row="${row}"][col="${col}"]`);
// managing visualization speed
await this.waitForSeconds(0.2 / timeMultiplier);
if (nBox && nBox !== startBox) nBox.classList += " pathSecondary";
const neighbours = [
{ row: row - 1, col },
{ row: row, col: col - 1 },
{ row: row + 1, col },
{ row, col: col + 1 },
];
for (let i = 0; i < neighbours.length; i++) {
let nRow = neighbours[i].row;
let nCol = neighbours[i].col;
let key = `${nRow}|${nCol}`;
if (!this.check(nRow, nCol)) continue;
let gnew = parseInt(closeSet[mainkey].g) + 1;
if (closeSet[key] == undefined || gnew < closeSet[key].g) {
closeSet[key] = {
key: mainkey,
g: gnew,
f: gnew + this.heuristic(nRow, nCol, endRow, endCol),
};
if (!(key in openSet)) {
openSet[key] = {
f: gnew + this.heuristic(nRow, nCol, endRow, endCol),
g: gnew,
};
}
}
}
}
if (!foundDestn) {
alert("No path found");
return;
}
this.createPath(closeSet, startKey, targetKey);
};
}
class dijkstra extends Algorithm {
dijkstraAlgo = async () => {
let startBox = document.getElementById("startBox");
let endBox = document.getElementById("endBox");
let startRow = parseInt(startBox.getAttribute("row"));
let startCol = parseInt(startBox.getAttribute("col"));
let endRow = parseInt(endBox.getAttribute("row"));
let endCol = parseInt(endBox.getAttribute("col"));
const startKey = `${startRow}|${startCol}`;
const targetKey = `${endRow}|${endCol}`;
const closeSet = {};
const openSet = {};
openSet[startKey] = {
g: 0,
};
closeSet[startKey] = {
g: 0,
key: undefined,
};
let foundDestn = false;
const speedSlider = document.querySelector("#speed");
let timeMultiplier = speedSlider.value;
speedSlider.addEventListener("change", () => {
timeMultiplier = speedSlider.value;
});
// console.log(Object.keys(openSet).length === 0);
while (Object.keys(openSet).length !== 0) {
var lowest = Object.keys(openSet)[0];
for (var key in openSet) {
if (openSet[key].g < openSet[lowest].g) lowest = key;
}
if (lowest === targetKey) {
foundDestn = true;
break;
}
let [row, col] = lowest.split("|");
row = parseInt(row);
col = parseInt(col);
delete openSet[lowest];
let mainkey = lowest;
let nBox = document.querySelector(`[row="${row}"][col="${col}"]`);
// managing visualization speed
await this.waitForSeconds(0.2 / timeMultiplier);
if (nBox && nBox !== startBox) nBox.classList += " pathSecondary";
const neighbours = [
{ row: row - 1, col },
{ row: row, col: col - 1 },
{ row: row + 1, col },
{ row, col: col + 1 },
];
for (let i = 0; i < neighbours.length; i++) {
let nRow = neighbours[i].row;
let nCol = neighbours[i].col;
let key = `${nRow}|${nCol}`;
if (!this.check(nRow, nCol)) continue;
let gnew = parseInt(closeSet[mainkey].g) + 1;
if (closeSet[key] == undefined || gnew < closeSet[key].g) {
closeSet[key] = {
key: mainkey,
g: gnew,
};
if (!(key in openSet)) {
openSet[key] = {
g: gnew,
};
}
}
}
}
if (!foundDestn) {
alert("No path found");
return;
}
this.createPath(closeSet, startKey, targetKey);
};
}
export const dfsobj = new depthFirstSearch();
export const bfsobj = new breadthFirstSearch();
export const dijkstraobj = new dijkstra();
export const astarobj = new astar();