Home > database >  Array rollover using generics
Array rollover using generics

Time:08-28

How can I modify this answer class using generics? Here I am shifting each element right by one index and the last element is moved to the first index.

internal class Answer
{
    public static int[] Rollover(int[] B, int K)
    {
        for (int j = 0; j < K; j  )
        {
            int lastelement = B[B.Length - 1];
            for (int i = B.Length - 1; i > 0; i--)
            {
                B[i] = B[i - 1];
            }
            B[0] = lastelement;
        }
        return B;
    }
}

CodePudding user response:

You can just add a generic parameter, and then change int to T.

public static T[] Rollover<T>(T[] B, int K)
{
    for (int j = 0; j < K; j  )
    {
        T lastelement = B[B.Length - 1];
        for (int i = B.Length - 1; i > 0; i--)
        {
            B[i] = B[i - 1];
        }
        B[0] = lastelement;
    }
    return B;
}

This is using a naive double-loop. A better solution would be to just use Array.Copy

public static T[] Rollover<T>(T[] B, int K)
{
    var temp = new T[K];
    Array.Copy(B, 0, temp, 0, K);
    Array.Copy(B, K, B, 0, B.Length - K);
    Array.Copy(temp, 0, B, K, K);
    return B;
}

To shift the other way you need to flip the positions

public static T[] Rollover<T>(T[] B, int K)
{
    var temp = new T[B.Length - K];
    Array.Copy(B, K, temp, 0, B.Length - K);
    Array.Copy(B, 0, B, K, K);
    Array.Copy(temp, 0, B, 0, B.Length - K);
    return B;
}

CodePudding user response:

public static T[] Rollover<T>(T[] B, int K)
{
    for (int j = 0; j < K; j  )
    {
        T lastelement = B[B.Length - 1];
        for (int i = B.Length - 1; i > 0; i--)
        {
            B[i] = B[i - 1];
        }
        B[0] = lastelement;
    }
    return B;
}
  • Related