由單個集合生成特定大小的所有組合,PHP 程式碼如下


要從單個集合中生成所有特定大小的組合,程式碼如下 −

示例

 線上演示

function sampling($chars, $size, $combinations = array()) {
   # in case of first iteration, the first set of combinations is the same as the set of characters
   if (empty($combinations)) {
      $combinations = $chars;
   }
   # size 1 indicates we are done
   if ($size == 1) {
      return $combinations;
   }
   # initialise array to put new values into it
   $new_combinations = array();
   # loop through the existing combinations and character set to create strings
   foreach ($combinations as $combination) {
      foreach ($chars as $char) {
         $new_combinations[] = $combination . $char;
      }
   }
   # call the same function again for the next iteration as well
   return sampling($chars, $size - 1, $new_combinations);
}
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);

輸出

這將產生以下輸出 −

array(9) { [0]=> string(2) "aa" [1]=> string(2) "ab" [2]=> string(2) "ac" [3]=> string(2) "ba" [4]=> string(2) "bb" [5]=> string(2) "bc" [6]=> string(2) "ca" [7]=> string(2) "cb" [8]=> string(2) "cc" }

第一次迭代表示要顯示的相同字元集。如果大小為 1,則顯示組合。陣列初始化為“new_combinations”,並使用“forloop”對其進行迴圈,並且該字串中的每個字元都與其他每個字串聯在一起。函式“sampling”使用引數(字串、字串的大小和陣列)呼叫。

更新於: 09-Apr-2020

1K+ 檢視次數

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.