How to generate a random number in Elixir?

RandomIntegerElixir

Random Problem Overview


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?

Random Solutions


Solution 1 - Random

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 - Random

&Enum.random/1

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

you can send list as argument too

Solution 3 - Random

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergio TapiaView Question on Stackoverflow
Solution 1 - RandomSergio TapiaView Answer on Stackoverflow
Solution 2 - RandomMichael KaravaevView Answer on Stackoverflow
Solution 3 - RandomKenny EvittView Answer on Stackoverflow