php 二维数组 列求和,PHP for for循环中的循环.尝试对多个数组列求和以获得组合...

您可以使用递归或直接嵌套循环,但是当使用组合或排列时,可能性的总数可能会爆炸并变成一个巨大的数字,消耗大量内存到您无法运行代码的程度.使用迭代器是交换cpu效率以提高内存效率的好方法.这是我写的迭代器.

class CartesianProductIterator implements Iterator {

protected $iterators;

function __construct(array $iters) {

$this->iterators = $iters;

}

function rewind() {

foreach ($this->iterators as $it) {

$it->rewind();

}

}

function current() {

$values = array();

foreach ($this->iterators as $it) {

$values[] = $it->current();

}

return $values;

}

function key() {

return null;

}

function next() {

/*

loop them in reverse, but exclude first

why? example, odometer: 55199

you always check the rightmost digit first to see if incrementing it would roll it over and need to be "rewound" to 0,

which causes the digit to the left to increase as well, which may also cause it to roll over as well, and so on...

looping in reverse operates from right column to the left.

we dont rewind the first column because if the leftmost column is on its last element and needs to roll over

then this iterator has reached its end, and so rewind() needs to be explicitly called

*/

for ($i = count($this->iterators) - 1; $i > 0; --$i) {

$it = $this->iterators[$i];

$it->next();

if ($it->valid()) {

// were done advancing because we found a column that didnt roll over

return;

} else {

$it->rewind();

}

}

//if execution reached here, then all of the columns have rolled over, so we must attempt to roll over the left most column

$this->iterators[0]->next();

}

function valid() {

return $this->iterators[0]->valid();

}

}

然后用它作为

$iterators = array();

foreach ($a as $columnNumber => $values) {

$iterators[] = new ArrayIterator($values);

}

foreach (new CartesianProductIterator($iterators) as $combo) {

// combo has 1 value from each of the ArrayIterators we instantiated

printf("summing %s = %d\n", join('+', $combo), array_sum($combo));

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值