我试图将带有for循环的方法转换为递归,作为编码Kata实践的一部分(尝试用递归方法解决问题)。逻辑中没有什么,但
以下是方法定义:
// Original method with for loop
public IEnumerable<Tuple<int, int>> GetElementWithLargestDeltaOnTimeline(int[] a)
{
int runningLindex = 0;
int currLValue = a[0];
int runningHindex = 1;
int currHvalue = a[1];
int currDelta = 0;
for (int i = 1; i < a.Length - 1; i++)
{
if (a[i] < currLValue)
{
currLValue = a[i];
runningLindex = i;
}
for (int j = runningLindex + 1; j < a.Length; j++)
{
if ((a[j] - currLValue) > currDelta)
{
currDelta = a[j] - currLValue;
runningHindex = j;
currHvalue = a[j];
}
}
}
yield return new Tuple<int, int>(currLValue, runningLindex);
yield return new Tuple<int, int>(currHvalue, runningHindex);
}
递归 -
// Trying above method to convert to recursive,
// Note - It may not be correct *shy* but the problem is why it's not doing anything(not step through/logging)
public IEnumerable<Tuple<int, int>> GetElementWithLargestDeltaOnTimelineRec
(int[] a, int i, int j, int runningLindex, int currLValue, int runningHindex, int currHvalue, int currDelta)
{
Console.WriteLine("Iteration i-{0}: j-{1} runningLindex-{2} currLValue-{3} runningHindex-{4} currHvalue-{5} currDelta-{6}"
, i, j, runningLindex, currLValue, runningHindex, currHvalue, currDelta);
if (i < a.Length)
{
if (a[i] < currLValue)
{
currLValue = a[i];
runningLindex = i;
}
if (j < a.Length)
{
if ((a[j] - currLValue) > currDelta)
{
currDelta = a[j] - currLValue;
runningHindex = j;
currHvalue = a[j];
}
GetElementWithLargestDeltaOnTimelineRec(a, i, j++, runningLindex, currLValue, runningHindex, currHvalue, currDelta);
}
}
else
{
yield return new Tuple<int, int>(currLValue, runningLindex);
yield return new Tuple<int, int>(currHvalue, runningHindex);
}
GetElementWithLargestDeltaOnTimelineRec(a, i++, runningLindex + 1, runningLindex, currLValue, runningHindex, currHvalue, currDelta);
yield break;
}
主要 -
public class Program
{
public static void Main()
{
var a = new[] { 10, 9, 3, 6, 7, 8, 15, 10, 6 };
var val = new StockManager();
var result = val.GetElementWithLargestDeltaOnTimelineRec(a, 0, 0, 0, a[0], 1, a[1], 0);
}
}
问题 -
其他信息 - .Net 4.5,Visual Studio 2013
我也尝试在不同的机器上运行此代码(只是为了验证我的VS实例是否有问题)。
答案 0 :(得分:3)
返回GetElementWithLargestDeltaOnTimelineRec
的方法有一点小技巧。你应该枚举它们!
不应在其自身内部调用IEnumerable
,而应该枚举它并返回其元素或存储结果以供稍后使用。 foreach (var e in GetElementWithLargestDeltaOnTimelineRec(...))
yield return e;
在他们枚举之前什么都不做。
var innerResult = GetElementWithLargestDeltaOnTimelineRec(...);
或者
innerResult
并以某种方式使用 xAxis: {
type: 'datetime'
},
导致它被枚举。