Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shifting array elements to right?

Tags:

c#

I can't use a built-in function for this, I must use my own logic.

I've done element shifting to the left side, but the right side doesn't work for me. Not sure why.

My method for left:

public int[] shiftLeft(int[] arr) {
    int[] demo = new int[arr.length];
    int index = 0;
    for (int i = 0; i < arr.length - 1; i++) {
        demo[index] = arr[i + 1];
        index++;
    }
    return demo;
}

and my attempt for the right shifting:

public int[] shiftRight(int[] arr) {
    int[] demo = new int[arr.length];
    int index = 0;
    for (int i = arr.length - 1; i >= 0; i--) {
        demo[index] = arr[(i - 1 > 0) ? i - 1 : 0];
        index++;
    }
    return demo;
}

What am I doing wrong?

By shifting I mean:

you have an array, 1 2 3 4 5 6
Shifting it to left by one: 2 3 4 5 6 1
Shifting it to right by one: 6 1 2 3 4 5

like image 761
Artemkller545 Avatar asked Jan 27 '14 15:01

Artemkller545


3 Answers

//right shift with modulus
for (int i = 0; i < arr.length; i++) {
    demo[(i+1) % demo.length] = arr[i];
}
like image 147
Robert Fricke Avatar answered Oct 17 '22 14:10

Robert Fricke


LINQ solution, just to add some diversity.

static int[] LeftShift(int[] array)
{            
    // all elements except for the first one... and at the end, the first one. to array.
    return array.Skip(1).Concat(array.Take(1)).ToArray();
}

static int[] RightShift(int[] array)
{
    // the last element (because we're skipping all but one)... then all but the last one.
    return array.Skip(array.Length - 1).Concat(array.Take(array.Length - 1)).ToArray();
}

Probably not recommended if performance matters (for large arrays).

I realize that the OP is not supposed to use a "built-in function".

like image 39
Konrad Morawski Avatar answered Oct 17 '22 13:10

Konrad Morawski


The easiest way to go:

public int[] shiftLeft(int[] arr) 
{
    int[] demo = new int[arr.Length];

    for (int i = 0; i < arr.Length - 1; i++) 
    {
        demo[i] = arr[i + 1];
    }

    demo[demo.Length - 1] = arr[0];

    return demo;
}

public int[] shiftRight(int[] arr) 
{
    int[] demo = new int[arr.Length];

    for (int i = 1; i < arr.Length; i++) 
    {
        demo[i] = arr[i - 1];
    }

    demo[0] = arr[demo.Length - 1];

    return demo;
}
like image 12
MarcinJuraszek Avatar answered Oct 17 '22 13:10

MarcinJuraszek