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?!
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.
An array is a random access data structure, where each element can be accessed directly and in constant time.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With