Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pick randomly from an array?

I want to know if there is a much cleaner way of doing this. Basically, I want to pick a random element from an array of variable length. Normally, I would do it like this:

myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ] item = myArray[rand(myarray.length)] 

Is there something that is more readable / simpler to replace the second line? Or is that the best way to do it. I suppose you could do myArray.shuffle.first, but I only saw #shuffle a few minutes ago on SO, I haven't actually used it yet.

like image 339
Paul Hoffer Avatar asked Aug 14 '10 05:08

Paul Hoffer


People also ask

How do you randomize an array?

Write the function shuffle(array) that shuffles (randomly reorders) elements of the array. Multiple runs of shuffle may lead to different orders of elements. For instance: let arr = [1, 2, 3]; shuffle(arr); // arr = [3, 2, 1] shuffle(arr); // arr = [2, 1, 3] shuffle(arr); // arr = [3, 1, 2] // ...

Can you use math random on array?

random() Let's write a function to return a random element from an array. We can use Math. random() to generate a number between 0–1 (inclusive of 0, but not 1) randomly.

How do you randomly select an array in Python?

Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.


1 Answers

Just use Array#sample:

[:foo, :bar].sample # => :foo, or :bar :-) 

It is available in Ruby 1.9.1+. To be also able to use it with an earlier version of Ruby, you could require "backports/1.9.1/array/sample".

Note that in Ruby 1.8.7 it exists under the unfortunate name choice; it was renamed in later version so you shouldn't use that.

Although not useful in this case, sample accepts a number argument in case you want a number of distinct samples.

like image 113
Marc-André Lafortune Avatar answered Oct 17 '22 07:10

Marc-André Lafortune