Randomly draw 5 cards from the playing cards, and judge whether it is a straight, that is, whether the 5 cards are consecutive (interview questions)

Randomly draw 5 cards from the playing cards to determine whether it is a straight, that is, whether these 5 cards are consecutive 2-10 digits themselves, A is 1, J is 11, Q is 12, K is 13, and Big and small kings can be regarded as any number

 

Analyze this question:

  The big and small kings can be used as any number, so it is recorded as 0

  Use php array for processing, put the incoming 5 numbers into the array

  Get the number of occurrences of each number in an array:

    The number of 0 is n, and n cannot be greater than 2

    Others cannot appear more than 1 time, and if it exceeds, it cannot be a 5-place straight (there is ambiguity here);

  After removing duplicates and 0s, determine the relationship between the number m of the remaining numbers and the difference df,

  If the difference df <= the remaining number m + 0 times n -1, then these 5 numbers are straight

 

Code example:

 1 function isStraight($num1, $num2, $num3, $num4, $num5){
 2     $startNumArr = [$num1, $num2, $num3, $num4, $num5];
 3     $numCountStatic = array_count_values($startNumArr);
 4     $zeroCount = 0;
 5     foreach ($numCountStatic as $num => $count) {
 6         if( $num === 0 ) {
 7              if ( $count > 2 ) {
 8                  return  false ;
 9              }
 10              $zeroCount = $count ;
 11          } else  if ( $count >1 ) {
 12              return  false ; // here There is an ambiguity, if the repeated numbers do not affect the composition of the straight, remove the judgment 
13          }
 14      }
 15      $uniqNumArr = array_unique ( $startNumArr );
 16     sort($uniqNumArr);
17     if ($uniqNumArr['0'] === 0) {
18         array_shift($uniqNumArr);
19     }
20     return(count($uniqNumArr)+$zeroCount-1 >= max($uniqNumArr)-min($uniqNumArr));
21 }
22 
23 var_dump(isStraight(6,3,7,4,5));

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325561217&siteId=291194637