-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataStruct.js
More file actions
2504 lines (2287 loc) · 78.3 KB
/
Copy pathDataStruct.js
File metadata and controls
2504 lines (2287 loc) · 78.3 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
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module DataStruct
* @description Data structures
* @version 1.0
* @since 1.1
* @license MIT
* @author Maximilian Berkmann <maxieberkmann@gmail.com>
* @copyright Maximilian Berkmann 2016
* @requires module:essence
* @requires DOM
* @requires Maths
* @requires Files
* @requires Misc
* @type {Module}
* @exports DataStruct
*/
var DataStruct = new Module("DataStruct", "Data structures", ["DOM", "Maths", "Files", "Misc"]);
/* eslint no-undef: 0 */
/**
* @description Linked list
* @param {*} [pl=1] Payload
* @param {LinkedList} [nx={payload: 1, next: ?LinkedList}] Next
* @param {string} name Name of the linked list
* @returns {LinkedList} Linked list
* @this LinkedList
* @constructor
* @since 1.0
* @property {NumberLike} LinkedList.payload Payload
* @property {LinkedList|Object} LinkedList.next Next element
* @property {string} LinkedList.name Name
* @property {function(this:LinkedList): string} LinkedList.show Show the linked list
* @property {function(this:LinkedList): string} LinkedList.next.show Show the linked list
* @property {function(): string} LinkedList.toString String representation
*/
function LinkedList (pl, nx, name) {
this.payload = pl || 1;
this.next = nx || {payload: 1, next: null};
this.next.show = function () {
/** @this LinkedList.next */
//noinspection JSPotentiallyInvalidUsageOfThis
return this.name + ":" + this.next.payload + "->"
};
this.name = name;
this.show = function () {
return this.name + ":" + this.payload + "->" + this.next.show()
};
this.toString = function () {
return "LinkedList(" + this.show() + ")"
};
return this
}
/**
* @description Node
* @param {*} [pl=1] Payload
* @param {Node} [nx] Next node
* @param {Node} [pv] Previous node
* @this Node
* @return {Node} Node
* @constructor
* @since 1.0
* @property {NumberLike} Node.payload Payload
* @property {Node} Node.next Next node
* @property {function(): Node} Node.traverse Node traversal
* @property {Function} Node.print Node printer
* @property {Function} Node.printList Node list printer
* @property {function(): Node} Node.last Get the last node
* @property {function(NumberLike)} Node.append Append the list with a new node
* @property {Function} Node.remove Node remover
* @property {function(): Node} Node.reverse List reversal
* @property {function(NumberLike, number): Nums} Node.find Look for a node
* @property {function(Node): boolean} Node.equals Node comparator
* @property {function(): string} Node.toString String representation
*/
function Node (pl, nx, pv) {
this.payload = pl || 1;
this.next = nx; //Or new node()
this.prev = pv;
this.traverse = function () {
if (this.next) this.next.traverse();
Essence.say("payload: " + this.payload);
};
this.print = function () {
if (this.next != null) this.next.print();
Essence.print(this.payload + "=>");
};
this.printList = function () {
if (this.next === null) Essence.txt2print += "->" + this.payload;
else this.next.printList();
Essence.print("");
};
this.last = function () {
if (this.next === null) return this;
else return this.next.last()
};
this.append = function (n) {
if (this.next === null) {
this.next = new Node(n); //If there is no next node, link the new one here
this.next.prev = this;
} else this.next.append(n); //Else, append to next node
};
this.remove = function () {
var n = this.next;
this.next = n.next;
n.next.prev = this;
};
this.reverse = function () {
if (this.next == null) return this;
else {
var newHead = this.next.reverse();
newHead.next = this;
newHead.prev = null;
this.prev = newHead;
this.next = null;
return newHead
}
};
this.toString = function () {
return "Node(payload = " + this.payload + ", previous = " + this.prev + ", next = " + this.next + ")"
};
this.equals = function (node) {
return this.payload === node.payload && this.next.equals(node.next) && this.prev.equals(node.prev)
};
this.find = function (n, d) {
if (!d) d = 0;
if (this.payload === n) return d;
if (this.next) return this.next.find(n, d + 1);
return [-1, d]
};
return this;
}
/**
* @description Nodes for path finding algs
* @param {number} [g=0] Current total cost
* @param {number} [h=0] Current total heuristic
* @param {number[]} [pos=[0, 0]] 2D position of the node
* @param {Edge[]} [edges=[]] List of edges connected to the path node
* @param {*} [payload=""] Payload
* @returns {Vertex} Vertex
* @this Vertex
* @constructor
* @since 1.0
* @property {number} Vertex.g Cost of the path to that node
* @property {number} Vertex.h Heuristic to get to that node
* @property {number} Vertex.f Cost of the path (g) + heuristic estimate
* @property {Edge[]} Vertex.edges List of edges connected to the path node
* @property {*} Vertex.payload Payload (content/data) of the node
* @property {number[]} Vertex.pos Position of the node
* @property {?Vertex} Vertex.parent Parent of the vertex
* @property {function(number): Vertex} Vertex.back Go n vertexes back
* @property {function(Vertex): boolean} Vertex.isCloser Check if the current vertex is closer than the other one
* @property {function(Vertex[]): string} Vertex.toString String representation
* @property {function(Vertex[])} Vertex.join Join Vertexes with edges
* @property {function(): Vertex} Vertex.getVertexInEdge Get the vertex connected to a particular edge
* @property {function(): Vertex[]} Vertex.getConnectedVertices Get the vertexes connected to this one
* @property {function(): (Vertex[]|Vertex[][])} Vertex.getNetwork Get the network/tree/graph/map of vertices connected to this one
* @property {function(): number} Vertex.size Size of the vertex's network
* @property {function(Vertex): number} Vertex.distanceFrom Distance from this vertex to another
* @property {function(): Vertex} Vertex.getNearestVertex Get the nearest connected vertex
*/
function Vertex (g, h, pos, payload, edges) {
this.g = g || 0;
this.h = h || 0;
this.f = this.g + this.h || 1;
this.pos = pos || [0, 0];
this.parent = null;
this.payload = payload || "";
this.edges = edges || [];
this.back = function (n) {
return (isNon(n) || n <= 1)? this.parent: this.parent.back(n - 1);
};
this.isCloser = function (vertex) {
return this.f <= vertex.f;
};
this.toString = function () {
var edges = this.edges.length > 0? this.edges.map(function (edge) {
try {
return edge.toString()
} catch (err) {
return null;
}
}): "";
return "Vertex(g=" + this.g + ", h=" + this.h + ", f=" + this.f + ", pos=[" + this.pos.toStr(true) + "], payload=" + this.payload + ", edges=[" + edges + "], parent=" + (this.parent === null? null: this.parent.toString()) + ")";
};
this.join = function (vertices) {
for (var i = 0; i < vertices.length; i++) {
if (!isType(this.edges[i], "Edge")) this.edges[i] = new Edge(this, vertices[i]);
else {
this.edges[i].startNode = this;
this.edges[i].endNode = vertices[i];
}
vertices[i].edges.push(this.edges[i]);
vertices[i].edges.last().startNode = this;
vertices[i].edges.last().endNode = vertices[i];
}
};
this.getVertexInEdge = function (index) {
var edge = this.edges[index || 0];
return edge.startNode.equals(this)? edge.endNode: edge.startNode;
};
this.getConnectedVertices = function () {
var list = [];
for (var i = 0; i < this.edges.length; i++) list.push(this.getVertexInEdge(i));
return list;
};
this.find = function (n, depth) {
if (!depth) depth = 0;
if (this.payload === n) return depth;
var search = this.getConnectedVertices().map(function (node) {
try {
return node.find(n, depth + 1);
} catch (err) {
return [-1, depth];
}
});
var res = search.filter(function (item) { //Filters out the items = [-1, depth]
return !isType(item, "Array");
});
return res.length > 0? res: [-1, depth]
};
this.getNetwork = function () {
var self = this;
var listVertices = function (vertex) {
var list = vertex.getConnectedVertices().remove([self, null], true);
return list.length > 0? list.map(listVertices): list;
};
return this.getConnectedVertices().map(listVertices);
};
this.size = function () {
return this.getNetwork().linearise().length;
};
this.distanceFrom = function (vertex) {
return euclidianDist(this.pos, vertex.pos);
};
this.getNearestVertex = function () {
var self = this;
var smallestEdge = this.edges.filter(function (edge) {
return edge.length === self.edges.map(function (edge) {
return edge.length;
}).min();
});
return smallestEdge.startNode.equals(this)? smallestEdge.endNode: smallestEdge.startNode;
};
return this;
}
/**
* @description Edge that connects two Vertices
* @param {?Vertex} start Starting vertex/node
* @param {?Vertex} end Ending vertex/node
* @param {number} [len=0] Length of the edge.
* @this Edge
* @since 1.1
* @constructor
* @property {?Vertex} Edge.startNode Starting node/vertex of the edge
* @property {?Vertex} Edge.endNode Ending node/vertex of the edge
* @property {number} Edge.length Length of the edge
* @property {function(): string} Edge.toString String representation of the edge
* @property {Function} Edge.draw Draw the edge
* @property {function(): Edge[]} Edge.getSurroundingEdges Get all the surrounding edges
* @property {function(): Edge[]} Edge.getNeighbours Get the neighbour edges
*/
function Edge (start, end, len) {
this.startNode = start || null;
this.endNode = end || null;
this.length = len || ((!isNon(start) && !isNon(end))? euclidianDist(start.pos, end.pos): 0);
this.line = new Line(start? start.pos: [0, 0], end? end.pos: [0, 0]);
this.toString = function () {
return "Edge(startNode=" + this.startNode + ", endNode=" + this.endNode + ", length=" + this.length + ")";
};
this.draw = function () {
this.line.draw();
};
this.getSurroundingEdges = function () {
var self = this, vertexNetwork = this.startNode? this.startNode.getNetwork(): [];
vertexNetwork.append(this.endNode? this.endNode.getNetwork(): []);
return vertexNetwork.map(function (vertex) {
return vertex.edges;
}).linearise().remove(this, true); //Get a 1d array of edges which are different than this one
};
this.getNeighbours = function () {
var self = this, neighbours = this.startNode? this.startNode.getConnectedVertices(): [];
neighbours.append(this.endNode? this.endNode.getConnectedVertices(): []);
return neighbours.map(function (vertex) {
return vertex.edges;
}).linearise().remove(this, true);
}
}
/**
* @description Binary tree node
* @param {*} [pl=0] Payload
* @param {TreeNode} [l] Left child
* @param {TreeNode} [r] Right child
* @this TreeNode
* @returns {TreeNode} Tree node
* @interface
* @constructor
* @since 1.0
* @property {TreeNode} TreeNode.left Left child
* @property {TreeNode} TreeNode.right Right child
* @property {NumberLike} TreeNode.payload Payload
* @property {function(?TreeNode, ?TreeNode)} TreeNode.add Child adder
* @property {function(TreeNode[])} TreeNode.addLeft Left child adder
* @property {function(TreeNode[])} TreeNode.addRight Right child adder
* @property {function(): TreeNode} TreeNode.traverse Tree traversal
* @property {Function} TreeNode.printInOrder Console in-order printing
* @property {Function} TreeNode.printPreOrder Console pre-order printing
* @property {Function} TreeNode.printPostOrder Console post-order printing
* @property {Function} TreeNode.printInOrder Console in-order printing
* @property {Function} TreeNode.inOrder Window in-order printing
* @property {Function} TreeNode.preOrder Window pre-order printing
* @property {Function} TreeNode.postOrder Window post-order printing
* @property {function(): string} TreeNode.getInOrder In-order getter
* @property {function(): string} TreeNode.getPreOrder Pre-order getter
* @property {function(): string} TreeNode.getPostOrder Post-order getter
* @property {function(): boolean} TreeNode.isLeaf Leaf check
* @property {function(*, string): number[]} TreeNode.find Look for a tree-node
* @property {function(*): number[]} TreeNode.dfs Depth First Search
* @property {function(*): number[]} TreeNode.bfs Breath First Search
* @property {Function} TreeNode.sum Sum of the payloads
* @property {Function} TreeNode.min Smallest payload
* @property {Function} TreeNode.max Biggest payload
* @property {function(number): number} TreeNode.nbOfBranches Branches counter
* @property {function(): number} TreeNode.avg Average of the payloads
* @property {function(): string} TreeNode.printBFS Print in the BFS order
* @property {function(): string} TreeNode.toString String representation
* @property {function(boolean): Array} TreeNode.toArray Array representation
* @property {function(NumberLike): number} TreeNode.count Count the number of times there's a particular payload
*/
function TreeNode (pl, l, r) { //Binary tree
this.left = l;
this.right = r;
this.payload = pl || 0;
this.add = function (l, r) {
this.left = l;
this.right = r;
};
this.addLeft = function (child) {
for (var i = 0; i < child.length; i++) {
if (i === 0) this.left = child[0];
else child[i - 1].left = child[i];
}
};
this.addRight = function (childs) {
for (var i in childs) {
if(childs.hasOwnProperty(i)) {
if (i === 0) this.right = childs[0];
else childs[i-1].right = childs[i];
}
}
};
this.traverse = function () {
if (this.left) this.left.traverse();
if (this.right) this.right.traverse();
return this
};
//Console printing
this.printInOrder = function () {
if (this.left) this.left.printInOrder();
Essence.addToPrinter(this.payload + "->");
if (this.right) this.right.printInOrder();
Essence.addToPrinter("\r\n");
};
this.printPreOrder = function () {
Essence.addToPrinter(this.payload + "->");
if (this.left) this.left.printPreOrder();
if (this.right) this.right.printPreOrder();
Essence.addToPrinter("\r\n")
};
this.printPostOrder = function () {
if (this.left) this.left.printPreOrder();
if (this.right) this.right.printPreOrder();
Essence.addToPrinter(this.payload + "->");
Essence.addToPrinter("\r\n")
};
//Window printing
this.inOrder = function (t, s, d, sym) {
if (!t) t = "";
if (!s) s = " ";
if (!d) d = 0;
if (!sym) sym = "|-";
if (this.left) this.left.inOrder(t + s, s, d + 1, sym);
println(t + sym + this.payload + s+" (depth=" + d+")");
if (this.right) this.right.inOrder(t + s, s, d + 1, sym);
};
this.preOrder = function (t, s, d, sym) {
if (!t) t = "";
if (!s) s = " ";
if (!d) d = 0;
if (!sym) sym = "|-";
println(t + sym + this.payload + s+" (depth=" + d+")");
if (this.left) this.left.preOrder(t + s, s, d + 1, sym);
if (this.right) this.right.preOrder(t + s, s, d + 1, sym)
};
this.postOrder = function (t, s, d, sym) {
if (!t) t = "";
if (!s) s = " ";
if (!d) d = 0;
if (!sym) sym = "|-";
if (this.left) this.left.postOrder(t + s, s, d + 1, sym);
if (this.right) this.right.postOrder(t + s, s, d + 1, sym);
println(t + sym + this.payload + s+" (depth=" + d+")")
};
//Getter
this.getInOrder = function (sym) {
if (!sym) sym = "->";
var order = "";
if (this.left) order += this.left.getInOrder(sym);
order += sym + this.payload;
if (this.right) order += this.right.getInOrder(sym);
return order
};
this.getPreOrder = function (sym) {
if (!sym) sym = "->";
var order = "";
order += sym + this.payload;
if (this.left) order += this.left.getPreOrder(sym);
if (this.right) order += this.right.getPreOrder(sym);
return order
};
this.getPostOrder = function (sym) {
if (!sym) sym = "->";
var order = "";
if (this.left) order += this.left.getPostOrder(sym);
if (this.right) order += this.right.getPostOrder(sym);
return order + sym + this.payload
};
this.isLeaf = function () { //Is it an end of branch ?
return !this.left && !this.right
};
this.find = function (n, method) {
return (method.normal() === "bfs")? this.bfs(n): this.dfs(n)
};
this.dfs = function (n) { //Depth First Search
var d = 0, td = 0; //Depth, total depth
var stack = [];
stack.push(this);
while (!stack.equals([])) {
d = 0;
var cur = stack.pop();
try {
if (cur.payload === n) return [d, td]
} catch (e) {
return [-1, td]
}
if (cur.left) stack.push(cur.left);
if (cur.right) stack.push(cur.right);
d++;
td++;
}
};
this.bfs = function (n) { //Breadth First Search
var b = 0, tb = 0; //Breadth, total breadth
var queue = [];
queue.unshift(this); //Add as the end
while (!queue.equals([])) {
b = 0;
var cur = queue.pop(); //Get the first element of the queue
try {
if (cur.payload === n) return [b, tb]
} catch (err) {
return [-1, tb]
}
if (cur.left) queue.unshift(cur.left);
if (cur.right) queue.unshift(cur.right);
b++;
tb++;
}
};
this.sum = function () {
var s = this.payload;
if (this.left) s += this.left.sum();
if (this.right) s += this.right.sum();
return s
};
this.min = function () {
var m = this.payload;
if (this.left) m = Math.min(m, this.left.min());
if (this.right) m = Math.min(m, this.right.min());
return m
};
this.max = function () {
var m = this.payload;
if (this.left) m = Math.max(m, this.left.max());
if (this.right) m = Math.max(m, this.right.max());
return m
};
this.nbOfBranches = function (n) {
if (!n) n = 0;
if (this.left) n = this.left.nbOfBranches(n + 1);
if (this.right) n = this.right.nbOfBranches(n + 1);
return n
};
this.avg = function () {
return this.sum() / this.nbOfBranches()
};
this.printBFS = function (sym) {
if (!sym) sym = "->";
var queue = [], res = "";
queue.unshift(this); //Add as the end
while (!queue.equals([])) {
var cur = queue.pop(); //Get the first element of the queue
res += cur + sym;
try {
if (cur.left) queue.unshift(cur.left);
if (cur.right) queue.unshift(cur.right);
} catch (err) {
Essence.say(err + " caused " + this + ".printBFS(" + sym + ") to go wrong", "erro");
}
}
return res
};
this.toString = function () {
/* Essence.txt2print = "";
this.printInOrder();
return "Tree(" + Essence.txt2print + ")" */
var str = "TreeNode(payload = " + this.payload + ", ";
if (this.left) str += "left = " + this.left.toString();
if (this.right) str += "right = " + this.right.toString();
return str.substring(0, str.length) + ")"
};
this.toArray = function (singly) {
var arr = [];
if (this.left) singly? arr.push(this.left.toArray().toString().split(",")): arr.push(this.left.toArray());
arr.push(this.payload);
if (this.right) singly? arr.push(this.right.toArray().toString().split(",")): arr.push(this.right.toArray());
return singly? arr.toString().split(","): arr
};
this.count = function (n) {
return this.getInOrder().countWord(n, "->");
};
return this;
}
NTreeNode.inheritsFrom(TreeNode);
/**
* @description N-ary tree node
* @see module:DataStruct~TreeNode
* @param {*} pl Payload
* @param {TreeNode[]} [ch=[]] Child
* @returns {NTreeNode} NTreeNode
* @this NTreeNode
* @constructor
* @since 1.0
* @property {NTreeNode[]} NTreeNode.child Child
* @property {NumberLike} NTreeNode.payload Payload
* @property {function(NTreeNode)} NTreeNode.add Child adder
* @property {function(NTreeNode)} NTreeNode.remove Child remove
* @property {function(): NTreeNode} NTreeNode.traverse Tree traversal
* @property {Function} NTreeNode.printInOrder Console in-order printing
* @property {Function} NTreeNode.printPreOrder Console pre-order printing
* @property {Function} NTreeNode.printPostOrder Console post-order printing
* @property {Function} NTreeNode.printInOrder Console in-order printing
* @property {function(number, string, number, string)} NTreeNode.inOrder Window in-order printing
* @property {function(number, string, number, string)} NTreeNode.preOrder Window pre-order printing
* @property {function(number, string, number, string)} NTreeNode.postOrder Window post-order printing
* @property {function(): string} NTreeNode.getOrder ??-order getter
* @property {function(): boolean} NTreeNode.isLeaf Leaf check
* @property {function(*, string): Nums} NTreeNode.find Look for a tree-node
* @property {function(...number): Nums} NTreeNode.dfs Depth First Search
* @property {function(...number): Nums} NTreeNode.bfs Breath First Search
* @property {function(): number} NTreeNode.sum Sum of the payloads
* @property {function(): number} NTreeNode.min Smallest payload
* @property {function(): number} NTreeNode.max Biggest payload
* @property {function(number): number} NTreeNode.nbOfBranches Branches counter
* @property {function(): number} NTreeNode.avg Average of the payloads
* @property {function(string)} NTreeNode.printBFS Print in the BFS order
* @property {function(): string} NTreeNode.toString String representation
* @property {function(): Array} NTreeNode.toArray Array representation
* @property {function(number): NTreeNode} NTreeNode.getChild Child getter
* @property {function(string, boolean): ?string} NTreeNode.see See the tree for that particular node
* @property {function(*): number} NTreeNode.count Count the number of times there's a particular payload
*/
function NTreeNode (pl, ch) {
this.payload = pl || 0;
this.child = ch || [];
this.add = function (c) {
this.child.push(c);
};
this.remove = function (c) {
this.child.remove(c);
};
this.traverse = function () {
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) c.traverse();
}
return this
};
//Console printing
this.printInOrder = function () {
for (var i = 0; i < this.child - 1; i++) {
this.child[i].printInOrder();
Essence.addToPrinter(this.payload + "->");
this.child[i + 1].printInOrder();
Essence.addToPrinter("\r\n");
}
Essence.addToPrinter("\b");
};
this.printPreOrder = function () {
for (var i = 0; i < this.child - 1; i++) {
Essence.addToPrinter(this.payload + "->");
this.child[i].printInOrder();
this.child[i + 1].printInOrder();
Essence.addToPrinter("\r\n");
}
Essence.addToPrinter("\b");
};
this.printPostOrder = function () {
for (var i = 0; i < this.child - 1; i++) {
this.child[i].printInOrder();
this.child[i + 1].printInOrder();
Essence.addToPrinter(this.payload + "->");
Essence.addToPrinter("\r\n");
}
Essence.addToPrinter("\b");
};
//Window printing
this.inOrder = function (t, s, d, sym) {
if (!t) t = "";
if (!s) s = " ";
if (!d) d = 0;
if (!sym) sym = "|-";
for (var i = 0; i < this.child; i++) {
this.child[i].inOrder(t + s, s, d + 1, sym);
println(t + sym + this.payload + s + " (depth=" + d + ")");
this.child[i].inOrder(t + s, s, d + 1, sym);
}
};
this.preOrder = function (t, s, d, sym) {
if (!t) t = "";
if (!s) s = " ";
if (!d) d = 0;
if (!sym) sym = "|-";
println(t + sym + this.payload + s + " (depth=" + d + ")");
for (var i = 0; i < this.child - 1; i++) {
console.log("this.child[i]=", this.child[i]);
this.child[i].preOrder(t + s, s, d + 1, sym);
}
};
this.postOrder = function (t, s, d, sym) {
if (!t) t = "";
if (!s) s = " ";
if (!d) d = 0;
if (!sym) sym = "|-";
for (var i = 0; i < this.child; i++) {
this.child[i].postOrder(t + s, s, d + 1, sym);
}
println(t + sym + this.payload + s + " (depth=" + d+")");
};
//Getter
this.getOrder = function (sym) {
if (!sym) sym = "->";
//var self = this;
var getPayloads = function (node) {
return node.isLeaf()? node.payload: node.payload + sym + node.getOrder(sym);
};
return this.payload + sym + this.child.map(getPayloads).join(sym);
};
this.isLeaf = function () {
return this.child.length === 0;
};
this.find = function (n, method) {
return (method && method.toLowerCase() === "bfs")? this.bfs(n): this.dfs(n)
};
this.dfs = function (n, d, td) { //Depth First Search
if (!d) d = 0; //Depth
if (!td) td = 0; //Total depth
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) {
if (!isType(c, "NTreeNode")) throw new TypeError("The child '" + c + "' is not a NTreeNode");
c.dfs(n, d + 1, td++);
}
}
return [-1, td]
};
this.bfs = function (n, b, tb) { //Breadth First Search
if (!b) b = 0; //Breadth
if (!tb) tb = 0; //Total breadth
var queue = [];
queue.unshift(this); //Add as the end
while (!queue.equals([])) {
b = 0;
var cur = new NTreeNode(queue.pop()); //Get the first element of the queue
if (cur.payload === n) return [b, tb];
if (cur.left) queue.unshift(cur.left);
if (cur.right) queue.unshift(cur.right);
b++;
tb++;
}
return [-1, tb]
};
this.sum = function () {
var s = this.payload;
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) s += c.payload;
}
return s
};
this.min = function () {
var m = this.payload;
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) m = Math.min(m, c.payload);
}
return m
};
this.max = function () {
var m = this.payload;
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) m = Math.max(m, c.payload);
}
return m
};
this.nbOfBranches = function (n) {
if (!n) n = 0;
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) n = c.nbOfBranches(n + 1);
}
return n
};
this.avg = function () {
return this.sum() / this.nbOfBranches()
};
this.printBFS = function (t) {
var queue = [this], tab = t || "-"; //Better and easier than a Queue/QueueList
while (!queue.isEmpty()) {
var cur = new NTreeNode(queue.pop()); //Get the first element of the queue
println(tab + ">" + cur.payload);
tab += "-";
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) queue.unshift(c);
}
}
};
this.toString = function () {
var str = "NTreeNode(payload=" + this.payload + ", child=[";
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) str += this.child[c].toString() + ", ";
}
return (str.substring(0, str.length) + "])").replace(", ]", "]");
};
this.toArray = function (singly) {
var arr = [];
arr.push(this.payload);
for (var c in this.child) {
if (this.child.hasOwnProperty(c)) singly? arr.push(c.toArray().toString().split(",")): arr.push(c.toArray());
}
return singly? arr.toString().split(","): arr
};
this.getChild = function (pos) {
return this.child[pos];
};
this.see = function (symbol, console) {
traverseTree(this, symbol);
Buffer.show(console, !console, true);
var tree = Buffer.log;
Buffer.clear();
return tree;
};
this.count = function (n) {
return this.getOrder().countWord(n, "->");
};
return this;
}
/**
* @description Traverse a (sub)tree starting from a particular node.
* @param {Node} node Node
* @param {string} [symbol="--"] Symbol/string/character to denote a branch
* @param {string} [start="|"] Starting symbol/string/character to denote the head of a branch
* @param {number} [indent=0] Indentation preceding a branch
* @return {string} Current buffer (assuming it's only containing what this function added to it).
* @func
* @since 1.1
*/
function traverseTree (node, symbol, start, indent) {
if (!indent) indent = 0;
if (!start) start = "|";
Buffer.add(" ".repeat(indent) + start + (symbol || "--") + node.payload);
indent++;
for (var i = 0; i < node.child.length; i++) {
traverseTree(node.getChild(i), symbol, start, indent);
}
return Buffer.log;
}
/**
* @description Mathematical set.<br />
* It's depreciated in the next version (in favour of ES6) and will have the following methods instead:
* add(*), has(*), delete(*), size()->size, values(), clear()
* @param {Array} [arr=[]] Array or element
* @returns {Set} Set
* @constructor
* @this Set
* @since 1.0
* @property {number[]} Set.value Values
* @property {function(): number} Set.size Size of the set
* @property {function(*)} Set.add Add an item to the set
* @property {function(*)} Set.remove Remove an item from the set
* @property {function(number)} Set.clear Clear the set or an item of it
* @property {function(): boolean} Set.isEmpty Check the emptiness of the set
* @property {Function} Set.contains Check if the set contains an item (or more)
* @property {function(Set): boolean} Set.equals Check if two sets are identical
* @property {function(Set): boolean} Set.isSame Check if two sets contains the same values
* @property {function(): string} Set.toString String representation
* @property {function(...number): Array} Set.subset Subset of the set
* @property {function(number): *} Set.get Get an item of the set
* @property {function(*): number} Set.indexOf Index of an item in the set
* @property {function(number, *)} Set.set Set an item's value
* @property {function(): *} Set.first Get the first item of the set
* @property {function(): *} Set.last Get the last item of the set
* @property {function(...number): ?number} Set.min Smallest item of the set
* @property {function(...number): ?number} Set.max Biggest item of the set
* @property {function(): ?number} Set.median Median item of the set
* @property {function(function(*))} Set.forEach Act on each items of the set
*/
function Set (arr) {
this.value = (isType(arr, "Array")? rmDuplicates(arr): [arr]) || [];
this.size = function () {
return this.value.length
};
this.add = function (item) {
if (isType(item, "Array")) {
for (var i = 0; i < item.length; i++) this.add(item[i]);
}
if (this.value.indexOf(item) === -1) this.value.push(item)
};
this.remove = function (item) {
if (this.value.has(item)) {
if (isType(item, "Array")) {
for(var i = 0; i < item.length; i++) this.remove();
} else this.value = this.value.remove()
}
};
this.clear = function (index) {
index? this.value = this.value.remove(): this.value = []
};
this.isEmpty = function () {
return this.value.length === 0
};
this.contains = function (item) {
if (isType(item, "Array")) {
var c = true;
for (var i = 0; i < item.length; i++) {
if (!c) return false; //Reduce the cost of the operation by not doing any unnecessary work
c = c && this.contains(item[i]);
}
return c
} else return this.value.has(item)
};
this.equals = function (s) {
return this.value.toString() === s.value.toString()
};
this.isSame = function (s) { //Check if both sets have the same elements but not necessarily in the same order
if (this.equals(s)) return true;
var same = true;
for (var i = 0; i < s.size(); i++) {
if (!same) return false;
same = same && this.contains(s.value[i]);
}
return same
};
this.toString = function () {
return "Set(" + this.value.toString() + ")"
};
this.subset = function (s, e) {
return this.value.slice(s, e + 1)
};
this.get = function (i) {
return this.value[i]
};
this.indexOf = function (val) {
return this.value.indexOf(val);
};
this.set = function (i, val) {
this.value[i] = val;
};
this.first = function () {
return this.value[0]
};
this.last = function () {
return this.value.last()
};
this.min = function (s, e) {
return this.value.min(s, e)
};
this.max = function (s, e) {
return this.value.max(s, e)
};
this.median = function () {
return this.value.median()
};
this.forEach = function (act) {
for (var i = 0; i < this.size(); i++) act(this.get(i));
};
return this;
}
SortedSet.inheritsFrom(Set);
/**
* @description Sorted mathematical set
* @this SortedSet
* @see module:DataStruct~Set
* @param {Array} arr Array
* @returns {SortedSet} Sorted set
* @constructor
* @inheritdoc
* @since 1.0
* @property {number[]} SortedSet.value Values
* @property {function(*)} SortedSet.add Add an item to the set and sort it
* @property {function(): string} SortedSet.toString String representation
*/
function SortedSet (arr) {
this.value = Copy(arr).quickSort() || [];
this.add = function (item) {
isType(item, "Array")? this.value.multiPlace(item): this.value.place(item);
this.value = rmDuplicates(this.value);
};
this.toString = function () {
return "SortedSet(" + this.value.toString() + ")"
};
return this;
}
/**
* @description Stack
* @param {Array|*} [arr] Array