假设我有一个像这样的数组,
The, Quick, Brown, Fox, Jumps
我需要将其中一个元素移动/移动到前面,所以看起来像这样
Brown, Fox, Jumps, The, Quick
如何将数组排序为旋转门?通过移动一个元素并让其余元素落后?
是否有简单的方法或我应该复制/循环/切片/复制?
答案 0 :(得分:1)
尝试以下方法
public void ShiftRevolvingDoor(ArrayList list, int count) {
while ( count > 0 ) {
ShiftRevolvingDoor(list);
count--;
}
}
public void ShiftRevolvingDoor(ArrayList list) {
if ( list.Count < 2 ) {
return;
}
int lastIndex = list.Count - 1;
object first = list[0];
for ( i = 0; i < lastIndex; i++) {
list[i] = list[i+1];
}
list[lastIndex] = first;
}
答案 1 :(得分:1)
ArrayList list = new ArrayList();
list.Add("The");
list.Add("Quick");
list.Add("Brown");
list.Add("Fox");
list.Add("Jumps");
ArrayList newList = new ArrayList();
int index = 2;
for (int i = index; i < list.Count; i++)
{
newList.Add(list[i]);
}
for (int i = 0; i < index; i++)
{
newList.Add(list[i]);
}
list = newList;
答案 2 :(得分:1)
请参阅此How to shift the start of an array in C#?或
string[] myArray = { "The", "Quick", "Brown", "Fox", "Jumps" };
myArray = myArray.SkipWhile(t => t != "Brown").Concat(myArray.TakeWhile(t => t != "Brown")).ToArray();
答案 3 :(得分:1)
您可以使用Array.Copy
来避免编写显式循环。以下代码创建一个新数组,而不是修改原始数组:
T[] rotate<T>(T[] a, int index)
{
T[] result = new T[a.Length];
Array.Copy(a, index, result, 0, a.Length - index);
Array.Copy(a, 0, result, a.Length - index, index);
return result;
}
public void Run()
{
string[] words = { "The", "Quick", "Brown", "Fox", "Jumps" };
string[] result = rotate(words, 2);
foreach (string word in result)
{
Console.WriteLine(word);
}
}