打印出从列表的Y元素中选择的X个不同对象的所有组合

时间:2010-11-08 03:36:11

标签: ruby combinations poker

例如,52张扑克牌中的5张牌= 2598960种组合 我如何实际显示所有这些组合?

查找号码的代码很简单:

def binomial_coef(total,subset)
  factorial(total) / (factorial(subset) * factorial(total - subset))
end

def factorial(n)
  n.downto(1).inject(:*)
end

# different 5 card poker hand combinations
cards = 52
hand_number = 5

puts binomial_coef(cards, hand_number)

关于打印出所有实际组合的解决方案的任何想法?
例如:

  

1,2,3,4,5
  1,2,3,4,6
  等

甚至帮助开始。 谢谢!

3 个答案:

答案 0 :(得分:6)

您需要Array#combination

cards = (1..52).to_a
hand_number = 5
cards.combination(hand_number).to_a

=> [[1,2,3,4,5],[1,2,3,4,6],...]

答案 1 :(得分:1)

(1..52).to_a.combination(5)

答案 2 :(得分:1)

puts (1..52).to_a.combination(5).to_a.inspect