From da6478b78d6fdb0b878e058cf18e190ebdcb0ee7 Mon Sep 17 00:00:00 2001 From: Leon Rische Date: Thu, 3 Mar 2016 15:53:40 +0100 Subject: [PATCH] code for chapter 6 in ruby --- .../ruby/01_breadth-first_search.rb | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 06_breadth-first_search/ruby/01_breadth-first_search.rb diff --git a/06_breadth-first_search/ruby/01_breadth-first_search.rb b/06_breadth-first_search/ruby/01_breadth-first_search.rb new file mode 100644 index 0000000..cb21b9f --- /dev/null +++ b/06_breadth-first_search/ruby/01_breadth-first_search.rb @@ -0,0 +1,40 @@ +def person_is_seller(name) + name[-1] == "m" +end + +@graph = {} + +# %w(string1 string2 ...) is a shorter way to define arrays of strings +@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"] = [] + +def search(name) + 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.member?(person) + if person_is_seller(person) + puts "#{person} is a mango seller!" + return true + else + search_queue += @graph[person] + # Marks this person as searched + searched.push(person) + end + end + + false +end + +search("you")