gpt4 book ai didi

PHP数组组合

转载 作者:IT王子 更新时间:2023-10-28 23:48:59 26 4
gpt4 key购买 nike

我有一个包含 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),因此只有其中一个应该包含在输出中。

我想知道 PHP 中是否有函数或任何算法可以做到这一点?我不知道从哪里开始。你能帮帮我吗?

我想将 7 个给定数字(它们取自数组)的所有组合放入 5 个槽中,不考虑顺序。

最佳答案

您可以使用此处找到的解决方案 http://stereofrog.com/blok/on/070910

万一链接失效,这里是代码....

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

345

关于PHP数组组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3742506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com