2012-10-15 62 views
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] 
] 
+3

什么是你的代码的目标是什么? –

+0

对于'print_r($ this-> items)'还有'print_r($ ret)''''''''''这样我就可以理解输入和期望的输出了。' – Baba

+0

@Ofir Baruch我添加了这段代码的目标对我的问题。 –

回答

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

我已将此代码的目标添加到我的问题中。 –

+0

我认为网站上的答案是存在的。现在我无法查看它,也许以后。但是如果你搜索一下,很可能你会找到它。 – hakre