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?


Solution 1:

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

Solution 2:

&Enum.random/1

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

you can send list as argument too

Solution 3:

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])