Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Last active August 29, 2015 14:14
Show Gist options
  • Save joshuakfarrar/42cc6f939ec3d9f0ff21 to your computer and use it in GitHub Desktop.
Save joshuakfarrar/42cc6f939ec3d9f0ff21 to your computer and use it in GitHub Desktop.
Princeton Algorithms - Week One - Quick Find
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