我试图通过指定的位数旋转一个项目列表,而不使用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);
}
Run Code Online (Sandbox Code Playgroud)
结果如下:
20,30,40,50,60,70
60,70,20,30,40,50 (Rotate 2)
50,60,70,20,30,40 (Rotate 3)
Run Code Online (Sandbox Code Playgroud)
如果你的意思是每个元素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)
Run Code Online (Sandbox Code Playgroud)
这是一个简单的工作通用方法:
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];
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
List<int> list = new List<int>() { 20, 30, 40, 50, 60, 70 };
RotateList(list, 3);
Run Code Online (Sandbox Code Playgroud)
或者因为我是扩展方法的忠实粉丝,你可以创建一个:
(通过使用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];
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
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);
Run Code Online (Sandbox Code Playgroud)