language: Erlang (erl-5.7.3)
date: 169 days 15 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
40
41
42
-module(prog).
-compile(export_all).
-define(R, 503).
 
%% main -program start point
main() -> 
        io:format("Main at: ~p~n",[self()]),
        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,
        erlang:halt().
 
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 when is_pid(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 -> 
                        io:format("Received: ~p at ID: ~p Pid: ~p~n",[X,Id,self()]),
                        OutPid ! (X - 1),
                        norm_mode(Id,OutPid,Main)
        end.
  • upload with new input
  • result: Success     time: 0.18s    memory: 9472 kB     returned value: 0

    10
    Main at: <0.1.0>
    Received: 10 at ID: 1 Pid: <0.29.0>
    Received: 9 at ID: 2 Pid: <0.30.0>
    Received: 8 at ID: 3 Pid: <0.31.0>
    Received: 7 at ID: 4 Pid: <0.32.0>
    Received: 6 at ID: 5 Pid: <0.33.0>
    Received: 5 at ID: 6 Pid: <0.34.0>
    Received: 4 at ID: 7 Pid: <0.35.0>
    Received: 3 at ID: 8 Pid: <0.36.0>
    Received: 2 at ID: 9 Pid: <0.37.0>
    10