-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkruskal.js
93 lines (73 loc) · 2.23 KB
/
kruskal.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
function processData(input) {
// using disjoint union data structure to find if two nodes are in the same set
// create network Sets. At start each node is in set of itself
var netSets = {}
var nodes = parseInt(input.split('\n')[0].split(' ')[0], 10)
for (let i = 1; i <= nodes; i++) {
netSets[i] = new Set().add("" + i)
}
// create network links and weights structure from the input
var graph = input.split('\n').slice(1).map(line => line.split(' ').map((chr, i) => {
if(i == 2) chr = parseInt(chr, 10)
return chr
}))
// merging to disjoint sets into one using quickfind algorithm
var unionSets = function(a, b) {
if(netSets[a] == netSets[b]) { return }
var toMove, toMerge
if(netSets[a].size < netSets[b].size) {
toMove = netSets[a]
toMerge = netSets[b]
} else {
toMove = netSets[b]
toMerge = netSets[a]
}
for (var item of toMove) {
toMerge.add(item)
netSets[item] = toMerge
}
}
// tests if both are in set
var isInSameSet = function(a, b) {
return netSets[a] === netSets[b]
}
// Kruskal's algorithm calls for sorting the graph in order of weighting,
// and a means of sorting if weighting is equal by adding the node values too
// if still equal, it doesn't matter which goes first
var sortedGraph = graph.sort((a, b) => {
if (a[2] < b[2]) return -1
else if(a[2] == b[2]) {
var totalA = a.map(chr => parseInt(chr, 10)).reduce((tot, cur) => tot + cur)
var totalB = b.map(chr => parseInt(chr, 10)).reduce((tot, cur) => tot + cur)
if (totalA <= totalB) return -1
else return 1
}
else return 1
})
// go through the sorted graph. If in same set, ignore, otherwise add the
// weight to total, then merge the sets
var totalWeight = 0
sortedGraph.forEach(line => {
if(isInSameSet(line[0], line[1])) { return }
totalWeight += line[2]
unionSets(line[0], line[1])
})
console.log(totalWeight)
}
var data =`4 6
1 2 5
1 3 3
4 1 6
2 4 7
3 2 4
3 4 5`
processData(data)
var data2 = `4 5
1 2 1
3 2 150
4 3 99
1 4 100
3 1 200`
processData(data2)
var dataset = require('./kruskal-dataset')
processData(dataset) // expect result to be 49950000