-
Notifications
You must be signed in to change notification settings - Fork 5
/
sketch.js
697 lines (628 loc) · 22.3 KB
/
sketch.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
// Declaring needed variables
let started
let algo
let startButton
let screen
let graph
let rows
let cols
let resolution
let openSet
let closedSet
let source;
let destination;
let shortestPath
let w;
let h;
let sourceSelected
let destinationSelected
// sourceColor = color(87, 50, 168)
// destColor = color(140, 68, 20)
function resetCanvas() {
console.log(new Node(0, 0))
// Initializing variables
started = false
algo = null
resolution = 30
openSet = []
closedSet = []
shortestPath = []
sourceSelected = false
destinationSelected = false
rows = floor(height / resolution);
cols = floor(width / resolution);
w = width / cols;
h = height / rows;
graph = twoDArray(rows, cols);
startButton = document.getElementById("startButton")
startButton.disabled = false
startButton.innerHTML = "Visualize"
startButton.onclick = start;
let message = document.getElementById('message')
message.innerHTML = ""
// creating the graph
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
graph[i][j] = new Node(i, j);
}
}
// determining neighbors of each vertices
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
graph[i][j].addNeighbor();
}
}
// Initializing random source and destination if not chosen
if (source === undefined || destination === undefined) {
x = Math.floor(Math.random() * cols / 2)
y = Math.floor(Math.random() * rows)
source = graph[x][y];
x = Math.floor(Math.random() * (cols - Math.floor((cols / 2 + 1)))) + Math.floor((cols / 2 + 1));
y = Math.floor(Math.random() * rows)
destination = graph[x][y];
}
// otherwise Reinitializing old source & destination from graph's new objects
else {
graph.forEach(row => {
row.forEach((node) => {
if (node.i === source.i && node.j === source.j) {
source = node
}
if (node.i === destination.i && node.j === destination.j) {
destination = node
}
})
})
}
//making sure source and destination aren't obstacls;
source.obstacle = false;
destination.obstacle = false;
background(255);
// revealing the canvas on screen
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
graph[i][j].show(255);
}
}
source.show(color(87, 50, 168));
destination.show(color(140, 68, 20));
noLoop();
console.log(openSet)
}
function Node(i, j) {
this.i = i;
this.j = j;
this.x = this.i * resolution;
this.y = this.j * resolution;
this.r = resolution - 1;
// needed for A* and Greedy
this.f = 0;
this.g = 0;
this.h = 0;
// needed for Dijkstra
this.d = Infinity
this.obstacle = false;
this.parent = undefined;
this.neighbors = []
this.dragging = false
this.show = (color) => {
console.log(color)
let x = this.x;
let y = this.y;
let r = this.r;
if (this.obstacle) {
fill(128, 128, 128);
}
else {
fill(color);
}
// fill(color);
stroke(66, 148, 255, 90);
strokeWeight(1);
rect(x, y, r, r);
}
this.addNeighbor = () => {
let i = this.i;
let j = this.j;
//Orthogonal neighbors
if (i > 0) this.neighbors.push(graph[i - 1][j]);
if (i < cols - 1) this.neighbors.push(graph[i + 1][j]);
if (j > 0) this.neighbors.push(graph[i][j - 1]);
if (j < rows - 1) this.neighbors.push(graph[i][j + 1]);
//Diagonal Neighbors
// if (i > 0 && j > 0) this.neighbors.push(graph[i - 1][j - 1]);
// if (i < cols - 1 && j < rows - 1) this.neighbors.push(graph[i + 1][j + 1]);
// if (i > 0 && j < rows - 1) this.neighbors.push(graph[i - 1][j + 1]);
// if (i < cols - 1 && j > 0) this.neighbors.push(graph[i + 1][j - 1]);
}
this.clicked = () => {
if (sourceSelected) {
// if(this == source){
this.show(color(87, 50, 168))
// source = this
// srcORdstClicked = false
}
else if (destinationSelected) {
this.show(color(140, 68, 20))
}
else if (!this.obstacle) {
this.obstacle = true;
this.show(color(128, 128, 128));
}
// else{
// this.obstacle = false;
// this.show(color(255,255,255));
// }
}
}
function twoDArray(rows, cols) {
let arrays = new Array(cols);
for (let i = 0; i < arrays.length; i++) {
arrays[i] = new Array(rows)
}
return arrays;
}
function windowResized() {
centerCanvas();
}
function centerCanvas() {
var x = ((windowWidth) - width) / 2;
var y = ((windowHeight - (windowHeight * 0.20)) - height) / 2;
screen.position(x, y);
}
function setup() {
// making the canvas
screen = createCanvas(windowWidth - (windowHeight * 0.05), windowHeight - (windowHeight * 0.20));
screen.parent("sketch01");
centerCanvas();
// startButton.parent("sketch01");
resetCanvas()
}
function dijkstraInitialize(){
source.d = 0
// Creating a openSet initializing with all the node of the graph
graph.forEach( row => {
row.forEach( node => {
openSet.push(node)
})
})
}
function initialize() {
openSet.push(source);
}
function BFSorDFS_initialize() {
openSet.push(source);
closedSet.push(source)
}
function draw() {
if (started) {
// Algorithm for Dijkstra
if (algo == "Dijkstra") {
if (openSet.length > 0) {
current = lowestDscoreNode(); //It'll return the node least d value
// Means there's no possible path with finite distance from source to destination
if(current.d === Infinity){
console.log('no solution');
noLoop();
return;
}
if (current === destination) {
noLoop();
console.log("We're Done!")
}
//removing the "current" vertex from openSet and adding it to closedSet
var removeIndex = openSet.map(function (item) { return item; }).indexOf(current);
openSet.splice(removeIndex, 1);
closedSet.push(current)
for (neighbor of current.neighbors) {
// Checking to see if the node is valid
if (!neighbor.obstacle) {
// let's calculate dist(current)+cost_between(current,neighbor)
dScore = current.d + 1
if(dScore < neighbor.d){
neighbor.d = dScore
neighbor.parent = current
}
}
}
}
}
// Algorithm for A* Search
if (algo == "A* Search") {
if (openSet.length > 0) {
current = lowestFscoreNode();
if (current == destination) {
noLoop();
console.log("We're Done!")
}
//removing the "current" vertex from openSet and adding it to closedSet
var removeIndex = openSet.map(function (item) { return item; }).indexOf(current);
openSet.splice(removeIndex, 1);
closedSet.push(current);
for (neighbor of current.neighbors) {
// Checking to see if the node is valid
if (!closedSet.includes(neighbor) && !neighbor.obstacle) {
gScore = current.g + heuristic(neighbor, current);
let isGbetter = false;
if (openSet.includes(neighbor)) {
if (gScore < neighbor.g) {
neighbor.g = gScore;
isGbetter = true;
}
}
else {
neighbor.g = gScore;
isGbetter = true;
openSet.push(neighbor);
}
if (isGbetter) {
neighbor.h = heuristic(neighbor, destination);
neighbor.f = neighbor.g + neighbor.h;
neighbor.parent = current;
}
}
}
}
else {
console.log('no solution');
noLoop();
return;
}
}
// Algorithm for Greedy Best First Search Search
if (algo == "Greedy Best First Search") {
if (openSet.length > 0) {
current = lowestHeuristicNode();
if (current == destination) {
noLoop();
console.log("We're Done!")
}
//removing the "current" vertex from openSet and adding it to closedSet
var removeIndex = openSet.map(function (item) { return item; }).indexOf(current);
openSet.splice(removeIndex, 1);
closedSet.push(current);
for (neighbor of current.neighbors) {
// Checking to see if the node is valid
if (!closedSet.includes(neighbor) && !openSet.includes(neighbor) && !neighbor.obstacle) {
neighbor.h = heuristic(neighbor, destination);
neighbor.parent = current;
openSet.push(neighbor)
}
}
}
else {
console.log('no solution');
noLoop();
return;
}
}
// Algorithm for Breadth First Search
if (algo == "Breadth First Search") {
if (openSet.length > 0) {
current = openSet[0]
if (current == destination) {
noLoop();
console.log("We're Done!")
}
//removing the "current" vertex from openSet and adding it to closedSet
var removeIndex = openSet.map(function (item) { return item; }).indexOf(current);
openSet.splice(removeIndex, 1);
console.log(openSet)
for (neighbor of current.neighbors) {
if (!closedSet.includes(neighbor) && !neighbor.obstacle) {
openSet.push(neighbor);
closedSet.push(neighbor);
neighbor.parent = current
}
}
}
else {
console.log('no solution');
noLoop();
return;
}
}
// Algorithm for Depth First Search
if (algo == "Depth First Search") {
if (openSet.length > 0) {
console.log(openSet)
current = openSet[openSet.length - 1]
if (current == destination) {
noLoop();
console.log("We're Done!")
}
//removing the "current" vertex from openSet and adding it to closedSet
var removeIndex = openSet.map(function (item) { return item; }).indexOf(current);
openSet.splice(removeIndex, 1);
console.log(openSet)
for (neighbor of current.neighbors) {
if (!closedSet.includes(neighbor) && !neighbor.obstacle) {
openSet.push(neighbor);
closedSet.push(neighbor);
neighbor.parent = current
}
}
}
else {
console.log('no solution');
noLoop();
return;
}
}
background(255);
// revealing the canvas on screen
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
graph[i][j].show(255);
}
}
//Coloring the visited, unvisited vertices and the shortest path
for (node of openSet) {
if(algo === "Dijkstra"){
if(node.d != Infinity){
node.show(color(45, 196, 129));
}
}
else{
node.show(color(45, 196, 129));
}
}
for (node of closedSet) {
node.show(color(255, 0, 0, 50));
}
//initialize shortestPath array first
shortestPath = [];
let temp = current;
shortestPath.push(temp);
while (temp.parent) {
shortestPath.push(temp.parent);
temp = temp.parent;
}
// for (Node of shortestPath) {
// Node.show(color(246, 196, 76));
// }
noFill();
stroke(255, 0, 200);
strokeWeight(4);
beginShape();
for (path of shortestPath) {
vertex(path.i * resolution + resolution / 2, path.j * resolution + resolution / 2);
}
endShape();
source.show(color(87, 50, 168));
destination.show(color(140, 68, 20));
}
}
function dropdown(event) {
algo = event.target.text
let startButton = document.getElementById('startButton')
startButton.innerHTML = `Start ${algo}`
let message = document.getElementById('message')
if(algo === "A* Search"){
message.innerHTML = `Insight: A* Search <span style = "font-weight: bold;">Gurantees</span> Shortest Path`
}
else if(algo === "Dijkstra"){
message.innerHTML = `Insight: Dijkstra's Algorithm Or A Variant Of It Is Known As UCS <span style = "font-weight: bold;">Gurantees</span> Shortest Path`
}
else if(algo === "Breadth First Search"){
message.innerHTML = `Insight: Breadth First Search (BFS) <span style = "font-weight: bold;">Gurantees</span> Shortest Path In An <span style = "font-weight: bold;">Unweighted Graph</span> And A Feasible Choice <span style = "font-weight: bold;">If The Destination Is Closer To The Source</span>`
}
else if(algo === "Depth First Search"){
message.innerHTML = `Insight: Depth First Search (DFS) <span style = "font-weight: bold;">Does Not Gurantee</span> Shortest Path Though Is A Feasible Choice For Memory <span style = "font-weight: bold;">If The Destination Is Far Away From The Source</span>`
}
else{
message.innerHTML = `Insight: Greedy Best-First Search <span style = "font-weight: bold;">Does Not Gurantee</span> Shortest Path As It Takes Decision Solely Based On <span style = "font-weight: bold;">Heuristics</span>`
}
}
function start() {
if (algo === null) {
let startButton = document.getElementById('startButton')
startButton.innerHTML = `Pick An Algorithm!`
return
}
else if(algo === "Dijkstra"){
dijkstraInitialize()
}
else if (algo != "Breadth First Search" && algo != "Depth First Search") {
initialize()
}
else {
BFSorDFS_initialize()
}
started = true;
startButton.disabled = true
loop();
}
function throwObstacles() {
// It maintains obstacle's distribution in the graph
let weights = [
["Obstacle", 30],
["Non Obstacle", 70]
]
console.log(weights[1][1])
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
if (graph[i][j] != source && graph[i][j] != destination) {
// taking decision if we should make this node an obstacle or not
let decision = weightedRandom(weights)
if (decision === "Obstacle") {
graph[i][j].obstacle = true
graph[i][j].show()
}
}
}
}
}
function mouseDragged() {
if(started){
return
}
console.log("clicked");
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
//let d = dist(mouseX, mouseY, graph[i][j].x, graph[i][j].y);
if (mouseX >= graph[i][j].x && mouseX <= graph[i][j].x + graph[i][j].r && mouseY >= graph[i][j].y && mouseY <= graph[i][j].y + graph[i][j].r) {
console.log("in IF");
if (graph[i][j] != source && graph[i][j] != destination) {
graph[i][j].clicked();
}
if (sourceSelected) {
console.log("HERE")
// srcORdstClicked = true
// change prev source's color
source.show(255)
source = graph[i][j]
// source.show(color(87, 50, 168))
graph[i][j].clicked();
}
if (destinationSelected) {
// change prev source's color
destination.show(255)
destination = graph[i][j]
// source.show(color(87, 50, 168))
graph[i][j].clicked();
}
}
}
}
}
function mousePressed() {
if(started){
return
}
console.log("clicked2");
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
//let d = dist(mouseX, mouseY, graph[i][j].x, graph[i][j].y);
if (mouseX >= graph[i][j].x && mouseX <= graph[i][j].x + graph[i][j].r && mouseY >= graph[i][j].y && mouseY <= graph[i][j].y + graph[i][j].r) {
if (graph[i][j] != source && graph[i][j] != destination) {
console.log("in IF");
console.log(graph[i][j])
console.log(source)
console.log(graph[i][j] === source)
graph[i][j].clicked();
}
else {
if (source === graph[i][j]) {
sourceSelected = true
}
if (destination === graph[i][j]) {
destinationSelected = true
}
// console.log("HERE")
// srcORdstClicked = true
// change prev source's color
// source.show(255)
// source = graph[i][j]
// source.show(color(87, 50, 168))
// graph[i][j].clicked();
}
}
}
}
}
function mouseReleased() {
if (sourceSelected || destinationSelected) {
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
//let d = dist(mouseX, mouseY, graph[i][j].x, graph[i][j].y);
if (mouseX >= graph[i][j].x && mouseX <= graph[i][j].x + graph[i][j].r && mouseY >= graph[i][j].y && mouseY <= graph[i][j].y + graph[i][j].r) {
if (sourceSelected) {
if (graph[i][j] === destination) {
source = graph[i - 1][j]
source.obstacle = false
graph[i][j].show(color(140, 68, 20))
source.show(color(87, 50, 168))
sourceSelected = false
}
else {
source = graph[i][j]
source.obstacle = false
source.show(color(87, 50, 168))
sourceSelected = false
}
}
else {
if (graph[i][j] === source) {
destination = graph[i - 1][j]
destination.obstacle = false
source.show(color(87, 50, 168))
destination.show(color(140, 68, 20))
destinationSelected = false
}
else {
destination = graph[i][j]
destination.obstacle = false
destination.show(color(140, 68, 20))
destinationSelected = false
}
}
}
}
}
}
}
function heuristic(node, goal) {
//euclidean distance
// dx = abs(node.x - goal.x);
// dy = abs(node.y - goal.y);
// return 1 * sqrt(dx * dx + dy * dy);
//Manhattan distance
dx = abs(node.x - goal.x);
dy = abs(node.y - goal.y);
return 1 * (dx + dy);
// let d = dist(a.i, a.j, b.i, b.j);
// let d = abs(a.i - b.i) + abs(a.j - b.j);
// return d;
}
function lowestFscoreNode() {
let minNode = openSet[0];
for (node of openSet) {
if (node.f < minNode.f) {
minNode = node;
}
}
return minNode;
}
function lowestDscoreNode() {
let minNode = openSet[0];
for (node of openSet) {
if (node.d < minNode.d) {
minNode = node;
}
}
return minNode;
}
function lowestHeuristicNode() {
let minNode = openSet[0];
for (node of openSet) {
if (node.h < minNode.h) {
minNode = node;
}
}
return minNode;
}
function weightedRandom(data) {
// First, we loop the main dataset to count up the total weight. We're starting the counter at one because the upper boundary of Math.random() is exclusive.
let total = 1;
for (let i = 0; i < data.length; ++i) {
total += data[i][1];
}
// Total in hand, we can now pick a random value akin to our
// random index from before.
const threshold = Math.floor(Math.random() * total);
// Now we just need to loop through the main data one more time
// until we discover which value would live within this
// particular threshold. We need to keep a running count of
// weights as we go, so let's just reuse the "total" variable
// since it was already declared.
total = 0;
for (let i = 0; i < data.length; ++i) {
// Add the weight to our running total.
total += data[i][1];
// If this value falls within the threshold, we're done!
if (total >= threshold) {
return data[i][0];
}
}
}