Last active
August 29, 2015 14:14
-
-
Save joshuakfarrar/7c7b616339bfcdfa913e to your computer and use it in GitHub Desktop.
Princeton Algorithms - Week One - Weighted Quick Union
This file contains hidden or 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 WeightedQuickUnion | |
attr_accessor :id | |
def initialize(n) | |
@id = Array.new(n) { |e| e = e } | |
@size = Array.new(n) { |e| e = 1 } | |
end | |
def connect(a, b) | |
c = parent_of(a) | |
d = parent_of(b) | |
return if c == d | |
if (@size[c] < @size[d]) | |
@id[c] = d | |
@size[d] += @size[c] | |
else | |
@id[d] = c | |
@size[c] += @size[d] | |
end | |
end | |
def connected?(a, b) | |
parent_of(a) === parent_of(b) | |
end | |
private | |
def parent_of(n) | |
parent = n | |
while parent != @id[parent] do | |
# @id[parent] = @id[@id[parent]] # path compression (optimization) | |
parent = @id[parent] | |
end | |
parent | |
end | |
end | |
wqu = WeightedQuickUnion.new(10) | |
wqu.connect(4, 3) | |
wqu.connect(3, 2) | |
wqu.connect(2, 1) | |
wqu.connect(1, 8) | |
puts wqu.id.inspect | |
puts wqu.connected?(4, 8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment