2

I have a poker hand and I need to check for three of a kind. Is there a way to see if 3 elements in the vector are the same but the other 2 are different?

E.g.:

hand <- c("Q","Q","6","5","Q")

Should return TRUE for three of a kind.

hand2 <- c("Q","Q","6","6","Q")

...would be a full-house though, and shouldn't be identified as a three of a kind.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
dllmn3
  • 31
  • 1
  • 1
    @RichardScriven - `rle` will require sorting - something like `any(table(hand)==3) & sum(table(hand)==1)==2` will probably do it. – thelatemail Sep 29 '15 at 23:29
  • 1
    Depends on how the cards are indicated. Post an example of a hand that should match and one that shouldn't. – Pierre L Sep 29 '15 at 23:29
  • @PierreLafortune - i've just added an example hand - maybe OP can clarify this is what they want. – thelatemail Sep 29 '15 at 23:30
  • 1
    haha That's nice of you but won't do any good if the hands are written in poker talk. Like this R walk-through https://stat.duke.edu/courses/Spring12/sta104.1/Homework/SimHW1.pdf. If rank and suit are indicated, you must separate them first then use the methods above. – Pierre L Sep 29 '15 at 23:34
  • @PierreLafortune - sure, there's extra considerations in taking into account suits of cards, but the general question of `see if 3 elements in the vector are the same but the other 2 are different` seems perfectly answerable with a simplified example. – thelatemail Sep 29 '15 at 23:41
  • I think it's a major consideration that the OP failed to mention. I'm downvoting their question but upvoting your effort :) – Pierre L Sep 29 '15 at 23:43
  • I already have the hand broken down to just the "values" of 2-10,JQKA so the suits are being ignored now. The actual hand has suits but I used sort(table(hand[,1])) or some sort to separate it, if this makes sense. – dllmn3 Sep 29 '15 at 23:49

1 Answers1

6

Using table and some logic checking should get you there:

tab <- table(hand)
#hand
#5 6 Q 
#1 1 3
any(tab==3) & (sum(tab==1)==2)
#[1] TRUE

tab <- table(hand2)
#hand2
#6 Q 
#2 3 
any(tab==3) & (sum(tab==1)==2)
#[1] FALSE

This works because any will look across the table, checking if there are any card values repeated 3 times. The tab==1 part of the function checks if any values in the table are equal to 1, returning TRUE or FALSE for each part of the table. sum-ing TRUE/FALSE values is equivalent to summing 1/0 values, so if you check that you had a sum of 2 for the other cards, you can be sure they are different.

thelatemail
  • 91,185
  • 12
  • 128
  • 188