File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
06_breadth-first_search/ruby Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ def person_is_seller ( name )
2
+ name [ -1 ] == "m"
3
+ end
4
+
5
+ @graph = { }
6
+
7
+ # %w(string1 string2 ...) is a shorter way to define arrays of strings
8
+ @graph [ "you" ] = %w( alice bob claire )
9
+ @graph [ "bob" ] = %w( anuj peggy )
10
+ @graph [ "alice" ] = %w( peggy )
11
+ @graph [ "claire" ] = %w( thom jonny )
12
+ @graph [ "anuj" ] = [ ]
13
+ @graph [ "peggy" ] = [ ]
14
+ @graph [ "thom" ] = [ ]
15
+ @graph [ "jonny" ] = [ ]
16
+
17
+ def search ( name )
18
+ search_queue = [ ]
19
+ search_queue += @graph [ name ]
20
+ # This array is how you keep track of which people you've searched before.
21
+ searched = [ ]
22
+
23
+ until search_queue . empty?
24
+ person = search_queue . shift
25
+ # Only search this person if you haven't already searched them.
26
+ next if searched . member? ( person )
27
+ if person_is_seller ( person )
28
+ puts "#{ person } is a mango seller!"
29
+ return true
30
+ else
31
+ search_queue += @graph [ person ]
32
+ # Marks this person as searched
33
+ searched . push ( person )
34
+ end
35
+ end
36
+
37
+ false
38
+ end
39
+
40
+ search ( "you" )
You can’t perform that action at this time.
0 commit comments