如何在长生不老药中产生一个随机数?

我需要生成一个随机数。我找到了 Enum.random/1函数,但它需要一个可枚举数,比如一个列表或一个数字范围。

这是得到随机数的唯一方法吗?

56975 次浏览

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

&Enum.random/1

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

you can send list as argument too

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