|
| 1 | +defmodule BreadthFirstSearch do |
| 2 | + def search(graph, initial_vertex, search_fn) do |
| 3 | + initial_search_queue = list_to_queue(graph[initial_vertex]) |
| 4 | + do_search(initial_search_queue, search_fn, [], graph) |
| 5 | + end |
| 6 | + |
| 7 | + defp do_search(_empty_queue = {[], []}, _, _, _), do: nil |
| 8 | + |
| 9 | + defp do_search(search_queue, search_fn, searched_list, graph) do |
| 10 | + {{:value, value}, rest_queue} = :queue.out(search_queue) |
| 11 | + |
| 12 | + cond do |
| 13 | + value in searched_list -> |
| 14 | + do_search(rest_queue, search_fn, searched_list, graph) |
| 15 | + |
| 16 | + search_fn.(value) -> |
| 17 | + value |
| 18 | + |
| 19 | + true -> |
| 20 | + continue_search(rest_queue, value, search_fn, searched_list, graph) |
| 21 | + end |
| 22 | + end |
| 23 | + |
| 24 | + defp continue_search(search_queue, value, search_fn, searched_list, graph) do |
| 25 | + join_with_search_queue = &:queue.join(search_queue, &1) |
| 26 | + |
| 27 | + updated_search_queue = |
| 28 | + graph[value] |
| 29 | + |> list_to_queue() |
| 30 | + |> join_with_search_queue.() |
| 31 | + |
| 32 | + do_search(updated_search_queue, search_fn, [value | searched_list], graph) |
| 33 | + end |
| 34 | + |
| 35 | + defp list_to_queue(list), do: :queue.from_list(list) |
| 36 | +end |
| 37 | + |
| 38 | +graph = %{ |
| 39 | + "you" => ["alice", "bob", "claire"], |
| 40 | + "bob" => ["anuj", "peggy"], |
| 41 | + "alice" => ["peggy"], |
| 42 | + "claire" => ["thom", "jonny"], |
| 43 | + "anuj" => [], |
| 44 | + "peggy" => [], |
| 45 | + "thom" => [], |
| 46 | + "jonny" => [] |
| 47 | +} |
| 48 | + |
| 49 | +person_is_seller? = &String.ends_with?(&1, "m") |
| 50 | + |
| 51 | +name = BreadthFirstSearch.search(graph, "you", person_is_seller?) |
| 52 | +IO.puts("#{name} is a mango seller!") |
0 commit comments