Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Random Element(s) from a List

Tags:

elixir

I'm basically looking for an Elixir equivalent of Ruby's Array#sample. Something that would let me do this:

list = [1,2,3,4,5,6,7]  sample(list) #=> 4  sample(list, 3) #=> [6, 2, 5] 

I didn't find anything in the Elixir List Docs either.

like image 534
Sheharyar Avatar asked Jul 04 '15 12:07

Sheharyar


People also ask

How do you pull a random item from a list in Python?

Use the random. sample() function when you want to choose multiple random items from a list without repetition or duplicates. There is a difference between choice() and choices() . The choices() was added in Python 3.6 to choose n elements from the list randomly, but this function can repeat items.

How do you select multiple random elements in a list in Python?

Use the numpy. random. choice() function to pick multiple random rows from the multidimensional array.

Which function in the random module returns a random element from a list?

choice() function is used to return a random item from a list, tuple, or string.


2 Answers

Updated Answer

As José Valim said in his answer, in Elixir 1.1 and above, you can now use these methods to get random element(s) from a list:

  • Enum.random/1 - For getting single random element
  • Enum.take_random/2 - For getting multiple random elements

Example:

Enum.random(list)                         #=> 4  Enum.take_random(list, 3)                 #=> [3, 9, 1] Enum.take_random(list, 1)                 #=> [7] 

Remember to call :random.seed(:erlang.now) first!


Original Answer

I'm still unable to find a 'proper' and 'magical' way to do this, but this is the best I could come up:

For getting a single random element:

list |> Enum.shuffle |> hd #=> 4 

Note: This gives an exception if the list is empty

For getting multiple random elements:

list |> Enum.shuffle |> Enum.take(3) #=> [7, 1, 5] 
like image 185
Sheharyar Avatar answered Oct 29 '22 11:10

Sheharyar


There is no such function in Elixir 1.0, so you need to implement it yourself as mentioned by the other solutions. However, Enum.random/1 is coming with Elixir v1.1: https://hexdocs.pm/elixir/Enum.html#random/1

like image 38
José Valim Avatar answered Oct 29 '22 10:10

José Valim