【问题标题】:C#, Rotate a List to the Right by specified placesC#,将列表向右旋转指定位置
【发布时间】:2016-07-19 07:17:11
【问题描述】:

我正在尝试将列表向右旋转特定数量的位置。我认为数组(或列表)旋转可以看作是一个圆形,这意味着从末端掉落的元素会环绕到开头,反之亦然。一个很好的例子可能是如果我们有一个数组或列表,然后我们将它向右旋转三个位置,结果如下:

初始数组(或列表):20、30、40、50、60、70

向右旋转 3 个位置:50、60、70、20、30、40。

根据我对这个概念的了解,我已经编写了一些代码。我想知道,手动执行此操作的正确方法是什么(无需任何花哨的代码或 LINQ),因为它将帮助我更好地理解它。

我要的是手动方法来解决这个问题,而不是任何花哨的东西。

public void Test8(List<int> items, int places)
{
    int[] copy = new int[items.Count];
    items.CopyTo(copy, 0);

    for (int i = 0; i < items.Count; i++)
    {
        int RotateRight = (i + places) % items.Count;
        items[i] = copy[RotateRight];

    }

}

【问题讨论】:

标签: c# arrays rotation


【解决方案1】:

这是LinqSkip()Take() 的方法。

List<int> iList = new List<int>() { 20, 30, 40, 50, 60, 70 };
int rotate = 3;
List<int> lResult = iList.Skip(rotate).Concat(iList.Take(rotate)).ToList();

另一种简单循环的方法

int[] items = new int[] { 20, 30, 40, 50, 60, 70 };
int[] result = new int[items.Length];
int rotate = 3;

for (int i = 0; i < items.Length; i++)
{
    result[i] = items[(i+rotate)% items.Length];
}

【讨论】:

  • 如何在循环中使用 items.Count 而不是 items.Length?
  • @Dyrus 使用 .Count() 而不是 .Length 是相同的结果 - 但 .Count()System.Linq.Enumerable 的一部分,您想要一个没有 Linq 的解决方案
猜你喜欢
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多