PHP 数组组合
给你一个由 7 个数字组成的数组 (1,2,3,4,5,6,7) 。目标是从该数组中找到 5 个数字的所有可能组合。每个组合必须是唯一的,这意味着不允许重复。例如,(1,2,3,4,5) 和 (5,4,3,2,1) 被视为相同的组合。
解
一个可能的解决方案涉及使用 Combinations 类,该类实现 Iterator 接口并提供一种迭代给定数字的所有可能组合的方法。它的工作原理如下:
class Combinations implements Iterator { protected $c = null; // Combination of numbers protected $s = null; // Source array protected $n = 0; // Number of elements in the array protected $k = 0; // Number of elements in each combination protected $pos = 0; // Current position of the iterator function __construct($s, $k) { // Initialize the class properties if(is_array($s)) { $this->s = array_values($s); $this->n = count($this->s); } else { $this->s = (string) $s; $this->n = strlen($this->s); } $this->k = $k; $this->rewind(); } // Return the current key function key() { return $this->pos; } // Return the current value function current() { $r = array(); for($i = 0; $i < $this->k; $i++) $r[] = $this->s[$this->c[$i]]; return is_array($this->s) ? $r : implode('', $r); } // Move to the next combination function next() { if($this->_next()) $this->pos++; else $this->pos = -1; } // Rewind to the first combination function rewind() { $this->c = range(0, $this->k); $this->pos = 0; } // Check if the iterator is valid (at a valid position) function valid() { return $this->pos >= 0; } // Move to the next combination (internal function) protected function _next() { $i = $this->k - 1; while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i) $i--; if($i < 0) return false; $this->c[$i]++; while($i++ < $this->k - 1) $this->c[$i] = $this->c[$i - 1] + 1; return true; } } // Create a Combinations object for the given array and number of elements per combination $combinations = new Combinations("1234567", 5); // Iterate over all possible combinations and print them out foreach($combinations as $substring) echo $substring, ' ';
此代码产生以下输出:
12345 12346 12347 12356 12357 12367 12456 12457 12467 12567 13456 13457 13467 13567 14567 23456 23457 23467 23567 24567 34567
以上是如何使用 PHP 从 7 个数字(1、2、3、4、5、6、7)的数组中生成 5 个数字的所有唯一组合?的详细内容。更多信息请关注PHP中文网其他相关文章!