views:

94

answers:

4

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, Jumps, 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?

A: 

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;
}
JaredPar
you guys are awesome thanks again for all the answers.
shift de array
A: 
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;
Darin Dimitrov
Oh man, that was fast i feel like a moron now that is way simpler than what i was going to do.thanks
shift de array
+1  A: 

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();
Akyegane
ok two lines is good.
shift de array
A: 

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);
    }
}
Mark Byers