Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random number in Elixir?

I need to generate a random number. I found the Enum.random/1 function, but it expects an enumerable such as a list or range of numbers.

Is that the only way to get a random number?

like image 210
Sergio Tapia Avatar asked Aug 04 '16 21:08

Sergio Tapia


3 Answers

You can call Erlang's rand module from Elixir code seamlessly.

random_number = :rand.uniform(n)

Will give a random number from 1 <= x <= n

like image 99
Sergio Tapia Avatar answered Oct 30 '22 15:10

Sergio Tapia


&Enum.random/1

Enum.random(0..n) will generate 0 to n randomly

you can send list as argument too

like image 74
Michael Karavaev Avatar answered Oct 30 '22 14:10

Michael Karavaev


As perhaps this other answer implies, you can use Enum.random/1 but you don't in fact need to pass it "a list of numbers" (as the question, as originally written) assumed.

As a commenter on that other answer pointed out, the docs for Enum.random/1 state:

If a range is passed into the function, this function will pick a random value between the range limits, without traversing the whole range (thus executing in constant time and constant memory).

Thus these should be (at least roughly) equivalent:

:rand.uniform(n)
1..n |> Enum.random()

Depending on why exactly you want a 'random' number, you might be able to use System.unique_integer/1 as well. The following "returns an integer that is unique in the current runtime instance":

System.unique_integer()

A unique positive integer (which could be useful for generating 'random names'):

System.unique_integer([:positive])

Unique monotonically increasing integers:

System.unique_integer([:monotonic])
like image 8
Kenny Evitt Avatar answered Oct 30 '22 15:10

Kenny Evitt