41 lines
1.7 KiB
Erlang
41 lines
1.7 KiB
Erlang
-module(dec_tree).
|
|
-export([start/0, decision_tree/0]).
|
|
|
|
%%% Interface
|
|
|
|
start() -> Pid = spawn(?MODULE, decision_tree, []), Pid.
|
|
|
|
decision_tree() -> T = create_tree(), decision_tree(T).
|
|
decision_tree(Tree) ->
|
|
io:format("~w~n", [Tree]), %% for debug purposes we always print the Tree
|
|
receive
|
|
{create_node, Node, Edge, Parent} -> NewTree = create_node(Tree, Node, Edge, Parent), decision_tree(NewTree);
|
|
{print} -> decision_tree(Tree); % no need to print the tree, since we already printed before receive...
|
|
{solve} -> io:format("Solution: ~w~n", [solve(Tree)]), decision_tree(Tree)
|
|
end.
|
|
|
|
%%% Create the decision Tree
|
|
|
|
create_tree() -> none.
|
|
|
|
create_node(none, Node, Edge, _) -> {Node, Edge, []}; % 1st node
|
|
create_node({Parent, P_Edge, L}, Node, Edge, Parent) -> {Parent, P_Edge, [{Node, Edge, []}|L]}; % we find the parent node and insert the new node
|
|
create_node({Root, R_Edge, []}, _, _, Parent) -> {Root, R_Edge, []}; % recursion stop when the parent node is not found
|
|
create_node({Root, R_Edge, L}, Node, Edge, Parent) -> {Root, R_Edge, lists:map(fun(N) -> create_node(N, Node, Edge, Parent) end, L)}. % we try to insert the node in all subtrees
|
|
|
|
%%% Solve the decision Tree
|
|
|
|
% Determines the path by choosing the greatest edge
|
|
solve_max([{Edge, Path}]) -> {Edge, Path};
|
|
solve_max([{H_Edge, E_Path}|T]) ->
|
|
{T_max, T_Path} = solve_max(T),
|
|
if
|
|
H_Edge > T_max ->
|
|
{H_Edge, E_Path};
|
|
true -> % works as an 'else' branch
|
|
{T_max, T_Path}
|
|
end.
|
|
|
|
solve(none) -> false; %there is no solition for an empty decision tree
|
|
solve({Node, Edge, []}) -> {Edge,[Node]}; %recursion stop
|
|
solve({Node, Edge, L}) -> {C_Edge, C_Path} = solve_max(lists:map(fun(N) -> solve(N) end, L)), {Edge + C_Edge, [Node|C_Path]}. |