c# - 在 C# 中,在不使用 LINQ 的情况下将列表向右旋转指定的位数?

标签 c# arrays sorting

我想在不使用 LINQ 的情况下以手动方式将项目列表向右旋转指定数量的位置,我如何才能做到这一点?

我想我不明白如何处理/解决这个问题。到目前为止,这是我尝试过的方法。

这个问题的一个明显例子可能是这样的: 初始数组(或列表):20,30,40,50,60,70 向右旋转3位:50,60,70,20,30,40

      public void Test(List<int> items, int places)
    {
        items.RemoveAt(places);
        items.Add(places);

    }

最佳答案

下面的结果:

20,30,40,50,60,70 
60,70,20,30,40,50  (Rotate 2) 
50,60,70,20,30,40  (Rotate 3)

如果您打算将每个元素 n 个索引向左移动,只需将行 list[i] = copy[index]; 替换为 list[index] = copy[i] ;

然后你会得到这些结果:

20,30,40,50,60,70 
40,50,60,70,20,30  (Rotate 2) 
50,60,70,20,30,40  (Rotate 3)

这是一个简单的通用方法:

static void RotateList<T>(IList<T> list, int places)
{
    // circular.. Do Nothing
    if (places % list.Count == 0)
        return;

    T[] copy = new T[list.Count];
    list.CopyTo(copy, 0);

    for (int i = 0; i < list.Count; i++)
    {
        // % used to handle circular indexes and places > count case
        int index = (i + places) % list.Count;

        list[i] = copy[index];
    }
}

用法:

List<int> list = new List<int>() { 20, 30, 40, 50, 60, 70 };
RotateList(list, 3);

或者由于我是扩展方法的忠实粉丝,您可以创建一个:

(通过使用 IList,此方法也适用于数组)

public static class MyExtensions
{
    public static void RotateList<T>(this IList<T> list, int places)
    {
        // circular.. Do Nothing
        if (places % list.Count == 0)
            return;

        T[] copy = new T[list.Count];
        list.CopyTo(copy, 0);

        for (int i = 0; i < list.Count; i++)
        {
            int index = (i + places) % list.Count;

            list[i] = copy[index];
        }
    }

用法:

List<int> list = new List<int>() { 20, 30, 40, 50, 60, 70 };
list.RotateList(12); // circular - no changes

int[] arr = new int[] { 20, 30, 40, 50, 60, 70 };

arr.RotateList(3);

关于c# - 在 C# 中,在不使用 LINQ 的情况下将列表向右旋转指定的位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38449665/

相关文章:

java - 从 Control 数组按类型获取 UI 元素?

java - 使用比较器的最短寻道时间优先算法

python - 根据每个字符串中的子字符串对字符串列表进行排序

c# - 对 XDocument 中的所有元素进行排序

c# - Comparer<T> 类有什么用?

c# - 如何从打开的流中检测文件重命名

c# - 使用 Script# 编译代码(独立)

javascript - 将平面数组的人转换为 JavaScript 中的嵌套谱系树

java - 如何从 JTextArea 获取字节数组?

C# TCP NetworkStream 缺少几个字节的数据