在C#中是否存在用于将列表元素向左或向右移动指定数量的代码?
这是一个棘手的代码,它需要一些时间来编写和测试特殊情况,我宁愿重用一些存在的东西。
谢谢
发布于 2013-08-12 14:49:34
类似于shift left的内容...
public static void ShiftLeft<T>(List<T> lst, int shifts)
{
for (int i = shifts; i < lst.Count; i++)
{
lst[i - shifts] = lst[i];
}
for (int i = lst.Count - shifts; i < lst.Count; i++)
{
lst[i] = default(T);
}
}对于右移来说,这有点棘手,因为我们必须反向复制
public static void ShiftRight<T>(List<T> lst, int shifts)
{
for (int i = lst.Count - shifts - 1; i >= 0; i--)
{
lst[i + shifts] = lst[i];
}
for (int i = 0; i < shifts; i++)
{
lst[i] = default(T);
}
}使用数组就简单多了,因为Array有非常强大的方法:
public static void ShiftLeft<T>(T[] arr, int shifts)
{
Array.Copy(arr, shifts, arr, 0, arr.Length - shifts);
Array.Clear(arr, arr.Length - shifts, shifts);
}
public static void ShiftRight<T>(T[] arr, int shifts)
{
Array.Copy(arr, 0, arr, shifts, arr.Length - shifts);
Array.Clear(arr, 0, shifts);
}是的,If sourceArray and destinationArray overlap, this method behaves as if the original values of sourceArray were preserved in a temporary location before destinationArray is overwritten.是防止Array.Copy越级的。
发布于 2013-08-12 15:05:56
下面是几个扩展方法,它们可以将列表向右或向左移动。这些方法将返回一个列表。
public static class ShiftList
{
public static List<T> ShiftLeft<T>(this List<T> list, int shiftBy)
{
if (list.Count <= shiftBy)
{
return list;
}
var result = list.GetRange(shiftBy, list.Count-shiftBy);
result.AddRange(list.GetRange(0,shiftBy));
return result;
}
public static List<T> ShiftRight<T>(this List<T> list, int shiftBy)
{
if (list.Count <= shiftBy)
{
return list;
}
var result = list.GetRange(list.Count - shiftBy, shiftBy);
result.AddRange(list.GetRange(0, list.Count - shiftBy));
return result;
}
}这里有一个如何调用它的示例。
class Program
{
static void Main(string[] args)
{
List<int> test = Enumerable.Range(0, 10).ToList();
test = test.ShiftLeft(1);
PrintList(test);
Console.WriteLine("");
PrintList(test.ShiftRight(2));
Console.ReadLine();
}
private static void PrintList(List<int> test)
{
for (int i = 0; i < test.Count; i++)
{
Console.WriteLine(test[i]);
}
}
}发布于 2021-08-15 20:33:18
通过将第一部分和第二部分翻转来保持简单。同样的事情,但对于ShiftRight来说是另一种方式
public static List<int> ShiftLeft(List<int> a, int d)
{
if (a.Count > d)
{
var beginingPart = a.GetRange(0, d);
var remainingPart = a.GetRange(d, a.Count - d);
return remainingPart.Concat(beginingPart).ToList();
}
else if (a.Count < d)
{
var mod = d % a.Count;
if (mod != 0)
{
return rotLeft(a, mod);
}
}
return a;
}https://stackoverflow.com/questions/18180958
复制相似问题