I agree about the cheap sorting. Your first post was a little bit ambiguous about whether you were talking about 2 sorts (once by value, once by suit) or a 2-level nested sort (by value and then by suite within each value, or vice versa). I just wanted to point out pitfalls of the 2-level sort.
I think you can iterate once and solve both questions in O(n). There are a lot of ways to solve this one. if your deck of cards were laid out the right way, you may be able to sort them by deck position instead and solve both at once. if it were a-kS a-kh a-kC a-kd layout, sorted by deck order, its a flush if the max and min card are in the same block, and a straight if max - min = 5, right? |
First of all, a nitpick: I think you mean it's a straight if max - min = 4. Simple off-by-one mistake we've all made.
But beyond that, I am a little bit confused, and I don't think the check for straights is as simple as you suggest. I think this is what you are saying:
The deck of cards is represented by integer values 0 - 51. Each suit is represented by 13 values mapping to ranks 2 - Ace:
Spades: 0 - 12
Hearts: 13 - 25
Clubs: 26 - 38
Diamonds: 39 - 51 |
If your hand has values 16, 18, 19, 20, 23, you would have a flush in hearts because all the values are between 13 and 25. (Incidentally, you can quickly determine this by dividing (integer division) each value by 13, and the result is the same for all cards.)
If my assumption so far is correct, then I don't understand how you use this for a quick check for a straight. Say you have 2S, 3d, 4C, 5C and 6h (I believe that's values 0, 40, 28, 29 and 17). This is a straight, however max - min == 40 and (max%13) - (min%13) == 1. From this layout, you cannot easily determine what ranks you have. You really need to sort the cards by rank and then make sure you have 5 consecutive values. This means that not only max - min == 4, but none of the ranks match.
The way I suggested above (array of ranks containing counts for each) will allow you for checks of straights as well as 2-, 3- and 4-of-a-kind.