开发者

Print out all combinations of X distinct objects chosen from the Y elements of a list

For instance, 5 cards in a poker hand of 52 cards = 2598960 combinations.

How would I actually display all those com开发者_运维百科binations though?

The code to find the number is easy:

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)

Any ideas on a solution to printing out the all the actual combinations?

eg:

1,2,3,4,5

1,2,3,4,6

etc.

Or even help gettings started. Thanks!


You need 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..52).to_a.combination(5)


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜