开发者

Retrieve x random elements from an array

开发者 https://www.devze.com 2023-04-09 16:02 出处:网络
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.

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 getrandomarr开发者_运维问答ayelements(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?!


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

精彩评论

暂无评论...
验证码 换一张
取 消