Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
mango_seller_with_comments
class Person
attr_accessor :name, :is_seller, :friends
def initialize
@name = ('a'..'z').to_a.sample(5).join.capitalize!
@is_seller = false
@friends = []
end
end
def make_friends(n)
friends = []
n.times { friends << Person.new}
return friends
end
central_person = Person.new; central_person.name = "Center"
central_person.friends = make_friends(4)
central_person.friends.each { |f| f.friends = make_friends(3) }
seller = central_person.friends.sample.friends.sample
seller.is_seller = true
puts "#{seller.name} now is set to be seller"
def search_seller(center)
search_queue = Queue.new
search_queue << center
searched = []
puts "Search from central node: #{center.name}"
while search_queue
person = search_queue.pop
puts "Checking whether #{person.name} is a seller?"
if person.is_seller
puts "#{person.name} is seller!"
return true
else
unless person.friends.empty? && !searched.include?(person)
pending_firends = person.friends.map { |p| p.name }
puts "#{person.name} is not a seller. Adding #{person.name}'s friends: #{pending_firends} to search queue'"
person.friends.each { |f| search_queue << f}
searched << person
end
end
end
puts "No seller"
return false
end
search_seller(central_person)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment