language: Erlang (erl-5.7.3)
date: 175 days 16 hours ago
link:
visibility: public
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
-module(prog).
-compile(export_all).
-define(R, 503).
 
%% main -program start point
main() -> 
        case io:fread("","~d") of
                eof -> false;
                {ok,[X]} -> main(X)
        end.
main([Arg]) -> main(list_to_integer(Arg));
main(Arg) when is_integer(Arg) ->
        start(Arg),
        receive
                {done, Id} -> io:format("~p~n",[Id])
        end.
 
start(Num) ->
        FPid = spawn(?MODULE,spawn_mode,[1,self()]),
        FPid ! Num,
        receive
                {getfirst,?R,LPid} -> LPid ! FPid
        end.
 
spawn_mode(Id,Main) when Id == ?R ->
        Main ! {getfirst, Id, self()},
        receive
                OutPid -> norm_mode(Id,OutPid,Main)
        end;
spawn_mode(Id,Main) -> 
        OutPid = spawn(?MODULE,spawn_mode,[Id + 1,Main]),
        norm_mode(Id,OutPid,Main).
norm_mode(Id,OutPid,Main) ->
        receive
                1 -> Main ! {done, Id};
                X -> 
                        OutPid ! (X - 1),
                        norm_mode(Id,OutPid,Main)
        end.