-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.erl
executable file
·61 lines (45 loc) · 1.77 KB
/
main.erl
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
54
55
56
57
58
59
60
61
% #!/usr/bin/env escript
-module (main).
-export ([init/1]).
-include_lib("eqc/include/eqc.hrl").
% ----------------------------------------------------------- %
% String helper functions %
% ----------------------------------------------------------- %
strip(S) -> re:replace(S, "\n", "", [global,{return,list}]).
split(S, Sep) -> string:tokens(S, Sep).
to_i(S) -> {I, _} = string:to_integer(S), I.
to_i_list(S) -> lists:map(fun (X) -> to_i(X) end, split(strip(S), " ")).
get_all_lines(Device, Acc) ->
case io:get_line(Device, "") of
eof -> lists:reverse(Acc);
Line -> get_all_lines(Device, [Line|Acc])
end.
% ----------------------------------------------------------- %
% Graph initializer functions %
% ----------------------------------------------------------- %
newGraph(N, Edges) ->
G = createGraph(N, []),
addEdges(G, Edges),
G.
createGraph(0, Acc) -> Acc;
createGraph(N, Acc) ->
createGraph(N - 1, [spawn(node, node, [[],0])|Acc]).
addEdges(_, []) -> ok;
addEdges(Graph, [[X, Y, Weight]|Es]) ->
Node_x = lists:nth(X, Graph),
Node_y = lists:nth(Y, Graph),
% Tell each node that they are neighbors
Node_x ! {add, Node_y, Weight},
Node_y ! {add, Node_x, Weight},
addEdges(Graph, Es).
% ----------------------------------------------------------- %
% main program %
% ----------------------------------------------------------- %
init(String) ->
{ok, Device} = file:open(String, [read]),
Content = get_all_lines(Device, []),
[[N|_]|Edges] = lists:map(fun (Ss) -> to_i_list(Ss) end, Content),
G = newGraph(N, Edges),
M = spawn(master, master, [N,G]),
io:format("Graph: ~p~n", [G]),
M.