php - 用递归简化这个方法

标签 php recursion

我需要通过递归来简化这个方法,以消除重复的业务逻辑,但我不知道如何做到这一点:

public function compute()
{
    $ret = array();
    foreach ($this->_items as $item) {
        $ret[] = array($item);
    }
    foreach ($this->_items as $item) {
        foreach ($this->_items as $item2) {
            $tmp = array($item, $item2);
            if (count($tmp) === count(array_unique($tmp))) {
                $ret[] = $tmp;
            }
        }
    }
    foreach ($this->_items as $item) {
        foreach ($this->_items as $item2) {
            foreach ($this->_items as $item3) {
                $tmp = array($item, $item2, $item3);
                if (count($tmp) === count(array_unique($tmp))) {
                    $ret[] = $tmp;
                }
            }
        }
    }
    return $ret;
}

编辑:

此方法应该返回数组元素的所有组合,因此如果您有如下数组:

[a, b, c]

它将返回:

[
    [a],
    [b],
    [c],
    [a, b],
    [a, c],
    [b, a],
    [b, c],
    [a, b, c],
    [a, c, b],
    [b, a, c],
    [b, c, a],
    [c, a, b],
    [c, b, a]
]

最佳答案

对于您的计算,不需要递归来简化您在此处所说的业务逻辑。至少一开始不是。将重复的代码移动到它自己的函数中然后进行处理就足够了。

我还建议将此作为第一步,因为您在这里的执行顺序:

public function compute()
{

    $ret = array();

    foreach ($this->_items as $item) {
        $ret[] = array($item);
    }

    $each = function(array $tmp) use (&$ret) {
        if (count($tmp) === count(array_unique($tmp))) {
            $ret[] = $tmp;
        }
    }

    foreach ($this->_items as $item) {
        foreach ($this->_items as $item2) {
            $each(array($item, $item2));
        }
    }

    foreach ($this->_items as $item) {
        foreach ($this->_items as $item2) {
            foreach ($this->_items as $item3) {
                $each(array($item, $item2, $item3));
            }
        }
    }

    return $ret;
}

关于php - 用递归简化这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12893061/

相关文章:

java - 如何修复: Sudoku solver Stack overflow problem

java - 如何递归获取图形中可以包含循环的所有连接节点?

php - RouteCollection.php 第 219 行中的 Laravel 5.2 MethodNotAllowedHttpException

php - 表单未重新提交

python - 使用递归查看随机列表时如何跟踪偶数的数量

c++ - 为什么类似解决方案的运行时间如此不同?

php - Mysql解释00 :00:00 as 12:00am?

javascript - CHMOD 更改会影响加载到页面的数据吗?

javascript - 提交表单后如何留在页面上

javascript - 具有不同子名称的递归 JSON 对象显示