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 に答える