You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 如何将数组左右旋转的迭代实现改写为递归版本

实现思路

  • 迭代转递归的核心是把循环计数器转换为递归的终止触发条件,每次递归仅处理一个步骤,待处理次数归零时直接返回结果
  • 移位操作不用嵌套循环,用Array.Copy优化性能,符合你要求不使用LINQ的限制
  • 递归全程直接操作原数组,和你原有迭代逻辑的行为保持一致

现有框架问题修正

  1. 入口Shift方法缺少返回值,调用递归方法后需要将结果返回
  2. ShiftRecursively返回值类型错误,不需要返回int,直接返回操作后的int数组即可
  3. 入参currentDirection是整个方向数组,需要通过索引定位当前递归轮次要处理的方向,不能直接和枚举值比较
  4. 空参数校验逻辑有问题,原有判断如果source或者directions为null都只抛source的空异常,需要分开校验

完整实现代码

using System;

// 假设Direction枚举已提前定义
public enum Direction
{
    Left,
    Right
}

public static class ArrayShift
{
    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;

        return ShiftRecursively(source, directions, directions.Length);
    }

    // 调整递归方法入参,去掉冗余的数组长度参数(可直接从source取),返回值改为int[]
    private static int[] ShiftRecursively(int[] source, Direction[] directions, int remainingSteps)
    {
        // 递归终止条件:没有待处理的方向,直接返回当前数组
        if (remainingSteps == 0)
            return source;

        // 取当前轮次要处理的方向
        var currentDir = directions[remainingSteps - 1];

        // 执行移位操作
        switch (currentDir)
        {
            case Direction.Left:
                var first = source[0];
                Array.Copy(source, 1, source, 0, source.Length - 1);
                source[^1] = first;
                break;
            case Direction.Right:
                var last = source[^1];
                Array.Copy(source, 0, source, 1, source.Length - 1);
                source[0] = last;
                break;
            default:
                throw new InvalidOperationException($"Incorrect {currentDir} enum value.");
        }

        // 递归处理剩余步骤,剩余步数减1
        return ShiftRecursively(source, directions, remainingSteps - 1);
    }
}

测试用例验证

你给出的测试用例[1,2] + [Left, Left, Right]执行过程:

  1. 第一步处理Right:数组变为[2,1]
  2. 第二步处理Left:数组变为[1,2]
  3. 第三步处理Left:数组变为[2,1]
    最终结果和预期完全一致。

内容的提问来源于stack exchange,提问作者Linascts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:57:02