Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

สร้างชุดค่าผสมทั้งหมดของขนาดเฉพาะจากชุดเดียวใน 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' และทุกอักขระในสตริงนั้นจะถูกเชื่อมกับอักขระอื่นๆ ทุกตัว ฟังก์ชัน 'การสุ่มตัวอย่าง' ถูกเรียกด้วยพารามิเตอร์ (สตริง ขนาดของสตริง และอาร์เรย์)