【发布时间】:2021-12-03 11:22:48
【问题描述】:
在某种程度上,递归实现对我来说是一个令人困惑的主题。我想了解如何将正常方法精确地“翻译”为递归方法,经过一些研究后我仍然有点困惑,尤其是在第一步(递归停止的地方)。
这个任务是左右旋转一个数组:
[TestCase(new[] { 1, 2 }, new[] { Direction.Left, Direction.Left, Direction.Right }, ExpectedResult = new[] { 2, 1 })]
我不想在此使用linq,我们可以使用Array.Copy 和indices 代替我的标准方法。
这是我要翻译的代码:
public static int[] Shift(int[] source, Direction[] directions)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (directions is null)
{
throw new ArgumentNullException(nameof(directions));
}
if (directions.Length == 0)
{
return source;
}
else
{
for (int i = 0; i < directions.Length; i++)
{
switch (directions[i])
{
case Direction.Left:
var temp1 = source[0];
for (var j = 0; j < source.Length - 1; j++)
{
source[j] = source[j + 1];
}
source[source.Length - 1] = temp1;
break;
case Direction.Right:
var temp2 = source[source.Length - 1];
for (int j = source.Length - 1; j > 0; j--)
{
source[j] = source[j - 1];
}
source[0] = temp2;
break;
default:
throw new InvalidOperationException($"Incorrect {directions[i]} enum value.");
}
}
return source;
}
}
这是我关于单独编程递归的小代码:
public static int[] Shift(int[] source, Direction[] directions)
{
if (source is null || directions is null)
{
throw new ArgumentNullException(nameof(source));
}
ShiftRecursively(source, source.Length, directions, directions.Length);
}
public static int ShiftRecursively(int[] sourceShift, int n, Direction[] currentDirection, int iterations)
{
if (iterations == 0)
{
}
if (currentDirection == Direction.Left)
{
// Handle "left" shift.
}
else if (currentDirection == Direction.Right)
{
// Handle "right" shift.
}
else
{
throw new InvalidOperationException($"Incorrect {currentDirection} enum value.");
}
}
【问题讨论】:
-
“递归实现对我来说是一个令人困惑的主题” - 要了解递归,您需要了解递归......
-
这正是我在这里发帖的原因,以了解实践中的递归并有足够好的示例供以后参考。
-
嗯,...我认为这根本不是一个使用递归的好例子。事实上,10 次中有 9 次,我将递归重构为非递归,而不是反过来。但无论如何......你在这里有一个数组来应用你的班次和要应用的操作列表。现在我要改变的是两件事:它应该返回排列后的数组,
iterations不应该倒数......我会试着写一个答案.. -
旁注:我可能会通过只取左右移位的网络来优化
-
@Charlieface 我完全同意实际的例子是有问题的,但 OP 的重点是“如何递归”,......所以我想我们需要通过这个镜头来看待它。
标签: c# arrays recursion enums rotation