2010-03-15 100 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

它很可能你的編譯器已經轉變了這個尾遞歸轉換到一個循環。