避免递归
我有一个方法,它根据它可以容纳的设备数量为我提供所需的盒子数量。目前我已经使用递归实现了这个逻辑
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。
I have a method, which gives me the required number of Boxes based on number of devices it can hold.Currently i have implemented this logic using recursion
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;
}
Is there any better method to implement the same logic without using recursion. Because this method is making my application very slow for cases when number of devices exceeds
50000.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
怎么样:
我不明白为什么你会使用递归甚至基于队列的解决方案来解决这样的问题。
How about this:
I don't see why you would use recursion or even a queue based solution for something like this.
我想我一定是误会了。如果您需要确定需要多少个盒子来容纳给定数量的设备,这很简单:
...其中 ceil 是一个运算,它采用任何小数值并向上舍入到最接近的整数。 (几乎所有环境都有该操作。刚刚注意到您的 .Net 标记;它是 Math.Ceiling;如果您使用 JScript.Net,它也是
Math.ceil
因为这是 JavaScript 的标准部分。)如果您需要纯粹使用整数数学:
I think I must be misunderstanding. If you need to determine how many boxes are needed to hold a given number of devices, it's trivial:
...where
ceil
is an operation that takes any fractional value and rounds up to the nearest integer. (Nearly all environments have that operation. Just noticed your .Net tag; it's Math.Ceiling in .Net; if you're using JScript.Net it's alsoMath.ceil
because that's a standard part of JavaScript.)If you need to do it purely with integer math:
是的,您可以使用队列来避免递归。像这样:
但看起来在你的情况下你根本不需要递归/队列。查看其他答案。
Yes, you can use Queue to avoid the recursion. Smth like this:
But it looks like in your case you don't need recursion/queue at all. See other answers.
您的编译器很可能已经将此尾递归转换为循环。
It is quite likely that your compiler have already transformed this tail recursion into a loop.