2010-03-15 143 views
0

我有一个方法,这给了我所需要的数量根据设备数量盒可以hold.Currently我一直在使用递归避免递归

private uint PerformRecursiveDivision(uint m_oTotalDevices,uint m_oDevicesPerBox, ref uint BoxesRequired) 
     { 
      if (m_oTotalDevices< m_oDevicesPerBox) 
      { 
       BoxesRequired = 1; 
      } 
      else if ((m_oTotalDevices- m_oDevicesPerBox>= 0) && (m_oTotalDevices- m_oDevicesPerBox) < m_oDevicesPerBox) 
      { 
       //Terminating condition 
       BoxesRequired++; 
       return BoxesRequired; 
      } 
      else 
      { 
       //Call recursive function 
       BoxesRequired++; 
       return PerformRecursiveDivision((m_oTotalDevices- m_oDevicesPerBox), m_oDevicesPerBox, ref BoxesRequired); 
      } 
      return BoxesRequired; 
     } 

实现这个逻辑有没有实现任何更好的方法同样的逻辑没有使用递归。因为这种方法使得我的应用程序在设备数量超过 50000的情况下非常缓慢。

回答

0

是的,您可以使用Queue来避免递归。如下所示:

private void ProcessNonRecursively(string data) 
    { 
     Queue<string> queue = new Queue<string>(); 

     // Enque initiali data. 
     queue.Enqueue(data); 

     while (queue.Count > 0) 
     { 
      // Get current data. 
      string currentData = queue.Dequeue(); 

      // Process it here... 

      // Enque all data to be processed instead of calling the recursion. 
      foreach (string newData in someNewDataAfterProcessing) 
      { 
       queue.Enqueue(newData); 
      } 
     } 
    } 

但它看起来像你的情况,你根本不需要递归/队列。查看其他答案。

+0

他可以避免循环周期... – Kiril 2010-03-15 09:01:29

+0

不,不是队列:堆栈(在一般情况下)。 – 2010-03-15 09:10:10

3

如何:

int boxesRequired = m_oTotalDevices/m_oDevicesPerBox; 
if (m_oTotalDevices % m_oDevicesPerBox > 0) 
    boxesRequired++; 

return boxesRequired; 

我不明白你为什么会使用递归甚至队列基础的解决方案这样的事情。

2

我想我一定是误会。如果您需要确定多少盒持有设备的给定数量的需要,这是微不足道的:

boxesRequired = ceil(totalDevices/devicesPerBox) 

...其中ceil是采取任何分数值,向上舍入为最接近的整数的操作。 (几乎所有的环境都有这个操作,只注意到了你的.Net标记;它在.Net中为Math.Ceiling;如果你使用的是JScript.Net,那么它也是Math.ceil,因为这是JavaScript的标准部分)。它纯粹与整数运算:

boxesRequired = totalDevices/devicesPerBox 
if totalDevices mod devicesPerBox <> 0 then 
    increment boxesRequired 
endif 
+0

快速手指+1! – Kiril 2010-03-15 09:00:53

0

它很可能你的编译器已经转变了这个尾递归转换到一个循环。