-
Notifications
You must be signed in to change notification settings - Fork 0
/
unionfind.lua
52 lines (45 loc) · 1.27 KB
/
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
--- UnionFind https://en.wikipedia.org/wiki/Disjoint-set_data_structure
---@class UnionFind
---@private parent table
local UnionFind = require("ji/class")("UnionFind")
function UnionFind:new(...)
local parent = {}
for i = 1, select("#", ...) do
local value = select(i, ...)
parent[value] = value
end
return { parent = parent }
end
--- Adds each of the given values to the set union.
function UnionFind:add(...)
for i = 1, select("#", ...) do
local value = select(i, ...)
if self.parent[value] == nil then
self.parent[value] = value
end
end
end
function UnionFind:find(x)
if not self.parent[x] then return nil end
while self.parent[x] ~= x do
x, self.parent[x] = self.parent[x], self.parent[self.parent[x]]
end
return x
end
--- Combines the set containing `x` and the set containing `y`
function UnionFind:union(x, y)
x = self:find(x)
y = self:find(y)
if x == nil or y == nil or x == y then return end
self.parent[x] = y
end
function UnionFind:__len()
local result = 0
for _ in pairs(self.parent) do result = result + 1 end
return result
end
--- Iterates over `value, parent` pairs
function UnionFind:__pairs()
return next, self.parent, nil
end
return UnionFind