Reputation: 9825
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?
Upvotes: 103
Views: 74565
Reputation: 11
I needed a 6 digit integer with no zeroes so I did this:
Enum.map(0..5, fn _ -> Enum.random(1..9) end) |> Integer.undigits
I wouldn't use this for anything large, but I consider it acceptable for a few digits and infrequent use.
Upvotes: 1
Reputation: 9811
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])
Upvotes: 15
Reputation: 9825
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
Upvotes: 166
Reputation: 1537
&Enum.random/1
Enum.random(0..n)
will generate 0 to n
randomly
you can send list as argument too
Upvotes: 87