Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c# - How to rotate an array by moving N elements from end to start?

I am trying to move a number of elements in an array to the end using C#.
I have an Array (in my case a char-array), and a integer z. Now I want to move z chars to the end of another array, the other chars should move to the beginning of the array.
So if the first array is {'H','E','L','L','O'} and z = 3, the new array should be {'L','O','H','E','L'}.

I hope somebody can help me.

Best attempt:

static char[] rotate(char[] c, int z)
{
    char[] nc = new char[c.Length];
    for (int i = z; i < c.Length; i++)
    {
        nc[i - z] = c[i];
    }
    for (int i = 0; i < z; i++)
    {
        nc[i + z] = c[i];
    }
    return nc;
}
question from:https://stackoverflow.com/questions/65868794/how-to-rotate-an-array-by-moving-n-elements-from-end-to-start

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem was with the wrong indexing that was in your code.
Here's the fixed version:

static char[] rotate(char[] c, int z)
{
    char[] nc = new char[c.Length];
    for (int i = z; i < c.Length; i++)
    {
        nc[i - z] = c[i];
    }
    for (int i = 0; i < z; i++)
    {
        nc[i + z - 1] = c[i]; // <-- Change here
    }
    return nc;
}

However, a better solution could be the usage of doubly-linked lists that handles movement of the array items to start/end better. .NET implementation of doubly-linked list is LinkedList Class. And here you can find some examples of how to do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...