使用递归简化此方法

时间:2012-10-15 09:46:17

标签: 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]
]

1 个答案:

答案 0 :(得分:2)

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

我也建议这是第一步,因为你在这里执行的顺序是:

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;
}