Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve x random elements from an array

I am struggling to write a clean method which when passed an array of strings and x returns a randomised list of array elements totalling x, eg.

def getrandomarrayelements(thearray, howmany)
    return [something]
end

Yes I should submit my existing code, which whilst works is not good, it's 8 lines long and I have a feeling it can be done in one?!

like image 327
creativetechnologist Avatar asked Sep 29 '11 18:09

creativetechnologist


People also ask

How do you generate a random element from 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.

Can array elements be accessed randomly?

An array is a random access data structure, where each element can be accessed directly and in constant time.


1 Answers

In ruby 1.9:

irb(main):001:0> [1,2,3,4,5].sample(3)
=> [2, 4, 5]
irb(main):002:0> [1,2,3,4,5].sample(3)
=> [2, 5, 3]

and for ruby 1.8 something like this:

def sample(arr, n)
  arr.shuffle[0...n]
end

irb(main):009:0> sample([1,2,3,4,5], 3)
=> [5, 1, 3]
irb(main):010:0> sample([1,2,3,4,5], 3)
=> [3, 4, 2]
like image 145
Vasiliy Ermolovich Avatar answered Oct 18 '22 17:10

Vasiliy Ermolovich