Skip to content

Instantly share code, notes, and snippets.

@ljsc
Created March 26, 2014 01:26
Show Gist options
  • Save ljsc/9775223 to your computer and use it in GitHub Desktop.
Save ljsc/9775223 to your computer and use it in GitHub Desktop.
Unoptimized Union-Find algorithm in Ruby.
class UnionFind
def initialize(universe)
@data = {}
universe.each do |element|
@data[element] = element
end
end
def find(n)
root = n
while @data[root] != root do
root = @data[root]
end
root
end
def union(a,b)
rootA, rootB = find(a), find(b)
return if rootA == rootB
@data[rootA] = @data[rootB]
end
def equiv?(a,b)
find(a) == find(b)
end
end
describe UnionFind do
describe "#find" do
before(:each) do
@eq = UnionFind.new('a'..'z')
end
it "sends elements to itself when fresh" do
expect(@eq.find('a')).to eq('a')
end
it "sends elements in the same set to one of those elements" do
@eq.union('a', 'e')
expect(@eq.find('a')).to eq('e')
end
it "sends elements in the same set to one of those elements, multiple" do
@eq.union('a', 'e')
@eq.union('i', 'o')
@eq.union('i', 'a')
expect(@eq.find('a')).to eq('e')
end
it "checks whether values are in the same equivilence class" do
# use some soundex classes
@eq.union('a', 'e')
@eq.union('i', 'o')
@eq.union('u', 'y')
@eq.union('h', 'w')
@eq.union('a', 'i')
@eq.union('u', 'h')
@eq.union('a', 'u')
@eq.union('b', 'f')
@eq.union('p', 'v')
@eq.union('b', 'p')
expect(@eq.equiv?('o', 'h')).to be
expect(@eq.equiv?('f', 'p')).to be
expect(@eq.equiv?('h', 'v')).not_to be
end
end
end
@ljsc
Copy link
Author

ljsc commented Mar 26, 2014

Union-find computes represents the quotient set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment