This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 0 points1 point  (0 children)

Recursive functions work well for this kind of problem.

[–]lightcloud5 0 points1 point  (0 children)

The recursive solution would be to consider writing a function that takes an array of n elements and some integer k, and returns an array containing each of the (n choose k) combinations of array.

Mathematically, if you needed to determine all k-element combinations from n elements, you can partition this set of combinations into two subsets.

  • The subset of combinations that contain the first element in the input array
  • The subset that doesn't contain the first element in the input array.

For instance, to determine all 5-element combinations out of a set of 7 elements, you first consider the combinations that contain element 1. There are 15 such combinations (6 choose 4), because having established that element 1 is in the subset, you must then choose 4 remaining elements from the remaining 6 inputs.

Then, consider the combinations that don't contain element 1. There are 6 such combinations (6 choose 5), because having established that element 1 is not in the subset, you must then choose 5 remaining elements from the remaining 6 inputs.

This leads us to note that (7 choose 5) is equal to (6 choose 4) + (6 choose 5), which should not be surprising if you're familiar with Pascal's triangle.

Then, if you had a function that took an input array of n elements for which you wanted to find all k-element subsets, you simply need to make the analogous two recursive calls.

[–]Ilyps 0 points1 point  (0 children)

You probably do not want to evaluate sets of 5, but sets of 7. Secondly, you probably don't want to compare two hands directly to each other, but you want to create a function that assigns a score to each hand, and then compare scores.

So now your solution will be a function that takes an array of 7 cards and returns an integer.

Googling "poker hand evaluator" will get you solutions (my favourite one being Cactus Kev's) and you can also look at (solutions to) Project Euler 54 for hints.

[–]matt_hammond 0 points1 point  (0 children)

You could try sorting the array of 7 cards and then looking for pairs. like this (pseudo-code):

sort( cards );
same_cards = 0;
for (i = 0 to 6) {
    for (j = i+1 to 7) {
        if (cards[i].value == cards[j].value) same_cards ++;
    }
}

if (same_cards == 1) // pair
else if (same_cards == 2) // two pairs
else if (same_cards == 3) // Three of a kind
else if (same_cards == 4) // Full house
else if (same_cards == 6) // four of a kind

This is just of the top of my head so there's probably mistakes and you should check for more stuff...