-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithms_1.js
613 lines (520 loc) · 18.3 KB
/
algorithms_1.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
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function TransposeAlg() {
this.description = "Graph transpose.\nA simple graph algorithm which mnerely swaps the direction of all edges.\n " +
"Only meaningful for directed graph.";
}
TransposeAlg.prototype.run = function(graph, show, canvas, logText, resultsText) {
// clear text area
logText.innerText = "";
var sLog = "";
var sleepTime;
var sleepTimeInc= 100;
var ctx = canvas.getContext("2d");
function Transpose(edge) {
var nd1 = edge.nodes[0];
var nd1_lbl = graph.allNodes[nd1].label;
var nd2 = edge.nodes[1];
var nd2_lbl = graph.allNodes[nd2].label;
sLog += + "edge [" + nd1_lbl + ", " + nd2_lbl + "] -> [" + nd2_lbl + ", " + nd1_lbl + "]\n";
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
var ed = edge;
sleep(sTime).then(() => {
ed.isSel = true;
// edge.draw(ctx);
graph.transpose(edge);
graph.redraw(canvas);
//nd.isSel = true;
//nd.draw(ctx);
logText.innerText = sLog;
});
} else {
logText.innerText = sLog;
graph.transpose(edge);
}
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
var ed = edge;
sleep(sTime).then(() => {
ed.isSel = false;
// edge.draw(ctx);
graph.redraw(canvas);
//nd.isSel = true;
//nd.draw(ctx);
});
}
}
graph.allEdges.forEach(edge => {
/* console.log(obj); */
if(edge != null) {
// edge.draw(ctx);
Transpose(edge);
}
});
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
sleep(sTime).then(() => {
//nd.isSel = true;
//nd.draw(ctx);
resultsText.innerText = "Transpose done";
graph.redraw(canvas);
});
}
else {
resultsText.innerText = "Transpose done";
graph.redraw(canvas);
}
}
function DFSAlg() {
this.description = "Depth first search (DFS).\nFrom start node, recursively attempt to reach all nodes in the graph.\n " +
"Exhaustively search nodes in 'depth', before attempting to search next node.\n" +
"Ah analogy would be single person going for a walk, then retracing their steps when they get to a dead end.\n" +
"This is a basic stragey is used in many graph algorithms\n" +
"If no node is selected, it will run with the first node.";
this.discFn = null; // custom function to execute when DFS discovers a given node
this.finishFn = null; // custom function to execute when DFS finishes a given node
this.nodesVisited = null;
}
DFSAlg.prototype.run = function(graph, show, canvas, logText, resultsText, initAlg=true) {
var nodesVisited;
var discOrder;
var finishOrder;
var discFn = this.discFn;
var finishFn = this.finishFn;
var s = "";
var rTxt;
var ctx = canvas.getContext("2d");
var sleepTime = 0;
var sleepTimeInc = 200;
function updateNode(nodeHnd) {
nodeHnd.color = "#FA0000"; // color node red
nodeHnd.draw(ctx);
rTxt = rTxt + " -> " + nodeHnd.label;
resultsText.innerText = rTxt;
}
function DFS(node, recLevel) {
if(node < 0)
return;
// we have already visited this node
if(nodesVisited[node])
return;
nodesVisited[node] = true;
var nd = graph.allNodes[node];
if (nd == null)
return;
var edgeList = graph.adjMat[node];
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
sleep(sTime).then(() => {
nd.isSel = true;
updateNode(nd);
});
}
else {
updateNode(nd);
}
discOrder.push(node);
// execute custom discovery function
if(discFn != null)
discFn();
edgeList.forEach(edgeID => {
s = s + " eID= " + edgeID;
logText.innerText = s;
if(edgeID >= 0) {
var e = graph.allEdges[edgeID];
if(e != null) {
var nextNode = e.nodes[1];
if(node == nextNode) {
if(e.isBiDir()) {
nextNode = e.nodes[0];
} else {
nextNode = -1;
}
}
s = s + " nextNode(ID)= " + nextNode;
logText.innerText = s;
if(nextNode >= 0 && !nodesVisited[nextNode]) {
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
sleep(sTime).then(() => {
nd.isSel = false;
e.isSel = true;
e.draw(ctx);
nd.draw(ctx);
});
}
// s2 = s2 + " ->" + nextNode;
//resultsText.innerText = s2;
// recursively call DFS
DFS(nextNode, recLevel + 1);
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
sleep(sTime).then(() => {
nd.isSel = true;
e.isSel = false;
/*
e.draw(ctx);
nd.draw(ctx);
*/
graph.redraw(canvas);
});
}
}
}
}
});
finishOrder.push(node);
// execute custom discovery function
if(finishFn != null)
finishFn();
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
sleep(sTime).then(() => {
nd.isSel = false;
nd.draw(ctx);
});
}
}
var ndNum = 0;
var objSel = graph.objSel;
if(objSel != null) {
if(objSel.objType() == NODE)
ndNum = objSel.nodeNum;
}
if(initAlg) {
sleepTime = 0;
discOrder = [];
finishOrder = [];
nodesVisited = new Array(graph.allNodes.length).fill(false);
logText.innerText = "";
rTxt = "";
this.nodesVisited = nodesVisited;
this.discOrder = discOrder;
this.finishOrder = finishOrder;
this.rTxt = rTxt;
} else {
discOrder = this.discOrder;
finishOrder = this.finishOrder;
nodesVisited = this.nodesVisited;
sleepTime = this.sleepTime;
rTxt = this.rTxt;
}
/*
for(var i=0; i<graph.allNodes.length; i++)
nodesVisited.push(false);
*/
DFS(ndNum, 0);
this.sleepTime = sleepTime;
/*
nodeOrder.forEach => ( nd => {
}
); */
}
function BFSAlg() {
this.description = "Breadth first search (BFS).\n From start node, attempt to reach all nodes in the graph.\n " +
"Unlike DFS, BFS will expand the frontier in breadth, before searching each node in 'depth'.\n" +
"An analogy would be several people going for a walk at the same time\n" +
"This is a basic stragey is used in many graph algorithms\n" +
"If no node is selected, it will run with the first node.";
}
BFSAlg.prototype.run = function(graph, show, canvas, logText, resultsText) {
var ctx = canvas.getContext('2d');
var nodesVisited = [];
var sLog = "";
var sRes = "";
function updateNode(nodeHnd) {
nodeHnd.color = "#FA0000"; // color node red
/*
s2 = s2 + " -> " + nodeHnd.label;
resultsText.innerText = s2;
*/
}
function BFS() {
var ndNum = nodesToVisit.pop();
var ndH = graph.allNodes[ndNum];
var edgeList = graph.adjMat[ndNum];
console.log("ndNum= " + ndNum + " edgeList= " + edgeList);
sRes += " -> " + ndH.label + "(";
sLog += "node " + ndH.label + " edges=";
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
var ndHnd = graph.allNodes[ndNum];
sleep(sTime).then(() => {
ndHnd.isSel = true;
ndHnd.draw(ctx);
resultsText.innerText = sRes;
logText.innerText = sLog;
});
} else {
logText.innerText = sLog;
resultsText.innerText = sRes;
}
var newNodes = [];
edgeList.forEach(edgeID => {
sLog += " " + edgeID;
logText.innerText = sLog;
if(edgeID >= 0) {
var e = graph.allEdges[edgeID];
if(e != null) {
var nextNode = e.nodes[1];
if(ndNum == nextNode) {
if(e.isBiDir()) {
nextNode = e.nodes[0];
} else {
nextNode = -1;
}
}
if(nextNode != -1) {
if(!nodesVisited[nextNode]) {
newNodes.push(nextNode);
var nxtNdHnd = graph.allNodes[nextNode];
sRes += " " + nxtNdHnd.label;
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
var edg = e;
sleep(sTime).then(() => {
edg.isSel = true;
edg.draw(ctx);
resultsText.innerText = sRes;
});
}
else {
resultsText.innerText = sRes;
}
nodesVisited[nextNode] = true;
nodesToVisit.push(nextNode);
}
}
}
}
});
sRes += ") ";
console.log("newNodes= " + newNodes);
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
var ndH = graph.allNodes[ndNum];
var newNodesCpy = [...newNodes];
var eList = [...edgeList];
sleep(sTime).then(() => {
resultsText.innerText = sRes;
ndH.isSel = false;
eList.forEach(edgeID => {
if(edgeID >= 0) {
var e = graph.allEdges[edgeID];
if(e != null) {
e.isSel = false;
}
}
});
console.log("newNodesCpy= ", newNodesCpy);
newNodesCpy.forEach(ndNum => {
ndH = graph.allNodes[ndNum];
updateNode(ndH);
});
graph.redraw(canvas);
});
} else {
resultsText.innerText = sRes;
}
} // end BFS
resultsText.innerText = "";
logText.innerText = "";
var ndNum = 0;
var objSel = graph.objSel;
if(objSel != null) {
if(objSel.objType() == NODE)
ndNum = objSel.nodeNum;
}
for(var i=0; i<graph.allNodes.length; i++)
nodesVisited.push(false);
nodesVisited[ndNum] = true;
// initialize nodes to visit
var nodesToVisit = new Queue();
nodesToVisit.push(ndNum);
var sleepTime = 0;
var sleepTimeInc = 200;
var ndHnd = graph.allNodes[ndNum];
updateNode(ndHnd);
ndHnd.draw(ctx);
while(!nodesToVisit.empty()) {
BFS();
}
sRes += "BFS done";
if(show) {
sleepTime += sleepTimeInc;
var sTime = sleepTime;
sleep(sTime).then(() => {
resultsText.innerText = sRes;
});
}
else {
resultsText.innerText = sRes;
}
}
function SCCAlg() {
this.description = "Strongly connected components.\nThe strong connected components of a graph, divides the graph into sets of nodes.\n" +
"Each node in a given set, must be reachable from all other nodes in the set.\n" +
"Generally only makes sense for directed graphs, or bidirectional graphs which are disconnected.\n" +
"for undirected graphs";
}
SCCAlg.prototype.run = function(graph, show, canvas, logText, resultsText) {
var ctx = canvas.getContext("2d");
var sleepTime;
var sleepTimeInc = 100;
var N = graph.allNodes.length;
var comp = new Array(N);
comp.fill(-1);
var transEdges = []; // transposed edges - stored separately so algoirthm and display can run independently
var transMat = []; // transposed adjacency matrix - stored separately so algoirthm and display can run independently
function updateNodeColor(sTime, nd, clr) {
sleep(sTime).then( () => {
console.log("updateNodeColor nd = " + nd.nodeNum + " clr= " + clr);
nd.color = clr;
nd.draw(ctx);
});
}
function copyNodeColor(sTime, nd, rt) {
sleep(sTime).then( () => {
console.log("copyNodeColor nd = " + nd.nodeNum + " rt = " + rt.nodeNum + " rt.color= " + rt.color);
nd.color = rt.color;
nd.draw(ctx);
});
}
function updateEdge(sTime, edge, isSel) {
sleep(sTime).then( () => {
edge.isSel = isSel;
graph.transpose(edge);
graph.redraw(canvas);
});
}
function Assign(nodeNum, root) {
console.log('SCC.Assign() nodeNum= ' + nodeNum + ' root= ' + root);
if (nodeNum < 0)
return;
var nd = graph.allNodes[nodeNum];
if(nd == null)
return;
if(comp[nodeNum] < 0) {
comp[nodeNum] = root;
if(show) {
sleepTime += sleepTimeInc;
copyNodeColor(sleepTime, nd, graph.allNodes[root]);
} else {
nd.color = graph.allNodes[root].color;
}
}
else return; // we have already assigned component
eLst = transMat[nodeNum];
console.log('eLst= ' + eLst);
eLst.forEach(edgeNum => {
edge = transEdges[edgeNum];
if(edge != null) {
nd_adj = edge.nodes[1];
if((edge.arrowDir != ARROW_TYPE_DST) && (nd_adj == nodeNum))
nd_adj = edge.nodes[0];
// console.log('nodeNum= ' + nodeNum + ' edge.nodes= ' + edge.nodes + ' nd_adj= ' + nd_adj);
Assign(nd_adj, root);
}
});
}
var DFS = new DFSAlg();
// Koseraju's algorithm - first construct a list of nodes by DFS'ing all nodes, saving finish times
initAlg = true;
graph.allNodes.forEach(nd => {
if (nd != null) {
var ndNum = nd.nodeNum;
console.log('ndNum= ' + ndNum + ' finishOrder= ' + DFS.finishOrder);
if (graph.objSel != null)
graph.objSel.isSel = false;
// depth first search to visit all nodes connected to this node
// DFS(ndNum, lst);
graph.objSel = graph.allNodes[ndNum];
DFS.run(graph, show, canvas, logText, resultsText, initAlg);
graph.objSel = null;
}
initAlg = false;
});
sleepTime = DFS.sleepTime;
var clrNum = 0;
// assign SCC based on transpose
const hue = [0.0, 0.083, 0.167, 0.319, 0.5, 0.658, 0.764, 0.847];
const lgt = [0.5, 0.25, 0.75];
const sat = [1.0, 0.75, 0.5, 0.25];
finishOrder = DFS.finishOrder;
console.log('SCC finishOrder.length= ' + finishOrder.length + " sleepTime= " + sleepTime);
// transpose graph
for(var i = 0; i<N; i++) {
row = Array(N).fill(-1);
transMat.push(row);
}
var j = 0;
transEdges = Array(graph.allEdges.length).fill(null);
graph.allEdges.forEach(edge => {
// store transposed edges separate, so algorithm can run properly indepednent of display
if(edge != null) {
var e = new Edge(edge.nodes[1], edge.nodes[0], edge.edgeNum, null, edge.arrowDir);
transEdges[j] = e;
transMat[edge.nodes[1]][edge.nodes[0]] = edge.edgeNum;
if(show) {
sleepTime += sleepTimeInc/2;
updateEdge(sleepTime, edge, true);
} else {
graph.transpose(edge);
}
}
j++;
});
while(finishOrder.length > 0) {
ndNum = finishOrder.pop();
if(comp[ndNum] < 0) {
var nd = graph.allNodes[ndNum];
// create new color
var h = hue[clrNum % hue.length];
var idx = Math.floor(clrNum / hue.length) % lgt.length;
var l = lgt[idx];
idx = Math.floor(clrNum / (hue.length * lgt.length)) % sat.length;
var s = sat[idx];
var clr = hslToRgb(h, s, l);
var clr_hx = rgbToHex(... clr);
console.log('clr= ' + clr + ' clr_hx= ' + clr_hx);
if(show) {
sleepTime += sleepTimeInc;
updateNodeColor(sleepTime, nd, clr_hx);
} else {
nd.color = clr_hx;
}
Assign(ndNum, ndNum);
// increemnt color
clrNum++;
}
}
// transpose graph back
graph.allEdges.forEach(edge => {
if(show) {
sleepTime += sleepTimeInc/2;
updateEdge(sleepTime, edge, false);
} else {
graph.transpose(edge);
}
});
if(show) {
sleepTime += sleepTimeInc;
sleep(sleepTime).then(() => {
graph.redraw(canvas);
});
} else {
graph.redraw(canvas);
}
}