简体   繁体   中英

Get permutation of 4 digits numbers without repetition with all possible combination

function permuteString($str) 
{ 
    $aStr = str_split($str);
    $iSize = count($aStr);
    $aResult = array();
    for ($i = 0; $i < $iSize; ++$i) 
    { 
        $sFirst = array_shift($aStr); 
        $aInner = $aStr; 
        $iInner = count($aInner); 
        for ($j = 0; $j < $iInner; ++$j) 
        { 
            $aResult[] = $sFirst . implode('', $aInner); 
            $sTmp = array_shift($aInner); 
            $aInner[] = $sTmp; 
        } 
        $aStr[] = $sFirst; 
    } 
    return $aResult; 
} 
$userinput = "7290"; 
print_r(permuteString($userinput));
    
[0] => 7290 
[1] => 7902 
[2] => 7029 
[3] => 2907 
[4] => 2079 
[5] => 2790 
[6] => 9072 
[7] => 9720 
[8] => 9207 
[9] => 0729 
[10] => 0297 
[11] => 0972

I get only 12 numbers Are there any probabilities to get more combinations in the given any 4 digits?

$chars = str_split('7290');
sort($chars);

$result = [];

foreach ($chars as $char1) {
  $chars2 = array_diff($chars, [$char1]);
  foreach ($chars2 as $char2) {
    $chars3 = array_diff($chars2, [$char2]);
    foreach ($chars3 as $char3) {
      $chars4 = array_diff($chars3, [$char3]);
      foreach ($chars4 as $char4) {
        $result[] = $char1 . $char2 . $char3 . $char4;
      }
    }
  }
}

print_r($result);

This will print:

Array
(
    [0] => 0279
    [1] => 0297
    [2] => 0729
    [3] => 0792
    [4] => 0927
    [5] => 0972
    [6] => 2079
    [7] => 2097
    [8] => 2709
    [9] => 2790
    [10] => 2907
    [11] => 2970
    [12] => 7029
    [13] => 7092
    [14] => 7209
    [15] => 7290
    [16] => 7902
    [17] => 7920
    [18] => 9027
    [19] => 9072
    [20] => 9207
    [21] => 9270
    [22] => 9702
    [23] => 9720
)

The code will only work for 4 different digits (or characters).

This code allows for any combination of 4 digits, including repeating:

$chars = str_split('7220');
sort($chars);

$result = [];

foreach ($chars as $char1) {
  $chars2 = $chars;
  unset($chars2[array_search($char1, $chars, true)]);
  foreach ($chars2 as $char2) {
    $chars3 = $chars2;
    unset($chars3[array_search($char2, $chars2, true)]);
    foreach ($chars3 as $char3) {
      $chars4 = $chars3;
      unset($chars4[array_search($char3, $chars3, true)]);
      foreach ($chars4 as $char4) {
        $result[] = $char1 . $char2 . $char3 . $char4;
      }
    }
  }
}

$result = array_unique($result);

print_r($result);

This will print:

Array
(
    [0] => 0227
    [1] => 0272
    [2] => 0722
    [3] => 2027
    [4] => 2072
    [5] => 2207
    [6] => 2270
    [7] => 2702
    [8] => 2720
    [9] => 7022
    [10] => 7202
    [11] => 7220
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM