Last active
August 29, 2015 14:14
-
-
Save joshuakfarrar/42cc6f939ec3d9f0ff21 to your computer and use it in GitHub Desktop.
Princeton Algorithms - Week One - Quick Find
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 QuickFind | |
attr_accessor :id | |
def initialize(n) | |
@id = Array.new(n) { |e| e = e } | |
end | |
def connect(a, b) | |
c = @id[a] | |
d = @id[b] | |
@id.each_with_index do |id, i| | |
if id == c | |
@id[i] = d | |
end | |
end | |
end | |
def connected?(a, b) | |
@id[a] === @id[b] | |
end | |
end | |
qf = QuickFind.new(10) | |
puts qf.id.inspect | |
puts qf.connected?(1, 2) | |
qf.connect(1, 2) | |
puts qf.connected?(1, 2) | |
qf.connect(3, 4) | |
qf.connect(4, 5) | |
puts qf.id.inspect | |
puts qf.connected?(3, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment