How to generate a random number in Elixir?

Sergio Tapia picture Sergio Tapia · Aug 4, 2016 · Viewed 36.5k times · Source

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?

Answer

Sergio Tapia picture Sergio Tapia · Aug 5, 2016

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