1

I'm writing a code in Erlang which suppose to generate a random number for a random amount of time and add each number to a list. I managed a function which can generate random numbers and i kinda managed a method for adding it to a list,but my main problem is restricting the number of iterations of the function. I like the function to produce several numbers and add them to the list and then kill that process or something like that.
Here is my code so far:

generator(L1)->
random:seed(now()),
A = random:uniform(100),
L2 = lists:append(L1,A),
generator(L2),

producer(B,L) ->

receive
  {last_element} ->
   consumer ! {lists:droplast(B)}
end

consumer()->
 timer:send_after(random:uniform(1000),producer,{last_element,self()}),
receive
  {Answer, Producer_PID} ->
  io:format("the last item is:~w~n",[Answer])
end,
consumer().



start() ->

register(consumer,spawn(lis,consumer,[])),
register(producer,spawn(lis,producer,[])),
register(generator,spawn(lis,generator,[random:uniform(10)])).

I know it's a little bit sloppy and incomplete but that's not the case.

pouyan021
  • 177
  • 1
  • 4
  • 19

2 Answers2

1

First, you should use rand to generate random numbers instead of random, it is an improved module.

In addition, when using rand:uniform/1 you won't need to change the seed every time you run your program. From erlang documentation:

If a process calls uniform/0 or uniform/1 without setting a seed first, seed/1 is called automatically with the default algorithm and creates a non-constant seed.

Finally, in order to create a list of random numbers, take a look at How to create a list of 1000 random number in erlang.

If I conclude all this, you can just do:

[rand:uniform(100) || _ <- lists:seq(1, 1000)].
Community
  • 1
  • 1
A. Sarid
  • 3,916
  • 2
  • 31
  • 56
1

There have some issue in your code:

  1. timer:send_after(random:uniform(1000),producer,{last_element,self()}),, you send {last_element,self()} to producer process, but in producer, you just receive {last_element}, these messages are not matched.

you can change

producer(B,L) ->
    receive
        {last_element} ->
            consumer ! {lists:droplast(B)}
    end.

to

producer(B,L) ->
    receive
         {last_element, FromPid} ->
             FromPid! {lists:droplast(B)}
    end.

the same reason for consumer ! {lists:droplast(B)} and {Answer, Producer_PID} ->.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67