PHP阵列组合 [英] PHP array combinations
问题描述
我有7个号码(1,2,3,4,5,6,7)的数组,我想使对5个号码一样(1,2,3,4,5),(1, 2,3,4,6,),(1,2,3,4,7)。
(1,2,3,4,5)等于(4,5,3,1,2)
I have an array of 7 numbers (1,2,3,4,5,6,7) and I want to make pairs of 5 numbers like (1,2,3,4,5),(1,2,3,4,6,),(1,2,3,4,7) . (1,2,3,4,5) is equal to (4,5,3,1,2)
我想知道是否有在PHP函数或可以做这件事的算法?
我不知道从何处入手。
你能帮助我吗?
I would like to know if there is a function in PHP or any algorithm that can do this ? I have no idea where to start from. Can you help me ?
我希望所有7给定数字(它们是从一个数组拍摄)组合投入5个插槽,不顾秩序
I want all the combinations of 7 given numbers ( they are taken from an array ) put into 5 slots,disregarding order
推荐答案
您可以使用此 HTTP找到了解决办法:// stereofrog。 COM / BLOK /上/ 070910 。
柜面之间的链接断开,这里的code ....
Incase the link goes down here's the code....
class Combinations implements Iterator
{
protected $c = null;
protected $s = null;
protected $n = 0;
protected $k = 0;
protected $pos = 0;
function __construct($s, $k) {
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();
}
function key() {
return $this->pos;
}
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);
}
function next() {
if($this->_next())
$this->pos++;
else
$this->pos = -1;
}
function rewind() {
$this->c = range(0, $this->k);
$this->pos = 0;
}
function valid() {
return $this->pos >= 0;
}
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;
}
}
foreach(new Combinations("1234567", 5) 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
12345 12346 12347 12356 12357 12367 12456 12457 12467 12567 13456 13457 13467 13567 14567 23456 23457 23467 23567 24567 34567
这篇关于PHP阵列组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!