forked from loganfechner/ap-performance-task
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunionfind.lua
53 lines (41 loc) · 956 Bytes
/
unionfind.lua
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
local UnionFind = {}
function UnionFind:initialize()
self.SetMap = {}
self.sets = {}
end
function UnionFind.makeSet(value)
local set = {}
set.value = value
set.rank = 0
set.parent = set
UnionFind.SetMap[set] = set
return set
end
function UnionFind.findSet(x)
local parent = x
if parent ~= parent.parent then
parent = UnionFind.findSet(parent.parent)
end
return parent
end
--little helper function for getting the set associated with a given point (vertex)
function UnionFind.getSetFromValue(t, value)
for i = 1, #t do
local v = t[i]
if v == value then
return UnionFind.sets[i]
end
end
end
function UnionFind.union(x, y)
local xRoot = UnionFind.findSet(x)
local yRoot = UnionFind.findSet(y)
if xRoot.value == yRoot.value then return end
if xRoot.rank >= yRoot.rank then
if xRoot.rank == yRoot.rank then xRoot.rank = xRoot.rank + 1 end
yRoot.parent = xRoot
else
xRoot.parent = yRoot
end
end
return UnionFind