TheAlgorithms-Ruby/data_structures/disjoint_sets/disjoint_sets.rb

48 lines
919 B
Ruby
Raw Normal View History

2021-10-12 09:21:38 +02:00
class Node
2021-11-02 07:45:20 +01:00
attr_accessor :data, :parent, :rank, :parent, :rank
def initialize(data)
@data = data
@parent = self
@rank = 0
end
2021-10-12 09:21:38 +02:00
end
2021-10-12 09:18:41 +02:00
class DisjointSets
2021-11-02 07:45:20 +01:00
def make_set(d)
Node.new(d)
end
2021-10-12 09:18:41 +02:00
2021-11-02 07:45:20 +01:00
def find_set(x)
raise ArgumentError unless x.class <= Node
2021-10-12 09:18:41 +02:00
2021-11-02 07:45:20 +01:00
x.parent = (find_set(x.parent)) unless x.parent == x
x.parent
end
def union_set(x, y)
px = find_set(x)
py = find_set(y)
return if px == py
if px.rank > py.rank
py.parent = px
elsif py.rank > px.rank
px.parent = py
else
px.parent = py
py.rank += 1
end
end
2021-10-12 09:18:41 +02:00
end
ds = DisjointSets.new
one = ds.make_set(1)
two = ds.make_set(2)
three = ds.make_set(3)
ds.union_set(one, two)
puts ds.find_set(one) == ds.find_set(two) # should be true
ds.union_set(one, three)
puts ds.find_set(two) == ds.find_set(three) # should be true
2021-11-02 07:45:20 +01:00
puts one.rank + two.rank + three.rank == 1 # should be true