-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickunion.js
54 lines (51 loc) · 1.34 KB
/
quickunion.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
/*jshint esversion: 6 */
var Constructor = function() {
this.id = [];
};
Constructor.prototype = function() {
var root = function(array, i) {
while (array[i] !== i) {
i = array[i];
}
return i;
};
return {
initialize: function(n) {
try {
if (!Number.isInteger(n)) {
throw new Error("Not a number");
}
} catch (error) {
console.error("Error: ", error.message);
}
for (var i = 0; i < n; i += 1) {
this.id[i] = i;
}
},
connected: function(a, b) {
if (root(this.id, a) === root(this.id, b)) {
return true;
}
return false;
},
union: function(a, b) {
let i = root(this.id, a);
let j = root(this.id, b);
if (i > j) {
this.id[j] = i;
} else {
this.id[i] = j;
}
},
commonroot: function(a, b) {
let roota = root(this.id, a);
let rootb = root(this.id, b);
if (roota === rootb) {
return roota;
} else {
console.log("No common root");
}
},
};
}();
module.exports = new Constructor();