ruby - recursively finding friends of friends etc -


i trying find names of of friends, names of of friends, out 4 degrees. need track degree friend me (eg direct friend=degree 1) have code, dont understand how solve problem. advice great.

def getfriendnames(name)     ret=array.new     #lots of code here, doesnt change problem      return ret #returns unique list of friends names end   arr=array.new friends=getfriendnames("me") arr.push(friends) #element1 of array arr friends of me. element 2 should friends of friends of me friends.each{|x|     getfriendname(x) #this returns array of friends }    

this may not efficient solution, simple , direct 1 came mind.

friends = hash.new to_process = ["me"]  (0..4).each { |distance|     processing = to_process     to_process = []      processing.each { |person|         if !friends.has_key?(person)             friends[person] = distance             to_process.concat(getfriendnames(person))         end     } } 

if want keep track of "source" friend instead write:

friends = hash.new to_process = ["me"]  4.times {     processing = to_process     to_process = []      processing.each { |source|         getfriendnames(source).each { |person|             if !friends.has_key?(person)                 friends[person] = source                 to_process.push(person)             end         }     } } 

note it's possible in reality have more 1 "source" friend. example if have a , b friends , both of them have friend c, c's source friend either a or b.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -