Created
July 14, 2015 19:59
-
-
Save rob-murray/b39c6445b756dbde8662 to your computer and use it in GitHub Desktop.
Weighted Quick Union & Quick Find Algorithm in Ruby http://www.leighhalliday.com/weighted-quick-union-find-algorithm-in-ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UnionFind | |
attr_accessor :nodes, :sizes | |
def initialize(num) | |
self.nodes = [] | |
self.sizes = [] | |
num.times do |n| | |
self.nodes[n] = n | |
self.sizes[n] = 1 | |
end | |
end | |
def root(i) | |
# Loop up the chain until reaching root | |
while nodes[i] != i do | |
# path compression for future lookups | |
nodes[i] = nodes[nodes[i]] | |
i = nodes[i] | |
end | |
i | |
end | |
def union(i, j) | |
rooti = root i | |
rootj = root j | |
# already connected | |
return if rooti == rootj | |
# root smaller to root of larger | |
if sizes[i] < sizes[j] | |
nodes[rooti] = rootj | |
sizes[rootj] += sizes[rooti] | |
else | |
nodes[rootj] = rooti | |
sizes[rooti] += sizes[rootj] | |
end | |
end | |
def connected?(i, j) | |
root(i) == root(j) | |
end | |
end | |
__END__ | |
u = UnionFind.new(10) | |
p u.nodes | |
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
p u.connected?(1, 4) | |
# false | |
u.union(1,2) | |
u.union(2,3) | |
u.union(3,4) | |
p u.nodes | |
# [0, 1, 1, 1, 1, 5, 6, 7, 8, 9] | |
p u.connected?(1,4) | |
# true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment