September September - 2 months ago 12
PHP Question

PHP - Poker algorithm that creates all possible poker combinations

I am currently trying to make a poker algorithm that creates all possible poker combinations with 2 cards. I know that there are 1,326 combinations of starting hands.
So I created my starting deck like this:

$startingDeck = array();
for($i=1; $i <= 13; $i++)
{
for($x=0; $x <= 3; $x++)
{
array_push($startingDeck, array("Value" => $i ,"Color" => $x, "key"=> $i.$x));
}
}


I want now to loop through all the cards and get all possible combinations with 2 cards for example

: value 1 color 1 and value 1 color 2
: value 1 color 1 and value 1 color 3
... etc
: value 2 color 0 and value 1 color 1
: value 2 color 0 and value 1 color 2
... etc


I want to do this for all the combinations that are possible but how.

Answer

You have your starting deck already. The idea is to generate all permutations:

E.g.

   CARD NUMBER
   1 2 3 4 5 6 7 8 9 10 11 12 13 ... 52
 1 o x x x x x x x x  x  x  x  x      x
 2 - o x x x x x x x  x  x  x  x      x
 3 - - o x x x x x x  x  x  x  x      x
 4 - - - o x x x x x  x  x  x  x      x
 5 - - - - o x x x x  x  x  x  x      x
 6 
 7 ......... and so on .........
 8
 9
10
11
12
13
...
52

We have 52 cards in the deck (that's what you generated in $startingDeck):

The x denote the combination that we want to generate. Note that we don't have to generate the lower part of the matrix as the order does not matter in poker as you receive both cards at the same time. We also don't generate the axis as you can't have the same card twice (unless you cheat :)).

The idea now is to use two loops, but let the second loop start depending on the first initial $j depends on $i. That way we do not generate e.g. 2-1, 3-2, 3-1, ... again as we already generated 1-2, 1-3, 2-3, ....

So let's start:

for ($i = 0; i < count($startingDeck); $i++) {
    // Ignore e.g. 2-1, 3-2, as we already generated 1-2, 2-3, and so on...
    for ($j = $i+1; $j < count($startingDeck); $j++) {
       $firstCard = $startingDeck[$i];
       $secondCard = $startingDeck[$j];
       // print my stuff
    }
}

This generates the top matrix. The $i+1 makes sure that we don't generate the diagonal.

I hope that helps.

Comments