# How do I calculate the probability of getting a flush?

  ClearAll["*"]

deck = Sort[
Join[Range[102, 114], Range[202, 214], Range[302, 314], Range[402, 414]]]
Length[deck]

holeCards =
Sort[RandomChoice[deck, 2]] (*selects two random cards from our deck*)

communityDeck =
DeleteCases[deck,
Alternatives @@
holeCards] (*creates a new deck and removes the holeCards*)
Length[communityDeck]

orderQ[card1_, card2_] := card1 < card2;
valueSort[hand_] := Sort[hand, orderQ]

cohands = Subsets[communityDeck, {5}] // Map[Join[#, holeCards] &]
sortedHands = valueSort /@ cohands

(* A pair *)

pair0Q[{___, x_, x_, ___}] := True;(* a pair*)
pair0Q[{___, x_, x_, x_, ___}] := False;
pair0Q[{___, x_, x_, ___, y_, y_, ___} /; x != y] := False;
pair0Q[{___}] := False;
pairQ[hand_] := pair0Q[Sort[Mod[hand, 100]]]

Count[sortedHands, _ ?(pairQ)]/Length[sortedHands]

(* Two Pairs *)

twoPairQ[{___, x_, x_, ___}] := False;
twoPairQ[{___, x_, x_, x_, ___}] := False;
twoPairQ[{___, x_, x_, ___, y_, y_, ___} /; x != y] := True;(*two pairs*)
twoPairQ[_] := False;
pair2Q[hand_] := twoPairQ[Sort[Mod[hand, 100]]]

Count[sortedHands, _ ?(pair2Q)]/Length[sortedHands]

(* Straight Flush *)

straightFlusQ[h_] :=
MatchQ[h - h[], {0, 1, 2, 3, 4, _, _}] ||
MatchQ[h - h[], {_, 0, 1, 2, 3, 4, _}] ||
MatchQ[h - h[], {_, _, 0, 1, 2, 3, 4}]

Count[sortedHands, _ ?(straightFlusQ)]/Length[sortedHands]

(* Flush *)



This is my code. The deck has 52 cards in total. 2 cards are randomly chosen and act as holecards. the deck is returned in subsets of 5 for all possible combinations. the holecards are inserted back into each subset of 5 becoming subsets of 7. How do I write a code for the flush which is 5 random cards of the same suit?

• RandomChoice[deck, 2]] can return duplicates, use RandomSample. Also this works sortedHands = Sort /@ cohands Sep 22, 2021 at 19:52
• Suits are being encoded as the first digit, you can extract it e.g. IntegerDigits // First gives 3, and count the number of occurrences. {102, 113, 203, 302, 305, 306, 412} // Map[IntegerDigits /* First] // Counts. Sep 22, 2021 at 20:06
• How does your set-up which involves 5 of 7 cards differs from what is described at en.wikipedia.org/wiki/Poker_probability ? I assume that the 5-car flush is based on the optimal selection of 5 from 7 cards.
– JimB
Sep 23, 2021 at 21:12
• Your code seems to have the objective of finding the probability of a resulting poker resulting (a pair, straight flush, flush, etc.) given the two particular hole cards selected. Is that what you want? That's different from the probability of obtaining a flush with 7 cards.
– JimB
Sep 24, 2021 at 3:18

flushQ[hand_] := MatchQ[hand/100 // Floor, {___, x_, x_, x_, x_, x_, ___}]
`