File tree Expand file tree Collapse file tree 3 files changed +48
-0
lines changed Expand file tree Collapse file tree 3 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ class QuickUnion
2
+ attr_reader :values , :size
3
+ def initialize ( size )
4
+ @size = size
5
+ @values = Array . new ( @size )
6
+ ( 0 ...@size ) . each do |i |
7
+ @values [ i ] = i
8
+ end
9
+ end
10
+
11
+ def root ( p )
12
+ root = p
13
+ while ( root != @values [ root ] )
14
+ root = @values [ root ]
15
+ end
16
+ root
17
+ end
18
+
19
+ def connected ( p , q )
20
+ return root ( p ) == root ( q )
21
+ end
22
+
23
+ def union ( p , q )
24
+ pr = root ( p )
25
+ qr = root ( q )
26
+ unless ( pr == qr )
27
+ @values [ pr ] = qr
28
+ end
29
+ end
30
+ end
31
+
32
+ qf = QuickUnion . new ( 10 )
33
+ p qf . values
34
+ qf . union ( 4 , 3 )
35
+ p qf . values
36
+ qf . union ( 9 , 8 )
37
+ p qf . values
38
+ qf . union ( 4 , 8 )
39
+ p qf . values
Original file line number Diff line number Diff line change
1
+ require_relative './quick_union'
2
+
3
+ RSpec . describe QuickUnion do
4
+ it "Create array with values assigned to its index" do
5
+ qf = QuickUnion . new ( 10 )
6
+ expect ( qf . size ) . to eq ( 10 )
7
+ expect ( qf . values . size ) . to eq ( 10 )
8
+ end
9
+ end
You can’t perform that action at this time.
0 commit comments