Say i have a Array like so,
The, Quick, Brown, Fox, Jumps
and i need to move/shift one of the elements to the front so it looks like this
Brown, Fox, Jum开发者_如何转开发ps, The, Quick
How can one sort an array like a revolving door? by moving one element and having the rest follow behind?
Is there an easy method or should i just copy/loop/slice/copy?
Try the following method
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;
}
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;
see this How to shift the start of an array in C#? or
string[] myArray = { "The", "Quick", "Brown", "Fox", "Jumps" };
myArray = myArray.SkipWhile(t => t != "Brown").Concat(myArray.TakeWhile(t => t != "Brown")).ToArray();
You can use Array.Copy
to avoid writing explicit loops. The following code creates a new array instead of modifying the original:
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);
}
}
精彩评论