Problem rotating an array

2

I have the following problem, the algorithm teacher has asked us to "improve" the following code and that its operation is the same:

// Método original
static char[] RotateOld(char[] src, int by)
{
    char[] output = new char[src.Length]; int n = by;

    if (by < 0)
        by = src.Length - by;

    for (int i = 0; i < src.Length; i++)
    {
        output[n] = src[i];
        if (n + 1 >= src.Length)
            n = 0;
        else if (n < 0)
            n = by + src.Length;
        else
            n++;
    }
    return output;
}

The exercise requires trying to remove as many conditions that are executed within the code (preferably all) for greater "performance", this is what I have done:

// Método nuevo.
static char[] Rotate(char[] src, int by)
{
    char[] output = new char[src.Length]; 

    for (int i = 0; i < src.Length; i++)
    {
        output[((i + (by * -1)) + src.Length) % src.Length] = src[i];
    }
    return output;
}

However, when executing it, the following happens, in the first code ( RotateOld() ), if the parameter by is positive, the array rotates to the right, that is, the position src[0] happens to be src[1] , but in my "improved" version the opposite occurs, src[0] becomes src[srcLength - 1] .

This is an example of the original function:

char[] Input = { 'H', 'o', 'l', 'a' };

char[] Result = RotateOld(Input, 1); // Esto da como resultado: 'a', 'H', 'o', 'l'

And my version:

char[] result = Rotate(Input, 1); // Esto da como resultado: 'o', 'l', 'a', 'H'

Why for this?

    
asked by NaCl 05.05.2016 в 17:52
source

1 answer

1

You must rotate to the right, so you do not need to multiply the value of by by -1 . Remove that multiplication of the code and it will be as you expect:

output[(i + by + src.Length) % src.Length] = src[i];
    
answered by 05.05.2016 / 18:31
source