nik nik - 2 months ago 7
C# Question

Stack array in reverse order

I m trying to create an array wich consists of an input array (length=N) and the same array in reverse order so that the output array is length (2N). Like if input = {1,2,3} then output={1,2,3,3,2,1}

This is what I tried:

public static double[] stack(double[] input)
{
int N = input.Length;
var z = new double[2 * N];
input.CopyTo(z, 0);
Array.Reverse(input).CopyTo(z, N);

return z;
}


But this throws an error (Operator cannot be applied to void type). where am I going wrong please? Is this the fastest approach?

Answer

The Reverse method modifies the the array that you pass into it and returns void. Try this:

public static double[] stack(double[] input)
{
    int N = input.Length;        // assuming input = { 1, 2, 3 }
    var z = new double[2 * N];   // z = { 0, 0, 0, 0, 0, 0 }
    input.CopyTo(z, 0);          // z = { 1, 2, 3, 0, 0, 0 }
    input.CopyTo(z, N);          // z = { 1, 2, 3, 1, 2, 3 }
    Array.Reverse(z, N, N);      // z = { 1, 2, 3, 3, 2, 1 }

    return z;
}
Comments