Jump to content

C# Offsetting an array by a value

AJTerminator

Hello, I was just wondering how I would offset an array by some amount of positions and have it wrap around, so for example, if an array had the values: "ABCDEF" then if it was offset by 3, it would be "FEDABC". Thanks

Link to comment
Share on other sites

Link to post
Share on other sites

You could have a temporary placeholder variable. 

 

For example 


 

char temp;

char[] arr = {a, b, c};

int offset =1;

 

temp = arr [0];

arr[0] = arr[1];

arr[1]= arr[2];

arr[2]= temp;

 

 

to make the code reusable you’d use loops & mathematics but you get the concept. 

Link to comment
Share on other sites

Link to post
Share on other sites

Here a sample approach if you want to do it with a List of generics or simply want 1 solution for either array and list :

 

public static void RotateList<T>(this List<T> source, int rotateTo)
{
    var tempList = new List<T>();

    tempList.AddRange(source.Skip(rotateTo).Take(source.Count - rotateTo));
    tempList.AddRange(source.Take(rotateTo));

    source.Clear();
    source.AddRange(tempList);
}

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×