2

我需要通过递归来简化此方法以消除重复的业务逻辑,但我无法弄清楚如何做到这一点:

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]
]
4

1 回答 1

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;
}
于 2012-10-15T09:54:04.343 回答