2010-11-08 62 views
1

例如,52張撲克牌中的5張牌= 2598960個組合。
雖然我會如何顯示所有這些組合?打印出從列表中的Y元素中選擇的X個不同對象的所有組合

找到數的代碼很簡單:

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

甚至幫助gettings開始。 謝謝!

回答

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],...] 
+3

使用塊的形式,以避免在內存中存儲整個事情:'(1..52).to_a.combination(5){|卡片|把cards.join','}' – 2010-11-08 09:25:36

+0

@Lars Haugseth,不錯! – Nakilon 2010-11-08 09:34:23

1
(1..52).to_a.combination(5) 
1
puts (1..52).to_a.combination(5).to_a.inspect 
相關問題