Skip to content

Commit 2d8171b

Browse files
committed
added disjoint sets data structure
1 parent af40ff3 commit 2d8171b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
require "./data_structures/disjoint_sets/node.rb"
2+
3+
class DisjointSets
4+
def make_set(d)
5+
Node.new(d)
6+
end
7+
8+
def find_set(x)
9+
raise ArgumentError unless x.class <= Node
10+
x.parent=(find_set(x.parent)) unless x.parent == x
11+
x.parent
12+
end
13+
14+
def union_set(x, y)
15+
px = find_set(x)
16+
py = find_set(y)
17+
return if px == py
18+
if px.rank > py.rank
19+
py.parent = px
20+
elsif py.rank > px.rank
21+
px.parent = py
22+
else
23+
px.parent = py
24+
py.rank += 1
25+
end
26+
end
27+
end
28+
29+
ds = DisjointSets.new
30+
one = ds.make_set(1)
31+
two = ds.make_set(2)
32+
three = ds.make_set(3)
33+
ds.union_set(one, two)
34+
puts ds.find_set(one) == ds.find_set(two) # should be true
35+
ds.union_set(one, three)
36+
puts ds.find_set(two) == ds.find_set(three) # should be true
37+
puts one.rank + two.rank + three.rank == 1 # should be true

data_structures/disjoint_sets/node.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Node
2+
attr_accessor :data, :parent, :rank
3+
def initialize(data)
4+
@data = data
5+
@parent = self
6+
@rank = 0
7+
end
8+
def parent
9+
@parent
10+
end
11+
def parent=(parent)
12+
@parent = parent;
13+
end
14+
def rank
15+
@rank
16+
end
17+
def rank=(rank)
18+
@rank = rank
19+
end
20+
end

0 commit comments

Comments
 (0)