-
Notifications
You must be signed in to change notification settings - Fork 0
/
beta.txt
53 lines (42 loc) · 1.11 KB
/
beta.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
defmodule Beta do
def init_state(name,master) do
%{
name: name,
parent: nil,
childs:[],
neighbors: [],
replies: 0,
root: false,
master_id: master,
}
end
def run(state) do
my_pid = self
state = receive do
{:add_neighbors, neighbors} ->
state = %{state | neighbors: neighbors}
state = %{state | replies: length(neighbors) - 1}
{:start,:spanning_tree} ->
state = %{state | root: true}
Enum.each(state.neighbors, fn dest -> send dest,{:search,my_pid} end)
state
{:search,origin} ->
if state.parent == nil do
state = %{state | parent: origin}
state = %{state | neighbors: state.neighbors}
send origin,{:reply,:parent_of, my_pid}
Enum.each(state.neighbors -- origin, fn dest -> send dest,{:search,my_pid} end)
else
send origin, {:reply,:rejected, my_pid}
end
state
{:reply, value, origin} ->
if value == :parent_of do
state = %{state | childs: state.childs ++ [origin]}
end
state = %{state | replies: state.replies - 1}
if state.replies == 0, do: send master,{:complete_tree}
state
end
end
end