avoid use of global variables; it is more rubyish to represent a graph as a class
This commit is contained in:
@@ -2,35 +2,38 @@ def person_is_seller?(name)
|
|||||||
name[-1] == "m"
|
name[-1] == "m"
|
||||||
end
|
end
|
||||||
|
|
||||||
@graph = {}
|
class Graph < Hash
|
||||||
|
def search(name)
|
||||||
|
search_queue = []
|
||||||
|
search_queue += self[name]
|
||||||
|
# This array is how you keep track of which people you've searched before.
|
||||||
|
searched = {}
|
||||||
|
|
||||||
# %w(string1 string2 ...) is a shorter way to define arrays of strings
|
until search_queue.empty?
|
||||||
@graph["you"] = %w(alice bob claire)
|
pp searched
|
||||||
@graph["bob"] = %w(anuj peggy)
|
person = search_queue.shift
|
||||||
@graph["alice"] = %w(peggy)
|
# Only search this person if you haven't already searched them.
|
||||||
@graph["claire"] = %w(thom jonny)
|
next if searched[person]
|
||||||
@graph["anuj"] = []
|
return person if yield person
|
||||||
@graph["peggy"] = []
|
search_queue += self[person]
|
||||||
@graph["thom"] = []
|
# Marks this person as searched
|
||||||
@graph["jonny"] = []
|
searched[person] = true
|
||||||
|
end
|
||||||
|
|
||||||
def search(name)
|
false
|
||||||
search_queue = []
|
|
||||||
search_queue += @graph[name]
|
|
||||||
# This array is how you keep track of which people you've searched before.
|
|
||||||
searched = {}
|
|
||||||
|
|
||||||
until search_queue.empty?
|
|
||||||
person = search_queue.shift
|
|
||||||
# Only search this person if you haven't already searched them.
|
|
||||||
next if searched[person]
|
|
||||||
return person if yield person
|
|
||||||
search_queue += @graph[person]
|
|
||||||
# Marks this person as searched
|
|
||||||
searched[person] = true
|
|
||||||
end
|
end
|
||||||
|
|
||||||
false
|
|
||||||
end
|
end
|
||||||
|
|
||||||
search("you"){|person| person_is_seller?(person) }.tap{|person| puts "#{person} is a mango seller!" if person}
|
|
||||||
|
# %w(string1 string2 ...) is a shorter way to define arrays of strings
|
||||||
|
graph = Graph.new
|
||||||
|
graph["you"] = %w(alice bob claire)
|
||||||
|
graph["bob"] = %w(anuj peggy)
|
||||||
|
graph["alice"] = %w(peggy)
|
||||||
|
graph["claire"] = %w(thom jonny)
|
||||||
|
graph["anuj"] = []
|
||||||
|
graph["peggy"] = []
|
||||||
|
graph["thom"] = []
|
||||||
|
graph["jonny"] = []
|
||||||
|
|
||||||
|
graph.search("you"){|person| person_is_seller?(person) }.tap{|person| puts "#{person} is a mango seller!" if person}
|
||||||
|
|||||||
Reference in New Issue
Block a user