Search code examples
rubycombinationspoker

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 combinations 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!


Solution

  • 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],...]