从数组中获取 x 个随机元素

10

我正在努力编写一个干净的方法,当传递一个字符串数组和x时,返回一个随机排列的数组元素列表,总数为x,例如:

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

是的,我应该提交我的现有代码,虽然它能够工作,但代码长度为8行,我感觉这可以用一行代码实现?!


1
那是洗牌和发牌。这方面有很多先前的技术,不是吗? - Craig Stuntz
1个回答

27

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

对于 Ruby 1.8,可以这样做:

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]

在1.9版本中,它会返回唯一的元素,忘记在我的问题中提到了吗? - creativetechnologist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接